Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
70fbbe22df | ||
|
|
ed2dffb091 | ||
|
|
27c465491f | ||
|
|
91d768afd2 | ||
|
|
3b40598ced | ||
|
|
160a8977e6 | ||
|
|
8c6ee6ca89 | ||
|
|
6cb05ebc37 | ||
|
|
c8450b9908 | ||
|
|
6f1f2623a3 | ||
|
|
52342a9b8e | ||
|
|
a3b64d8c8d | ||
|
|
6d532fc719 | ||
|
|
0c745fdb0c | ||
|
|
fd24e844b0 | ||
|
|
88c57558e1 | ||
|
|
fbdfbaa8d3 | ||
|
|
27c86e052a | ||
|
|
3864f0ffd0 | ||
|
|
5a0c277993 | ||
|
|
fb11fedb76 | ||
|
|
c15d622ba2 | ||
|
|
2b220bc5d9 | ||
|
|
2d744d283b | ||
|
|
76f7832522 | ||
|
|
c60d49fb8c | ||
|
|
d0af46b445 |
No files matched your search
+20
-7
@@ -1,10 +1,23 @@
|
||||
# EKB MCP 配置示例
|
||||
# hose-use 环境变量示例(全部可选,不设置即使用默认值)
|
||||
|
||||
# 企业配置目录(默认 ./enterprises)
|
||||
# EKB_CONFIG_DIR=./enterprises
|
||||
# 企业配置目录覆盖(默认 ~/.config/hose-use/enterprises,目录权限 0700)
|
||||
# HOSE_ENTERPRISES_DIR=~/.config/hose-use/enterprises
|
||||
|
||||
# Token 缓存目录(默认 ~/.cache/ekb-mcp)
|
||||
# EKB_TOKEN_CACHE_DIR=~/.cache/ekb-mcp
|
||||
# 全局配置文件覆盖(默认 ~/.config/hose-use/config.json)
|
||||
# HOSE_CONFIG_FILE=~/.config/hose-use/config.json
|
||||
|
||||
# 默认 API 基础 URL
|
||||
# EKB_BASE_URL=https://app.ekuaibao.com
|
||||
# 账号与 Token 缓存文件覆盖(默认位于 ~/.config/hose-use/,文件权限 0600)
|
||||
# HOSE_ACCOUNTS_FILE=~/.config/hose-use/accounts.json
|
||||
# HOSE_TOKENS_FILE=~/.config/hose-use/tokens.json
|
||||
|
||||
# 本地状态目录(审批引擎 / Token 缓存 / 守护进程状态,默认 ~/.config/hose-use)
|
||||
# HOSE_STATE_DIR=~/.config/hose-use
|
||||
|
||||
# 本地 HTTP Daemon(默认 127.0.0.1,建议保持回环地址)
|
||||
# HOST=127.0.0.1
|
||||
# PORT=8888
|
||||
# HOSE_HTTP_TOKEN=<访问令牌>
|
||||
# HOSE_HTTP_CORS_ORIGIN=http://localhost:7788
|
||||
|
||||
# MCP Server 总开关(默认关闭)
|
||||
# HOSE_USE_MCP_ENABLED=true
|
||||
@@ -18,9 +18,9 @@ jobs:
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
with:
|
||||
bun-version: latest
|
||||
bun-version: 1.3.14
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.11",
|
||||
"version": "0.8.13",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -4,37 +4,44 @@
|
||||
|
||||
## 项目定位
|
||||
|
||||
合思/易快报(ekuaibao)企业费控与平台自建应用的高性能 CLI 命令行工具与底层 SDK(兼具轻量 MCP 适配能力):
|
||||
合思/易快报(ekuaibao)企业费控与平台自建应用的高性能 CLI 命令行工具与底层 SDK(兼具轻量 MCP 与本地 HTTP 网关适配能力):
|
||||
|
||||
- **CLI 工具 (`hose-use` / `hose-aipro`)**:面向运维/实施/开发者的高性能交互与自动化命令行
|
||||
- **底层 SDK (`src/domains/` & `src/core/`)**:纯函数式、零 UI 绑定的业务 API 与换票能力
|
||||
- **MCP Server (`src/server.ts`)**:精简核心适配器(保留核心切换与扫描能力)
|
||||
- **Agent Skill (`skills/hose-use`)**:内嵌 AI 智能体技能标准定义(支持 `hose-use skill install` 一键分发)
|
||||
- **CLI 工具 (`hose-use` / `hose-aipro`)**:面向运维/实施/开发者与 AI Agent 的高性能交互与确定性审批命令行
|
||||
- **底层 SDK (`src/domains/` & `src/core/`)**:纯函数式、零 UI 绑定的业务编排、API 传输、SQLite 持久化与换票能力
|
||||
- **MCP Server (`src/server.ts`)**:极简核心单工具网关(`hose_cli` -> `runCli`)
|
||||
- **本地 HTTP Daemon (`src/http/`)**:常驻 HTTP API 网关与交互式 OpenAPI 文档服务
|
||||
- **构建与分发内嵌层 (`src/packaging/`)**:OpenAPI 规范与 Agent Skill (`skills/hose-use`) 内嵌分发、二进制运行态自省
|
||||
|
||||
## 架构总览
|
||||
|
||||
```text
|
||||
CLI (src/cli.ts) / MCP (src/server.ts)
|
||||
│ │
|
||||
└──────────┬─────────┘
|
||||
▼
|
||||
domains/ (业务编排与平台引擎)
|
||||
│
|
||||
▼
|
||||
core/ (认证、配置与 HTTP 基础设施)
|
||||
├── auth/ Token 登录、换票与缓存
|
||||
├── config/ 多账号与企业配置管理
|
||||
└── http/ HTTP 客户端工厂
|
||||
CLI (src/cli.ts) / AI PRO (src/aipro-cli.ts) / MCP (src/server.ts) / HTTP (src/http/)
|
||||
│ │ │ │
|
||||
└─────────────────────┴───────────┬───────────┴───────────────────┘
|
||||
▼
|
||||
cli/registry.ts & cli/commands/* (命令分发与视图渲染)
|
||||
│
|
||||
▼
|
||||
domains/ (14 个业务子域:编排 tools/services + 传输 api)
|
||||
│
|
||||
▼
|
||||
core/ (严格基础设施白名单)
|
||||
├── auth/ Token 登录、双通道续期、多账号与跨进程 Token 缓存
|
||||
├── config/ 多账号与企业配置管理(0600 权限与字段归一化)
|
||||
├── http/ 语义化 HTTP 客户端工厂(Session / OpenAPI / Unity / Piper)
|
||||
├── cache/ L1 内存 + L2 SQLite 多级协同缓存
|
||||
├── db/ 统一 SQLite 连接单例与结构化版本迁移 (migrations)
|
||||
└── errors.ts 统一异常语义体系 (EkbError 子类)
|
||||
```
|
||||
|
||||
核心原则:
|
||||
|
||||
- `server.ts` 只做 MCP 协议适配(tools 注册、参数解析、结果序列化)
|
||||
- 业务编排统一放在 `domains/*/tools.ts`
|
||||
- `domains/*/api.ts` 只负责 HTTP 请求和响应校验
|
||||
- `core/auth/` 负责各子域的 Token 获取与刷新
|
||||
- `core/config/` 负责本地认证配置读写
|
||||
- `core/errors.ts` 负责统一异常语义
|
||||
- `server.ts` 只做单工具 MCP 协议适配(`hose_cli` 委托 `src/cli/runner.ts`)
|
||||
- `src/cli/registry.ts` 作为顶层命令、别名与常驻属性的唯一声明式注册表
|
||||
- 业务编排统一放在 `domains/*/tools.ts` 或 `domains/*/services.ts`
|
||||
- `domains/*/api.ts` 只负责 HTTP 请求和响应校验,严禁被入口层直接导入
|
||||
- `core/` 严格保持基础设施窄白名单(`auth/`, `cache/`, `config/`, `db/`, `errors.ts`, `http/`),构建产物与 Skill 分发统一置于 `src/packaging/`
|
||||
- 所有本地 SQLite 持久化(审批引擎、多级缓存、事件轮询去重、工作流错误指纹)统一收敛至 `core/db/` 并通过版本迁移管理
|
||||
|
||||
## 文档索引
|
||||
|
||||
@@ -52,35 +59,37 @@ CLI (src/cli.ts) / MCP (src/server.ts)
|
||||
新增或调整功能时,优先遵循下面这条链路:
|
||||
|
||||
1. 先明确 `domains/` 的业务边界
|
||||
2. 再实现 `core/auth/` 或复用现有认证层
|
||||
3. 再接入 `server.ts` 注册 MCP tools
|
||||
2. 再实现 `core/auth/` 或复用现有认证与 `core/db/` 基础设施
|
||||
3. 再接入 `src/cli/commands/*` 并在 `src/cli/registry.ts` 注册
|
||||
4. 最后更新对应层级文档,而不是把细节补到根目录
|
||||
|
||||
同步更新顺序:
|
||||
|
||||
1. `domains/*/api.ts` — 传输层
|
||||
2. `domains/*/tools.ts` — 业务层
|
||||
3. `server.ts` — 注册 tools
|
||||
2. `domains/*/tools.ts` / `services.ts` — 业务编排层
|
||||
3. `cli/commands/*` & `cli/registry.ts` — CLI 命令层
|
||||
4. 对应目录下的 `README*.md`
|
||||
5. 只有在总纲真的变化时,才更新本文件
|
||||
|
||||
## 分层导入约束
|
||||
## 分层导入约束(由 `src/cli/architecture-boundaries.test.ts` 自动化强制卡点)
|
||||
|
||||
以下导入关系严格禁止:
|
||||
|
||||
| 禁止方向 | 说明 |
|
||||
|---|---|
|
||||
| `server.ts -> domains/*/api.ts` | Server 不得直接调用 API 层 |
|
||||
| `(cli/** \| http/** \| server.ts \| cli.ts \| aipro-cli.ts) -> domains/*/api.ts` | 任何入口层不得绕过 `tools.ts`/`services.ts` 直接调用 API 传输层 |
|
||||
| `domains/** -> (cli/** \| http/** \| server.ts \| cli.ts \| aipro-cli.ts)` | 域层必须保持纯 SDK 零 UI/入口绑定 |
|
||||
| `core/** -> (domains/** \| cli/** \| http/** \| server.ts \| cli.ts \| aipro-cli.ts)` | Core 基础设施层严禁向上反向依赖业务域或入口层 |
|
||||
|
||||
正确路径:
|
||||
|
||||
- `server.ts -> domains/*/tools.ts -> domains/*/api.ts -> core/http/*`
|
||||
- `domains/*/tools.ts -> core/auth/*`
|
||||
- `entrypoints -> cli/registry.ts -> cli/commands/* -> domains/*/(tools|services).ts -> domains/*/api.ts -> core/http/*`
|
||||
- `domains/*/(tools|services).ts -> core/{auth,cache,config,db,errors,http}`
|
||||
|
||||
## 异常规则
|
||||
|
||||
- `domains/` 层只抛 `EkbError` 子类(定义在 `core/errors.ts`)
|
||||
- `server.ts` 统一负责 MCP error 映射
|
||||
- `domains/` 层只抛 `EkbError` 子类(定义在 `core/errors.ts`:`NotLoggedInError`, `AuthenticationError`, `PermissionError`, `NotFoundError`, `ValidationError`, `BusinessError`, `EkbApiError`)
|
||||
- `src/cli/errors.ts` 统一按 `EkbError` 子类与状态码映射 CLI 退出码与下一步恢复建议
|
||||
- tools 文件里不要重复做局部异常体系
|
||||
|
||||
## 文档规则
|
||||
@@ -100,7 +109,7 @@ CLI (src/cli.ts) / MCP (src/server.ts)
|
||||
2. **分支命名规范**:
|
||||
- 特性分支:`feat/<feature-name>` 或 `codex/issue-<id>-<name>`
|
||||
- 发布分支:`codex/release-v<X.Y.Z>` 或 `release/v<X.Y.Z>`
|
||||
- 维护优化:`chore/<task-name>` 或 `fix/<issue-name>`
|
||||
- 维护优化:`chore/<task-name>`、`refactor/<task-name>` 或 `fix/<issue-name>`
|
||||
3. **Pull Request 提交流程**:
|
||||
- 本地必须验证:`bun test && bun run check`(全绿方可提交);
|
||||
- 推送分支至远端:`git push origin <branch>`;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.8.11)
|
||||
# hose-use (v0.8.13)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
|
||||
Vendored
+706
-669
File diff suppressed because it is too large.
Load diff
@@ -105,7 +105,7 @@ CLI 入口保持在 `platform` 命令域,支持 `list`、`get`、`entities`、
|
||||
|
||||
```bash
|
||||
bun run export:workflow-schema
|
||||
# 输出:schemas/workflow-schema.json
|
||||
# 输出:specs/workflow-schema.json
|
||||
```
|
||||
|
||||
## 工作流数据结构要点
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# enterprises/ 目录说明
|
||||
|
||||
本目录仅保留 `example.json`(企业配置字段示例,随 git 分发),用于说明企业配置文件的格式。
|
||||
|
||||
**运行时数据不在这里。** CLI 实际读取的企业配置目录为 `~/.config/hose-use/enterprises/`(可用环境变量 `HOSE_ENTERPRISES_DIR` 覆盖),文件权限强制 `0600`、目录权限 `0700`,且已被 `.gitignore` 排除。解析逻辑见 `src/core/config/loader.ts`。
|
||||
+5
-1
@@ -1,12 +1,16 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.11",
|
||||
"version": "0.8.13",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
"hose-use": "src/cli.ts",
|
||||
"hose-aipro": "src/cli.ts"
|
||||
},
|
||||
"packageManager": "bun@1.3.14",
|
||||
"engines": {
|
||||
"bun": ">=1.3.14"
|
||||
},
|
||||
"scripts": {
|
||||
"cli": "bun run src/cli.ts",
|
||||
"aipro": "bun run src/aipro-cli.ts",
|
||||
|
||||
@@ -52,13 +52,13 @@ skillContent = skillContent.replace(/\(v[\d.]+\)/g, `(v${nextVersion})`);
|
||||
writeFileSync(skillPath, skillContent);
|
||||
console.log("✓ Updated skills/hose-use/SKILL.md");
|
||||
|
||||
// 4. openapi/openapi.yaml
|
||||
const openapiPath = join(ROOT, "openapi", "openapi.yaml");
|
||||
// 4. specs/openapi/openapi.yaml
|
||||
const openapiPath = join(ROOT, "specs", "openapi", "openapi.yaml");
|
||||
if (existsSync(openapiPath)) {
|
||||
let openapiContent = readFileSync(openapiPath, "utf-8");
|
||||
openapiContent = openapiContent.replace(/version: [\d.]+/g, `version: ${nextVersion}`);
|
||||
writeFileSync(openapiPath, openapiContent);
|
||||
console.log("✓ Updated openapi/openapi.yaml");
|
||||
console.log("✓ Updated specs/openapi/openapi.yaml");
|
||||
}
|
||||
|
||||
// 4.5 .zcode-plugin/plugin.json
|
||||
|
||||
@@ -6,8 +6,8 @@ import YAML from "yaml";
|
||||
|
||||
type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
|
||||
|
||||
const inputFile = resolve("openapi/openapi.yaml");
|
||||
const outputFile = resolve("dist/openapi.json");
|
||||
const inputFile = resolve("specs/openapi/openapi.yaml");
|
||||
const outputFile = resolve("specs/openapi.json");
|
||||
|
||||
const bundled = bundle(inputFile, new Set());
|
||||
|
||||
|
||||
@@ -7,8 +7,8 @@ const packageVersion = (JSON.parse(readFileSync(join(root, "package.json"), "utf
|
||||
const expected: Array<[string, string | undefined]> = [
|
||||
["package.json", packageVersion],
|
||||
[".zcode-plugin/plugin.json", readJsonVersion(".zcode-plugin/plugin.json")],
|
||||
["openapi/openapi.yaml", readFileSync(join(root, "openapi/openapi.yaml"), "utf8").match(/^\s+version:\s+([^\s]+)\s*$/m)?.[1]],
|
||||
["dist/openapi.json", readJsonVersion("dist/openapi.json", ["info", "version"])],
|
||||
["specs/openapi/openapi.yaml", readFileSync(join(root, "specs/openapi/openapi.yaml"), "utf8").match(/^\s+version:\s+([^\s]+)\s*$/m)?.[1]],
|
||||
["specs/openapi.json", readJsonVersion("specs/openapi.json", ["info", "version"])],
|
||||
];
|
||||
|
||||
const mismatches = expected.filter(([, value]) => value !== packageVersion);
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
WorkflowSchema,
|
||||
} from "../src/domains/platform/types.js";
|
||||
|
||||
const OUTPUT_DIR = join(process.cwd(), "schemas");
|
||||
const OUTPUT_DIR = join(process.cwd(), "specs");
|
||||
const OUTPUT_FILE = join(OUTPUT_DIR, "workflow-schema.json");
|
||||
|
||||
function writeJson(path: string, data: unknown): void {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
|
||||
const outputFile = resolve("dist/raw-hose-openapi.json");
|
||||
const outputFile = resolve("specs/openapi.raw.json");
|
||||
|
||||
function standardResponse(description: string, dataSchema: any) {
|
||||
return {
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
name: hose-use
|
||||
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
||||
metadata:
|
||||
version: 0.8.11
|
||||
version: 0.8.13
|
||||
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
||||
---
|
||||
|
||||
# hose-use (v0.8.11)
|
||||
# hose-use (v0.8.13)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.8.11",
|
||||
"version": "0.8.13",
|
||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||
},
|
||||
"servers": [
|
||||
File renamed without changes.
File renamed without changes.
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.8.11
|
||||
version: 0.8.13
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+72
-1085
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,22 @@
|
||||
# CLI 引擎层说明
|
||||
|
||||
本目录是三个入口(`src/cli.ts` 主 CLI、`src/aipro-cli.ts` AI PRO CLI、`src/server.ts` MCP 网关)共享的命令引擎:声明式注册、参数解析、写防护、输出渲染与错误映射。入口层只做薄壳,业务编排统一在 `domains/`。
|
||||
|
||||
## 文件职责
|
||||
|
||||
- `registry.ts`:`CLI_COMMAND_REGISTRY` 顶层命令唯一声明式注册表(`area` / `aliases` / `standing` 常驻属性 / `handler`)。新增命令先在此注册。
|
||||
- `runner.ts`:`runCli` 分发入口。按注册表查命令;非常驻命令经 `runQueue` 串行化执行,避免并发写冲突。
|
||||
- `parser.ts`:参数解析器(`parseArgs` / `stringOption` / `booleanOption` / `outputOptions`)。
|
||||
- `printer.ts`:输出渲染(`printJson` / `printHelp` / `redactSensitiveText` 敏感信息脱敏)。
|
||||
- `errors.ts`:`classifyCliError` 按 `EkbError` 子类与状态码映射退出码与恢复建议。
|
||||
- `mutation.ts`:写操作统一防护(确认/dry-run 语义),边界由 `mutation-boundaries.test.ts` 强制。
|
||||
- `helpers.ts`:横切运行时助手(`initCorpRuntime` / `requireSelectedCorp` / `getSessionClientForRuntime`)。
|
||||
- `service.ts`:常驻守护进程管理(安装/启停/状态)。
|
||||
- `help.ts`:帮助文本组织。
|
||||
- `commands/`:每个顶层命令域一个 handler 文件,与 `src/domains/` 一一对应;复杂命令(如 `aipro/`)可用子目录形态。
|
||||
- `architecture-boundaries.test.ts`:分层导入约束的机器卡点(入口层禁触 `domains/*/api.ts`、域层禁反向依赖、core 白名单)。
|
||||
|
||||
## 约定
|
||||
|
||||
- handler 统一签名 `(parsed, runtime, options) => Promise<CliResult>`。
|
||||
- 命令文件内部不重复做异常体系,只抛/透传 `EkbError` 子类。
|
||||
@@ -0,0 +1,131 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { readdirSync, readFileSync, statSync } from "node:fs";
|
||||
import { dirname, join, relative, resolve } from "node:path";
|
||||
|
||||
const SRC_ROOT = join(import.meta.dir, "..");
|
||||
|
||||
function collectTsFiles(dir: string, includeTests = false): string[] {
|
||||
const results: string[] = [];
|
||||
for (const entry of readdirSync(dir)) {
|
||||
const full = join(dir, entry);
|
||||
const stat = statSync(full);
|
||||
if (stat.isDirectory()) {
|
||||
results.push(...collectTsFiles(full, includeTests));
|
||||
} else if (full.endsWith(".ts") && (includeTests || !full.endsWith(".test.ts"))) {
|
||||
results.push(full);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
function extractImportSpecifiers(source: string): string[] {
|
||||
const specifiers: string[] = [];
|
||||
const staticImportRe = /(?:import|export)\s+(?:type\s+)?(?:[\s\S]*?\s+from\s+)?["']([^"']+)["']/g;
|
||||
const dynamicImportRe = /import\(\s*["']([^"']+)["']\s*\)/g;
|
||||
|
||||
for (const match of source.matchAll(staticImportRe)) {
|
||||
if (match[1]) specifiers.push(match[1]);
|
||||
}
|
||||
for (const match of source.matchAll(dynamicImportRe)) {
|
||||
if (match[1]) specifiers.push(match[1]);
|
||||
}
|
||||
return specifiers;
|
||||
}
|
||||
|
||||
function resolveImportRelativeToSrc(fromFile: string, specifier: string): string | null {
|
||||
if (!specifier.startsWith(".")) return null;
|
||||
const abs = resolve(dirname(fromFile), specifier).replace(/\.[jt]s$/, "");
|
||||
return relative(SRC_ROOT, abs);
|
||||
}
|
||||
|
||||
describe("Architecture Layering Boundaries", () => {
|
||||
test("Entrypoints (src/cli, src/http, server.ts, cli.ts, aipro-cli.ts) must never import domains/*/api directly", () => {
|
||||
const entrypointFiles = [
|
||||
...collectTsFiles(join(SRC_ROOT, "cli")),
|
||||
...collectTsFiles(join(SRC_ROOT, "http")),
|
||||
join(SRC_ROOT, "server.ts"),
|
||||
join(SRC_ROOT, "cli.ts"),
|
||||
join(SRC_ROOT, "aipro-cli.ts"),
|
||||
];
|
||||
|
||||
const violations: string[] = [];
|
||||
for (const file of entrypointFiles) {
|
||||
const content = readFileSync(file, "utf8");
|
||||
const specifiers = extractImportSpecifiers(content);
|
||||
for (const spec of specifiers) {
|
||||
const targetRel = resolveImportRelativeToSrc(file, spec);
|
||||
if (targetRel && /^domains\/[^/]+\/api$/.test(targetRel)) {
|
||||
violations.push(`${relative(SRC_ROOT, file)} -> ${targetRel}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
|
||||
test("src/domains/ must remain pure SDK and never import from cli, http, or server entrypoints", () => {
|
||||
const domainFiles = collectTsFiles(join(SRC_ROOT, "domains"));
|
||||
const violations: string[] = [];
|
||||
|
||||
for (const file of domainFiles) {
|
||||
const content = readFileSync(file, "utf8");
|
||||
const specifiers = extractImportSpecifiers(content);
|
||||
for (const spec of specifiers) {
|
||||
const targetRel = resolveImportRelativeToSrc(file, spec);
|
||||
if (
|
||||
targetRel &&
|
||||
(targetRel.startsWith("cli/") ||
|
||||
targetRel.startsWith("http/") ||
|
||||
targetRel === "server" ||
|
||||
targetRel === "cli" ||
|
||||
targetRel === "aipro-cli")
|
||||
) {
|
||||
violations.push(`${relative(SRC_ROOT, file)} -> ${targetRel}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
|
||||
test("src/core/ must never depend upward on domains, cli, http, or server entrypoints", () => {
|
||||
const coreFiles = collectTsFiles(join(SRC_ROOT, "core"));
|
||||
const violations: string[] = [];
|
||||
|
||||
for (const file of coreFiles) {
|
||||
const content = readFileSync(file, "utf8");
|
||||
const specifiers = extractImportSpecifiers(content);
|
||||
for (const spec of specifiers) {
|
||||
const targetRel = resolveImportRelativeToSrc(file, spec);
|
||||
if (
|
||||
targetRel &&
|
||||
(targetRel.startsWith("domains/") ||
|
||||
targetRel.startsWith("cli/") ||
|
||||
targetRel.startsWith("http/") ||
|
||||
targetRel === "server" ||
|
||||
targetRel === "cli" ||
|
||||
targetRel === "aipro-cli")
|
||||
) {
|
||||
violations.push(`${relative(SRC_ROOT, file)} -> ${targetRel}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
|
||||
test("src/core/ must only contain whitelisted infrastructure modules", () => {
|
||||
const allowedTopLevel = new Set([
|
||||
"README.core.md",
|
||||
"auth",
|
||||
"cache",
|
||||
"config",
|
||||
"db",
|
||||
"errors.ts",
|
||||
"http",
|
||||
]);
|
||||
const entries = readdirSync(join(SRC_ROOT, "core"));
|
||||
const unexpected = entries.filter((entry) => !allowedTopLevel.has(entry));
|
||||
expect(unexpected).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,299 @@
|
||||
import type { ApprovalRunRecord } from "../../../domains/approval/index.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
import { parseIntegerList, type AiProCommandResult, type AiProExecutionContext } from "./types.js";
|
||||
|
||||
export async function handleAiProScopes(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { parsed, positional, repo, operator, rawArgs } = ctx;
|
||||
const runHandle = stringOption(parsed.options, ["run", "r"]) || positional[1];
|
||||
let runRecord: ApprovalRunRecord | null = null;
|
||||
if (runHandle) {
|
||||
runRecord = repo.getRunByHandle(runHandle);
|
||||
if (!runRecord) {
|
||||
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
|
||||
}
|
||||
}
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "scopes",
|
||||
runId: runRecord?.shortId || runRecord?.id,
|
||||
documentSn: runRecord?.documentSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
summary: runRecord ? `在会话 [${runRecord.shortId}] 查阅规约场景索引` : "查阅规约场景索引",
|
||||
});
|
||||
|
||||
const scopes = repo.listScopes().map((s) => ({
|
||||
索引号: s.index,
|
||||
适用场景: s.scope,
|
||||
}));
|
||||
return { stdout: JSON.stringify(scopes, null, 2) + "\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleAiProRules(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { parsed, positional, repo, operator, rawArgs } = ctx;
|
||||
const runHandle = stringOption(parsed.options, ["run", "r"]);
|
||||
const rawIndexes =
|
||||
stringOption(parsed.options, ["indexes", "index", "i", "scope", "s"]) ||
|
||||
positional[1] ||
|
||||
positional[2];
|
||||
|
||||
let runRecord: ApprovalRunRecord | null = null;
|
||||
if (runHandle) {
|
||||
runRecord = repo.getRunByHandle(runHandle);
|
||||
if (!runRecord) {
|
||||
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
|
||||
}
|
||||
}
|
||||
|
||||
const targetIndexes = parseIntegerList(rawIndexes);
|
||||
const uniqueIndexes = [...new Set(targetIndexes)].sort((a, b) => a - b);
|
||||
if (uniqueIndexes.length === 0) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `请提供具名参数,例如:\n hose-aipro rules --run <runId> --indexes "[1]"\n hose-aipro rules --run <runId> --indexes "[1, 2]"\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const rulesMap = new Map<number, { 编号: number; 适用场景: string; 规则明细: string }>();
|
||||
const notFound: number[] = [];
|
||||
|
||||
for (const idx of uniqueIndexes) {
|
||||
const detail = repo.getScopeDetail(idx);
|
||||
if (!detail) {
|
||||
notFound.push(idx);
|
||||
continue;
|
||||
}
|
||||
for (const r of detail.rules) {
|
||||
if (!rulesMap.has(r.code)) {
|
||||
rulesMap.set(r.code, {
|
||||
编号: r.code,
|
||||
适用场景: detail.scope,
|
||||
规则明细: r.body,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (notFound.length > 0 && rulesMap.size === 0) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 未找到指定索引对应的规约场景: [${notFound.join(", ")}]\n提示: 请先运行 "hose-aipro scopes" 查看所有可用场景索引。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const flattenedRules = Array.from(rulesMap.values()).sort((a, b) => a.编号 - b.编号);
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "rules",
|
||||
runId: runRecord?.shortId || runRecord?.id,
|
||||
documentSn: runRecord?.documentSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
summary: runRecord
|
||||
? `在会话 [${runRecord.shortId}] 查询索引 ${JSON.stringify(uniqueIndexes)} 的规约明细 (${flattenedRules.length} 条)`
|
||||
: `查询索引 ${JSON.stringify(uniqueIndexes)} 的规约明细 (${flattenedRules.length} 条)`,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: JSON.stringify(flattenedRules, null, 2) + "\n",
|
||||
stderr: notFound.length > 0 ? `[WARNING] 部分索引未找到: [${notFound.join(", ")}]\n` : "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleAiProPoints(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { parsed, positional, repo, service, runtime, operator, rawArgs, getClient } = ctx;
|
||||
const arg1 = positional[1] || stringOption(parsed.options, ["scope", "s", "index", "i"]);
|
||||
const arg2 = positional[2];
|
||||
|
||||
// 兼容双参数调用: 如果同时提供了单号和索引号,走单据绑定流
|
||||
if (arg1 && arg2) {
|
||||
const billSn = arg1;
|
||||
const scopeTarget = arg2;
|
||||
const context = await getClient();
|
||||
const result = await service.injectAuditPoints(context.client, context.corpId, billSn, {
|
||||
scope: scopeTarget ? (isNaN(Number(scopeTarget)) ? scopeTarget : Number(scopeTarget)) : undefined,
|
||||
});
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "bind",
|
||||
documentSn: result.bill.billCode,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
decision: "PENDING",
|
||||
summary: `绑定单据并挂载审核要点成功,共 ${result.findings.length} 条要点(场景: ${result.scope})`,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
sn: result.bill.billCode,
|
||||
scope: result.scope,
|
||||
runId: result.run.id,
|
||||
count: result.findings.length,
|
||||
findings: result.findings,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "严格程度", "归属规则", "审核要点内容", "核验状态"];
|
||||
const rows = result.findings.map((f, i) => [
|
||||
i + 1,
|
||||
`[${f.strictness}]`,
|
||||
f.ruleCode ? `#${f.ruleCode}` : "-",
|
||||
f.clauseText,
|
||||
f.checkStatus,
|
||||
]);
|
||||
|
||||
const table = printTable(headers, rows);
|
||||
const title = `====== [AI PRO] 单据 ${result.bill.billCode} 已挂载场景 [${result.scope}] 审核要点 (共 ${result.findings.length} 条) ======\n`;
|
||||
const tip =
|
||||
`\n✅ [已安全登记] 审核要点已固化至数据库审批实例,全流程监控已激活。\n` +
|
||||
`下一步: 运行 "hose-aipro review ${result.bill.billCode} --eval '...' " 进行事实核验打标。\n` +
|
||||
`最终决断: 运行 "hose-aipro decide ${result.bill.billCode} --apply --yes" 由确定性网关仲裁审批。\n`;
|
||||
|
||||
return { stdout: title + table + tip, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const targetScope = arg1;
|
||||
if (!targetScope) {
|
||||
const allScopes = repo.listScopes("active");
|
||||
if (allScopes.length === 0) {
|
||||
return {
|
||||
stdout: "规约库中暂无生效规则。可使用 hose-use rule add <场景> <正文> 新增规则。\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
const lines: string[] = [
|
||||
`====== [AI PRO] 规约审核要点总览 (共 ${allScopes.length} 个适用场景) ======\n`,
|
||||
];
|
||||
for (const s of allScopes) {
|
||||
const detail = repo.getScopeDetail(s.index);
|
||||
if (!detail) continue;
|
||||
lines.push(`▶ 场景 [${detail.index}] ${detail.scope} (包含 ${detail.ruleCount} 条规则):`);
|
||||
let count = 0;
|
||||
detail.rules.forEach((r) => {
|
||||
r.parsed.clauses.forEach((c) => {
|
||||
count++;
|
||||
lines.push(` ${count}. [${c.strictness}] (规则 #${r.code}) ${c.action}`);
|
||||
});
|
||||
});
|
||||
lines.push("");
|
||||
}
|
||||
lines.push(`提示: 输入 "hose-aipro points <索引号|场景名称>" 查看指定场景要点明细。\n`);
|
||||
return { stdout: lines.join("\n"), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const detail = repo.getScopeDetail(targetScope);
|
||||
if (!detail) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 未找到索引号或场景为 "${targetScope}" 的规约场景。\n提示: 请先运行 "hose-aipro scopes" 查看所有可用场景索引。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const points: Array<{ index: number; strictness: string; ruleCode: number; clauseText: string }> = [];
|
||||
let count = 0;
|
||||
for (const rule of detail.rules) {
|
||||
for (const clause of rule.parsed.clauses) {
|
||||
count++;
|
||||
points.push({
|
||||
index: count,
|
||||
strictness: clause.strictness,
|
||||
ruleCode: rule.code,
|
||||
clauseText: clause.action,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
index: detail.index,
|
||||
scope: detail.scope,
|
||||
ruleCount: detail.ruleCount,
|
||||
pointsCount: points.length,
|
||||
points,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "严格程度", "归属规则", "审核要点内容 (Clause)"];
|
||||
const rows = points.map((p) => [p.index, `[${p.strictness}]`, `#${p.ruleCode}`, p.clauseText]);
|
||||
|
||||
const table = printTable(headers, rows);
|
||||
const title = `====== [AI PRO] 适用场景 [${detail.index}] ${detail.scope} - 审核要点清单 (共 ${points.length} 条要点) ======\n`;
|
||||
const tip =
|
||||
`\n说明: 审核要点为规约条款提取出的判定标准,纯规则元数据,与具体单据无关。\n` +
|
||||
`绑定单据: 运行 "hose-aipro bind <单号> ${detail.index}" 将此要点清单挂载到具体单据。\n`;
|
||||
|
||||
return { stdout: title + table + tip, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleAiProChecklist(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { targetSn, requireCorpId, service, repo, operator, rawArgs, runtime } = ctx;
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供单号: hose-aipro checklist <单号>");
|
||||
}
|
||||
|
||||
const activeCorpId = requireCorpId();
|
||||
const { run, findings } = service.getAuditChecklist(targetSn, activeCorpId);
|
||||
if (!run || findings.length === 0) {
|
||||
repo.logAiProAction({
|
||||
action: "checklist",
|
||||
documentSn: targetSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "BLOCKED",
|
||||
summary: "查询审核清单阻断:单据尚未绑定任何审核要点",
|
||||
});
|
||||
|
||||
const errorMsg =
|
||||
`[审批链路阻断] 单据 [${targetSn}] 尚未绑定任何明细级审核要点(要点列表为空)!\n` +
|
||||
`网关安全卡点生效:在要点未绑定前,审批链路物理不通!\n` +
|
||||
`请先执行: hose-aipro bind ${targetSn} <索引号> 挂载明细级审核要点清单。\n`;
|
||||
return { stdout: "", stderr: errorMsg, exitCode: 1 };
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ run, findings }),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "严格程度", "规则", "审核要点内容", "核验状态", "事实证据 / 说明"];
|
||||
const rows = findings.map((f, i) => [
|
||||
i + 1,
|
||||
`[${f.strictness}]`,
|
||||
f.ruleCode ? `#${f.ruleCode}` : "-",
|
||||
f.clauseText,
|
||||
f.checkStatus === "PASS"
|
||||
? "✅ PASS"
|
||||
: f.checkStatus === "FAIL"
|
||||
? "❌ FAIL"
|
||||
: f.checkStatus === "SKIP"
|
||||
? "➖ SKIP"
|
||||
: "⏳ PENDING",
|
||||
[f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-",
|
||||
]);
|
||||
|
||||
const table = printTable(headers, rows);
|
||||
const pendingCount = findings.filter((f) => f.checkStatus === "PENDING").length;
|
||||
const title = `====== [AI PRO] 单据 ${targetSn} 审核清单核验进度 (适用场景: [${run.scope || "未关联"}] | 总数: ${findings.length} | 待核验: ${pendingCount} | 决策: ${run.decision}) ======\n`;
|
||||
|
||||
return { stdout: title + table, stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -0,0 +1,499 @@
|
||||
import {
|
||||
type ApprovalRunRecord,
|
||||
type CreateFindingInput,
|
||||
type FindingCheckStatus,
|
||||
type RuleRecord,
|
||||
parseRuleBody,
|
||||
validateGatewayAction,
|
||||
} from "../../../domains/approval/index.js";
|
||||
import {
|
||||
approveBill,
|
||||
getRawBillFlow,
|
||||
getTranslatorContext,
|
||||
rejectBill,
|
||||
} from "../../../domains/bill/tools.js";
|
||||
import { translateBillFlowToMarkdown } from "../../../domains/bill/translator.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { parseIntegerList, type AiProCommandResult, type AiProExecutionContext } from "./types.js";
|
||||
|
||||
export async function handleAiProInit(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { positional, parsed, getClient, repo, operator, rawArgs } = ctx;
|
||||
const billSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
|
||||
if (!billSn) {
|
||||
throw new Error("请提供单号: hose-aipro init <单号>");
|
||||
}
|
||||
const context = await getClient();
|
||||
const raw = await getRawBillFlow(context.client, context.corpId, billSn);
|
||||
if (!raw) {
|
||||
throw new Error(`在当前企业下未找到单号为 [${billSn}] 的单据`);
|
||||
}
|
||||
const flowIdObj = (raw.flowId && typeof raw.flowId === "object" ? raw.flowId : raw) as Record<
|
||||
string,
|
||||
any
|
||||
>;
|
||||
const form = (flowIdObj.form && typeof flowIdObj.form === "object" ? flowIdObj.form : {}) as Record<
|
||||
string,
|
||||
any
|
||||
>;
|
||||
const title = form.title || flowIdObj.title || "<无标题>";
|
||||
const translatorContext = await getTranslatorContext(context.client, context.corpId, raw).catch(
|
||||
() => undefined
|
||||
);
|
||||
const snapshot = translateBillFlowToMarkdown(raw, translatorContext);
|
||||
|
||||
const run = repo.createApprovalRun({
|
||||
documentSn: form.code || billSn,
|
||||
corpId: context.corpId,
|
||||
flowId: flowIdObj.id || raw.id,
|
||||
documentSnapshot: snapshot,
|
||||
});
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "init",
|
||||
runId: run.shortId || run.id,
|
||||
documentSn: run.documentSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
summary: `初始化审批会话成功,签发 6 位短 ID: ${run.shortId} (有效期 6 小时)`,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout:
|
||||
JSON.stringify(
|
||||
{
|
||||
runId: run.shortId,
|
||||
documentSn: run.documentSn,
|
||||
title,
|
||||
corpId: run.corpId,
|
||||
status: run.decision,
|
||||
expiresIn: "6h",
|
||||
createdAt: run.createdAt,
|
||||
},
|
||||
null,
|
||||
2
|
||||
) + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleAiProTranslate(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { parsed, positional, repo, operator, rawArgs, getClient } = ctx;
|
||||
const runHandle = stringOption(parsed.options, ["run", "r"]);
|
||||
const specifiedSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
|
||||
|
||||
let runRecord: ApprovalRunRecord | null = null;
|
||||
if (runHandle) {
|
||||
runRecord = repo.getRunByHandle(runHandle);
|
||||
if (!runRecord) {
|
||||
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
|
||||
}
|
||||
} else if (specifiedSn) {
|
||||
const maybeRun = repo.getRunByHandle(specifiedSn);
|
||||
if (maybeRun?.shortId && maybeRun.shortId.toUpperCase() === specifiedSn.toUpperCase()) {
|
||||
runRecord = maybeRun;
|
||||
}
|
||||
}
|
||||
|
||||
let targetSn: string | undefined;
|
||||
let isSessionPrimary = false;
|
||||
|
||||
if (runRecord) {
|
||||
if (specifiedSn && specifiedSn !== runRecord.shortId) {
|
||||
targetSn = specifiedSn;
|
||||
} else {
|
||||
targetSn = runRecord.documentSn;
|
||||
isSessionPrimary = true;
|
||||
}
|
||||
} else {
|
||||
targetSn = specifiedSn;
|
||||
}
|
||||
|
||||
if (!targetSn) {
|
||||
throw new Error("请提供会话 ID 或单号: hose-aipro translate [单号] --run <runId>");
|
||||
}
|
||||
|
||||
if (isSessionPrimary && runRecord?.documentSnapshot) {
|
||||
repo.logAiProAction({
|
||||
action: "translate",
|
||||
runId: runRecord.shortId || runRecord.id,
|
||||
documentSn: runRecord.documentSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
summary: `在会话 [${runRecord.shortId}] 读取主单据快照 [${runRecord.documentSn}]`,
|
||||
});
|
||||
return {
|
||||
stdout: runRecord.documentSnapshot.endsWith("\n")
|
||||
? runRecord.documentSnapshot
|
||||
: runRecord.documentSnapshot + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const context = await getClient();
|
||||
const raw = await getRawBillFlow(context.client, context.corpId, targetSn);
|
||||
if (!raw) {
|
||||
throw new Error(`在当前企业下未找到单号或 ID 为 [${targetSn}] 的单据`);
|
||||
}
|
||||
const translatorContext = await getTranslatorContext(context.client, context.corpId, raw).catch(
|
||||
() => undefined
|
||||
);
|
||||
const markdown = translateBillFlowToMarkdown(raw, translatorContext);
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "translate",
|
||||
runId: runRecord?.shortId || runRecord?.id,
|
||||
documentSn: targetSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
summary: runRecord
|
||||
? `在会话 [${runRecord.shortId}] 查阅关联单据 [${targetSn}] 转译文本`
|
||||
: `查阅单据 [${targetSn}] 转译文本`,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: markdown.endsWith("\n") ? markdown : markdown + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleAiProBind(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { parsed, positional, repo, operator, rawArgs } = ctx;
|
||||
const runHandle = stringOption(parsed.options, ["run", "r"]) || positional[1];
|
||||
if (!runHandle) {
|
||||
throw new Error("请提供会话 ID: hose-aipro bind --run <runId> --rules '[1, 2]'");
|
||||
}
|
||||
const runRecord = repo.getRunByHandle(runHandle);
|
||||
if (!runRecord) {
|
||||
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
|
||||
}
|
||||
|
||||
const rawRules = stringOption(parsed.options, ["rules", "rule", "codes", "c"]);
|
||||
const rawIndexes = stringOption(parsed.options, ["indexes", "index", "i", "scopes", "scope", "s"]);
|
||||
const fallbackRaw = positional
|
||||
.slice(1)
|
||||
.find((p) => p !== runHandle && p.startsWith("[") && p.endsWith("]"));
|
||||
|
||||
const ruleCodes = parseIntegerList(rawRules || fallbackRaw);
|
||||
const indexNums = parseIntegerList(rawIndexes);
|
||||
|
||||
if (ruleCodes.length === 0 && indexNums.length === 0) {
|
||||
throw new Error("请指定要挂载的规则或场景索引,例如: hose-aipro bind --run <runId> --rules '[1, 2]'");
|
||||
}
|
||||
|
||||
const targetRulesMap = new Map<number, RuleRecord>();
|
||||
for (const code of ruleCodes) {
|
||||
const r = repo.getRuleByCode(code);
|
||||
if (r && r.status === "active") {
|
||||
targetRulesMap.set(r.code, r);
|
||||
}
|
||||
}
|
||||
for (const idx of indexNums) {
|
||||
const detail = repo.getScopeDetail(idx);
|
||||
if (detail) {
|
||||
for (const r of detail.rules) {
|
||||
if (r.status === "active") {
|
||||
targetRulesMap.set(r.code, r);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (targetRulesMap.size === 0) {
|
||||
throw new Error("未找到任何有效规则,请先运行 hose-aipro scopes 和 hose-aipro rules 查看规约");
|
||||
}
|
||||
|
||||
const sortedRules = Array.from(targetRulesMap.values()).sort((a, b) => a.code - b.code);
|
||||
const findingsToInject: CreateFindingInput[] = [];
|
||||
|
||||
for (const r of sortedRules) {
|
||||
const parsedRule = parseRuleBody(r.body);
|
||||
for (const clause of parsedRule.clauses) {
|
||||
findingsToInject.push({
|
||||
ruleId: r.id,
|
||||
clauseText: clause.action,
|
||||
strictness: clause.strictness,
|
||||
checkStatus: "PENDING",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const injected = repo.injectFindings(runRecord.id, findingsToInject);
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "bind",
|
||||
runId: runRecord.shortId || runRecord.id,
|
||||
documentSn: runRecord.documentSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
summary: `在会话 [${runRecord.shortId}] 挂载 ${injected.length} 条审核要点清单(涵盖规则: ${sortedRules.map((r) => `#${r.code}`).join(", ")})`,
|
||||
});
|
||||
|
||||
const output = injected.map((f, i) => ({
|
||||
要点编号: i + 1,
|
||||
严格程度: f.strictness,
|
||||
归属规则: f.ruleCode ?? "-",
|
||||
审核要点: f.clauseText,
|
||||
核验状态: "待核验",
|
||||
}));
|
||||
|
||||
return {
|
||||
stdout: JSON.stringify(output, null, 2) + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleAiProReview(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { parsed, positional, repo, operator, rawArgs } = ctx;
|
||||
const runHandle = stringOption(parsed.options, ["run", "r"]) || positional[1];
|
||||
if (!runHandle) {
|
||||
throw new Error("请提供会话 ID: hose-aipro review --run <runId> --eval '...'");
|
||||
}
|
||||
const runRecord = repo.getRunByHandle(runHandle);
|
||||
if (!runRecord) {
|
||||
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
|
||||
}
|
||||
|
||||
const findings = repo.getFindingsByRunId(runRecord.id);
|
||||
if (findings.length === 0) {
|
||||
throw new Error(
|
||||
`会话 [${runRecord.shortId || runRecord.id}] 尚未挂载任何审核要点清单,请先执行 hose-aipro bind --run ${runRecord.shortId || runRecord.id} --rules '...'`
|
||||
);
|
||||
}
|
||||
|
||||
const evalStr = stringOption(parsed.options, ["eval", "findings", "e"]);
|
||||
const pointIndex = numberOption(parsed.options, ["point", "p", "index", "i"], 0);
|
||||
const statusInput = stringOption(parsed.options, ["status", "state"])?.toUpperCase() as
|
||||
| FindingCheckStatus
|
||||
| undefined;
|
||||
const evidence = stringOption(parsed.options, ["evidence", "proof"]);
|
||||
const reasoning = stringOption(parsed.options, ["reasoning", "reason"]);
|
||||
|
||||
const normalizeStatus = (raw: string): FindingCheckStatus => {
|
||||
const upper = raw.trim().toUpperCase();
|
||||
if (["PASS", "通过", "合规", "OK", "YES"].includes(upper)) return "PASS";
|
||||
if (["FAIL", "未通过", "不通过", "违规", "NO"].includes(upper)) return "FAIL";
|
||||
if (["SKIP", "跳过", "不适用", "NA", "N/A"].includes(upper)) return "SKIP";
|
||||
return "PENDING";
|
||||
};
|
||||
|
||||
const updates: Array<{
|
||||
index: number;
|
||||
status: FindingCheckStatus;
|
||||
evidence?: string;
|
||||
reasoning?: string;
|
||||
}> = [];
|
||||
|
||||
if (typeof pointIndex === "number" && pointIndex > 0 && statusInput) {
|
||||
updates.push({ index: pointIndex, status: normalizeStatus(statusInput), evidence, reasoning });
|
||||
} else if (evalStr) {
|
||||
const segments = evalStr
|
||||
.split(/[;\n]+/)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
for (const seg of segments) {
|
||||
const match = seg.match(/^(\d+)\s*=\s*([A-Za-z\u4e00-\u9fa5]+)(?::(.*))?$/);
|
||||
if (match) {
|
||||
const idx = parseInt(match[1], 10);
|
||||
const status = normalizeStatus(match[2]);
|
||||
const desc = match[3]?.trim();
|
||||
updates.push({ index: idx, status, evidence: desc, reasoning: desc });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
throw new Error(
|
||||
`请提供核验判定参数,例如:\n` +
|
||||
` hose-aipro review --run ${runRecord.shortId || runRecord.id} --eval "1=PASS:已上传发票; 2=FAIL:住宿超标; 3=SKIP"\n`
|
||||
);
|
||||
}
|
||||
|
||||
for (const item of updates) {
|
||||
const target = findings[item.index - 1];
|
||||
if (!target) {
|
||||
throw new Error(`要点编号超出范围: #${item.index} (当前要点总数: ${findings.length})`);
|
||||
}
|
||||
repo.updateFinding(target.id, {
|
||||
checkStatus: item.status,
|
||||
evidence: item.evidence,
|
||||
reasoning: item.reasoning,
|
||||
});
|
||||
}
|
||||
|
||||
const updatedFindings = repo.getFindingsByRunId(runRecord.id);
|
||||
const passCount = updatedFindings.filter((f) => f.checkStatus === "PASS").length;
|
||||
const failCount = updatedFindings.filter((f) => f.checkStatus === "FAIL").length;
|
||||
const skipCount = updatedFindings.filter((f) => f.checkStatus === "SKIP").length;
|
||||
const pendingCount = updatedFindings.filter((f) => f.checkStatus === "PENDING").length;
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "review",
|
||||
runId: runRecord.shortId || runRecord.id,
|
||||
documentSn: runRecord.documentSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
summary: `在会话 [${runRecord.shortId || runRecord.id}] 录入 ${updates.length} 项要点核验(通过: ${passCount}, 违规: ${failCount}, 待核验: ${pendingCount})`,
|
||||
});
|
||||
|
||||
const checklistOutput = updatedFindings.map((f, i) => ({
|
||||
要点编号: i + 1,
|
||||
严格程度: f.strictness,
|
||||
归属规则: f.ruleCode ?? "-",
|
||||
审核要点: f.clauseText,
|
||||
核验状态:
|
||||
f.checkStatus === "PASS"
|
||||
? "通过"
|
||||
: f.checkStatus === "FAIL"
|
||||
? "未通过"
|
||||
: f.checkStatus === "SKIP"
|
||||
? "已跳过"
|
||||
: "待核验",
|
||||
事实依据: Array.from(new Set([f.evidence, f.reasoning].filter(Boolean))).join(" - ") || "-",
|
||||
}));
|
||||
|
||||
const resultObj = {
|
||||
会话ID: runRecord.shortId || runRecord.id,
|
||||
单号: runRecord.documentSn,
|
||||
要点总数: updatedFindings.length,
|
||||
已通过: passCount,
|
||||
未通过: failCount,
|
||||
已跳过: skipCount,
|
||||
待核验: pendingCount,
|
||||
核验清单: checklistOutput,
|
||||
};
|
||||
|
||||
return {
|
||||
stdout: JSON.stringify(resultObj, null, 2) + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleAiProDecide(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { parsed, positional, command, repo, operator, rawArgs, getClient } = ctx;
|
||||
const runHandle =
|
||||
stringOption(parsed.options, ["run", "r"]) ||
|
||||
positional
|
||||
.slice(1)
|
||||
.find(
|
||||
(p) => !["approve", "reject", "pass", "同意", "通过", "驳回", "拒绝"].includes(p.toLowerCase())
|
||||
);
|
||||
if (!runHandle) {
|
||||
throw new Error("请提供会话 ID: hose-aipro decide <approve|reject> --run <runId> --opinion '...'");
|
||||
}
|
||||
const runRecord = repo.getRunByHandle(runHandle);
|
||||
if (!runRecord) {
|
||||
throw new Error(`未找到会话 ID 为 [${runHandle}] 的审批实例`);
|
||||
}
|
||||
|
||||
let actionRaw: string | undefined = positional[1]?.toLowerCase();
|
||||
if (actionRaw === runHandle?.toLowerCase()) {
|
||||
actionRaw = positional[2]?.toLowerCase();
|
||||
}
|
||||
if (!actionRaw || actionRaw.startsWith("-")) {
|
||||
actionRaw = stringOption(parsed.options, ["action", "a"])?.toLowerCase();
|
||||
}
|
||||
if (command === "approve") {
|
||||
actionRaw = "approve";
|
||||
} else if (command === "reject") {
|
||||
actionRaw = "reject";
|
||||
}
|
||||
|
||||
let action: "APPROVE" | "REJECT" | undefined;
|
||||
if (["approve", "pass", "同意", "通过"].includes(actionRaw || "")) {
|
||||
action = "APPROVE";
|
||||
} else if (["reject", "refuse", "驳回", "拒绝"].includes(actionRaw || "")) {
|
||||
action = "REJECT";
|
||||
}
|
||||
|
||||
if (!action) {
|
||||
throw new Error("请指定要执行的审批动作: hose-aipro decide approve 或 hose-aipro decide reject");
|
||||
}
|
||||
|
||||
const opinion = (
|
||||
stringOption(parsed.options, ["opinion", "comment", "message", "m", "审批意见", "意见"]) || ""
|
||||
).trim();
|
||||
|
||||
if (!opinion) {
|
||||
throw new Error("必须提供小于 150 字的审批意见: --opinion '<审批意见>'");
|
||||
}
|
||||
|
||||
const findings = repo.getFindingsByRunId(runRecord.id);
|
||||
|
||||
validateGatewayAction({
|
||||
documentSn: runRecord.documentSn,
|
||||
findings,
|
||||
requestedAction: action === "APPROVE" ? "approve" : "reject",
|
||||
opinion,
|
||||
});
|
||||
|
||||
const apply = booleanOption(parsed.options, ["apply", "execute", "run", "do"]);
|
||||
let executionStatus = "模拟完成(未带 --apply,未真实修改线上单据)";
|
||||
|
||||
if (apply) {
|
||||
const confirmed = booleanOption(parsed.options, ["yes", "y", "confirm"]);
|
||||
if (!confirmed) {
|
||||
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
||||
throw new Error("开启 --apply 会真实改变单据流转状态,请显式添加 --yes 确认。");
|
||||
}
|
||||
const { prompt } = await import("../../helpers.js");
|
||||
const ans = await prompt(
|
||||
`[AI PRO] 即将向合思系统真实执行审批流转 [${action === "APPROVE" ? "同意" : "驳回"}],确认执行?输入 yes: `
|
||||
);
|
||||
if (!/^(y|yes|是)$/i.test(ans.trim())) throw new Error("已取消审批操作");
|
||||
}
|
||||
|
||||
const context = await getClient();
|
||||
if (action === "APPROVE") {
|
||||
await approveBill(context.client, context.corpId, runRecord.documentSn, {
|
||||
comment: opinion,
|
||||
});
|
||||
} else {
|
||||
await rejectBill(context.client, context.corpId, runRecord.documentSn, {
|
||||
comment: opinion,
|
||||
});
|
||||
}
|
||||
executionStatus = "已真实下发合思系统流转";
|
||||
}
|
||||
|
||||
repo.updateApprovalRun(runRecord.id, {
|
||||
decision: action,
|
||||
decisionSummary: opinion,
|
||||
failedRulesCount: findings.filter((f) => f.checkStatus === "FAIL").length,
|
||||
});
|
||||
|
||||
repo.logAiProAction({
|
||||
action: "decide",
|
||||
runId: runRecord.shortId || runRecord.id,
|
||||
documentSn: runRecord.documentSn,
|
||||
operator,
|
||||
args: JSON.stringify(rawArgs),
|
||||
status: "SUCCESS",
|
||||
decision: action,
|
||||
summary: `审批动作 [${action === "APPROVE" ? "同意" : "驳回"}] (${executionStatus})`,
|
||||
});
|
||||
|
||||
const resultObj = {
|
||||
会话ID: runRecord.shortId || runRecord.id,
|
||||
单号: runRecord.documentSn,
|
||||
执行动作: action === "APPROVE" ? "同意" : "驳回",
|
||||
审批意见: opinion,
|
||||
流转状态: executionStatus,
|
||||
网关状态: "放行",
|
||||
};
|
||||
|
||||
return {
|
||||
stdout: JSON.stringify(resultObj, null, 2) + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import type { ApprovalRunRecord } from "../../../domains/approval/index.js";
|
||||
import { VERSION } from "../../../version.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { formatExpiresAt, printJson, printTable } from "../../printer.js";
|
||||
import type { AiProCommandResult, AiProExecutionContext } from "./types.js";
|
||||
|
||||
export async function handleAiProStatus(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { repo, corp, corpId, operator, runtime, parsed } = ctx;
|
||||
const scopes = repo.listScopes("active");
|
||||
const rules = repo.listRules();
|
||||
const runs = corpId ? repo.listRuns({ corpId }) : repo.listRuns();
|
||||
const pendingRuns = runs.filter((r) => r.decision === "PENDING");
|
||||
const recentLogs = repo.listAiProLogs(undefined, 5);
|
||||
const isJson = runtime.jsonMode || booleanOption(parsed.options, ["json", "j"]);
|
||||
|
||||
const corpStaffId = corp?.credentials?.staffId || corp?.staffId || "-";
|
||||
const corpStaffName = corp?.staffName || corp?.session?.staffName || null;
|
||||
const corpExpiresAt = corp?.auth?.expiresAt || corp?.session?.expTime;
|
||||
|
||||
if (isJson) {
|
||||
return {
|
||||
stdout:
|
||||
JSON.stringify(
|
||||
{
|
||||
tool: "hose-aipro",
|
||||
version: VERSION,
|
||||
corp: corp
|
||||
? {
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
staffId: corpStaffId,
|
||||
userName: corpStaffName,
|
||||
source: corp.source,
|
||||
expiresAt: corpExpiresAt,
|
||||
expired: corpExpiresAt ? corpExpiresAt <= Date.now() : false,
|
||||
baseUrl: corp.baseUrl,
|
||||
}
|
||||
: null,
|
||||
operator,
|
||||
ruleEngine: {
|
||||
scopesCount: scopes.length,
|
||||
rulesCount: rules.length,
|
||||
scopes: scopes.map((s) => ({
|
||||
index: s.index,
|
||||
scope: s.scope,
|
||||
ruleCount: s.ruleCount,
|
||||
})),
|
||||
},
|
||||
sessions: {
|
||||
total: runs.length,
|
||||
pending: pendingRuns.length,
|
||||
},
|
||||
recentLogsCount: recentLogs.length,
|
||||
},
|
||||
null,
|
||||
2
|
||||
) + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const lines = [
|
||||
`====== 合思 AI PRO 确定性审批网关运行上下文 (v${VERSION}) ======`,
|
||||
` 当前连接企业 : ${corp ? `${corp.name} (${corp.id})` : "⚠️ 未指定企业"}`,
|
||||
` 当前操作工号 : ${corpStaffId}`,
|
||||
` 操作员标识 : ${operator}`,
|
||||
` 凭证有效状态 : ${corp ? formatExpiresAt(corpExpiresAt) : "-"}`,
|
||||
` 主站 BaseURL : ${corp?.baseUrl || "-"}`,
|
||||
` 规约场景库 : 已加载 ${scopes.length} 个场景 (${scopes.map((s) => `#${s.index} ${s.scope}`).join(", ") || "无"}),共 ${rules.length} 条仲裁规则`,
|
||||
` 未结审批会话 : ${pendingRuns.length} 个待决断会话 (当前企业历史总会话: ${runs.length} 个)`,
|
||||
"",
|
||||
"提示:",
|
||||
" - 查看规约场景列表: hose-aipro scopes",
|
||||
" - 切换全局工作企业: hose-use corps switch <企业ID>",
|
||||
" - 临时指定执行企业: hose-aipro --corp=<企业ID> <子命令>",
|
||||
" - 单据审批全流程 : hose-aipro bind <单号> <索引号> -> hose-aipro review -> hose-aipro decide",
|
||||
"",
|
||||
];
|
||||
|
||||
return { stdout: lines.join("\n"), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleAiProLogs(ctx: AiProExecutionContext): Promise<AiProCommandResult> {
|
||||
const { parsed, repo, runtime, targetSn } = ctx;
|
||||
const runHandle = stringOption(parsed.options, ["run", "r"]);
|
||||
const limit = numberOption(parsed.options, ["limit", "n"], 50) ?? 50;
|
||||
|
||||
let runRecord: ApprovalRunRecord | null = null;
|
||||
if (runHandle) {
|
||||
runRecord = repo.getRunByHandle(runHandle);
|
||||
} else if (targetSn) {
|
||||
const maybeRun = repo.getRunByHandle(targetSn);
|
||||
if (maybeRun?.shortId && maybeRun.shortId.toUpperCase() === targetSn.toUpperCase()) {
|
||||
runRecord = maybeRun;
|
||||
}
|
||||
}
|
||||
|
||||
const filter: { runId?: string; documentSn?: string } = {};
|
||||
if (runRecord) {
|
||||
filter.runId = runRecord.shortId || runRecord.id;
|
||||
} else if (runHandle) {
|
||||
filter.runId = runHandle;
|
||||
}
|
||||
if (targetSn && targetSn !== runRecord?.shortId) {
|
||||
filter.documentSn = targetSn;
|
||||
}
|
||||
|
||||
const logs = repo.listAiProLogs(filter, limit);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ total: logs.length, logs }),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (logs.length === 0) {
|
||||
const targetDesc = filter.runId
|
||||
? ` (会话: ${filter.runId})`
|
||||
: filter.documentSn
|
||||
? ` (单号: ${filter.documentSn})`
|
||||
: "";
|
||||
return {
|
||||
stdout: `[AI PRO 监控流水] 暂无任何登记日志记录${targetDesc}。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = [
|
||||
"#",
|
||||
"发生时间",
|
||||
"会话 ID",
|
||||
"动作 (Action)",
|
||||
"单号",
|
||||
"操作人",
|
||||
"状态",
|
||||
"网关决策",
|
||||
"摘要说明",
|
||||
];
|
||||
const rows = logs.map((l, i) => [
|
||||
i + 1,
|
||||
new Date(l.createdAt).toLocaleString("zh-CN"),
|
||||
l.runId || "-",
|
||||
l.action,
|
||||
l.documentSn || "-",
|
||||
l.operator || "-",
|
||||
l.status === "SUCCESS" ? "✅ SUCCESS" : l.status === "BLOCKED" ? "🚫 BLOCKED" : "❌ ERROR",
|
||||
l.decision || "-",
|
||||
l.summary || "-",
|
||||
]);
|
||||
|
||||
const table = printTable(headers, rows);
|
||||
const title = `====== [AI PRO 全流程监控流水账本] (共登记 ${logs.length} 条记录) ======\n`;
|
||||
|
||||
return { stdout: title + table, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export function handleAiProHelp(ctx: AiProExecutionContext): AiProCommandResult {
|
||||
const { corp, operator, jsonMode } = ctx;
|
||||
const corpExpiresAt = corp?.auth?.expiresAt || corp?.session?.expTime;
|
||||
const corpBanner = corp
|
||||
? `[当前连接企业: ${corp.name} (${corp.id}) | 操作人: ${operator} | 凭证状态: ${formatExpiresAt(corpExpiresAt)}]\n[全局切换: hose-use corps switch <企业ID> | 临时指定: hose-aipro --corp=<企业ID>]`
|
||||
: `[当前企业: 未指定 | 请先运行 hose-use auth login 或带上 --corp=<企业ID>]`;
|
||||
|
||||
const helpText = `
|
||||
合思 AI PRO 确定性审批仲裁网关 CLI (hose-aipro) v${VERSION}
|
||||
一切操作在本地 SQLite 强受控、全流程监控、不可篡改审计留痕。
|
||||
|
||||
${corpBanner}
|
||||
|
||||
核心工作流:
|
||||
0. 查看 AI PRO 运行上下文与当前绑定企业:
|
||||
hose-aipro status # 查看当前企业、操作人、规则库统计与待办会话
|
||||
|
||||
1. 查看规约场景索引库 (获取规则索引号):
|
||||
hose-aipro scopes # 列出所有场景索引 (Index / Scope / 规则数)
|
||||
|
||||
2. 查看场景审核要点清单 (纯规则元数据,与单据无关):
|
||||
hose-aipro points <索引号|场景名称> # 例如: hose-aipro points 1
|
||||
|
||||
3. 显式绑定单据并挂载审核要点:
|
||||
hose-aipro bind <单号> <索引号> # 例如: hose-aipro bind S26000001 1
|
||||
|
||||
4. 查看单据审核清单与核验进度:
|
||||
hose-aipro checklist <单号> # 查看当前单据要点核验进度与挂载场景
|
||||
|
||||
5. 逐项录入事实核验打标:
|
||||
hose-aipro review <单号> --eval "1=PASS; 2=FAIL:证据说明; 3=SKIP"
|
||||
hose-aipro review <单号> --point 1 --status FAIL --reason "缺少发票"
|
||||
|
||||
6. 确定性网关仲裁与流转执行 (硬性条款物理切断同意分支):
|
||||
hose-aipro decide <单号> # 预审仿真 (Dry Run)
|
||||
hose-aipro decide <单号> --apply --yes # 真实驱动下游审批/驳回/评论
|
||||
|
||||
7. 全流程监控日志流水查看:
|
||||
hose-aipro logs [单号] # 追溯所有 AI PRO 操作流水
|
||||
`;
|
||||
return {
|
||||
stdout: jsonMode ? printJson({ help: helpText.trim() }) + "\n" : helpText.trim() + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import type { ApprovalRepository, ApprovalService } from "../../../domains/approval/index.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
|
||||
export interface AiProExecutionContext {
|
||||
rawArgs: string[];
|
||||
parsed: CliParsedArgs;
|
||||
runtime: CliRuntime;
|
||||
corp: CorpConfig | null;
|
||||
corpId?: string;
|
||||
operator: string;
|
||||
positional: string[];
|
||||
command: string;
|
||||
targetSn?: string;
|
||||
jsonMode: boolean;
|
||||
repo: ApprovalRepository;
|
||||
service: ApprovalService;
|
||||
requireCorpId: () => string;
|
||||
getClient: () => Promise<{ client: KyInstance; corpId: string }>;
|
||||
}
|
||||
|
||||
export type AiProCommandResult = CliResult;
|
||||
|
||||
export function parseIntegerList(input?: string): number[] {
|
||||
if (!input) return [];
|
||||
const trimmed = input.trim();
|
||||
const list: number[] = [];
|
||||
if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
|
||||
try {
|
||||
const parsedJson = JSON.parse(trimmed);
|
||||
if (Array.isArray(parsedJson)) {
|
||||
for (const item of parsedJson) {
|
||||
const n = Number(item);
|
||||
if (!isNaN(n)) list.push(n);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
const inner = trimmed.replace(/[\[\]]/g, "");
|
||||
const parts = inner.split(/[,,\s]+/).filter(Boolean);
|
||||
for (const p of parts) {
|
||||
const n = Number(p.replace(/['"]/g, ""));
|
||||
if (!isNaN(n)) list.push(n);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { fetchWorkbenchAppsList } from "../../domains/menu/tools.js";
|
||||
import { getPlatform } from "../../domains/datalink/api.js";
|
||||
import { getPlatform } from "../../domains/datalink/services.js";
|
||||
import { createClientsForCorp } from "../helpers.js";
|
||||
import { stringOption, booleanOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
|
||||
@@ -29,7 +29,7 @@ import {
|
||||
handleGenerateCorpLink,
|
||||
handleSyncFromSeal,
|
||||
resolveTargetCorpByArgOrContext,
|
||||
} from "./corps.js";
|
||||
} from "./corps/index.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
function isHttpUrl(val?: string): boolean {
|
||||
|
||||
@@ -1,752 +0,0 @@
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { booleanOption, stringOption, numberOption } from "../parser.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import {
|
||||
searchAndFormatBills,
|
||||
getBillByCodeOrId,
|
||||
getBillFlow,
|
||||
formatBillFlowOperator,
|
||||
getBillRisk,
|
||||
getBillReferences,
|
||||
getBillRelations,
|
||||
getBillAttachments,
|
||||
downloadBillAttachments,
|
||||
getFieldDictionary,
|
||||
approveBill,
|
||||
rejectBill,
|
||||
transferBill,
|
||||
addNodeBill,
|
||||
commentBill,
|
||||
resolveBillStaffIds,
|
||||
inspectFormSpecification,
|
||||
formatFormPriorityList,
|
||||
hasLinkageOverridePriority,
|
||||
} from "../../domains/bill/tools.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
|
||||
export async function handleBillCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) {
|
||||
throw new Error(
|
||||
"未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。"
|
||||
);
|
||||
}
|
||||
|
||||
const action = parsed.action?.toLowerCase();
|
||||
const corpId = corp.corpId || corp.id;
|
||||
let client: Awaited<ReturnType<typeof createSessionClient>> | undefined;
|
||||
const getClient = async () => {
|
||||
client ??= await createSessionClient(corp);
|
||||
return client;
|
||||
};
|
||||
|
||||
const actionTarget = () => parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
const requireWriteConfirmation = async () => {
|
||||
if (isDryRun(parsed, runtime) || booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])) return;
|
||||
if (!process.stdin.isTTY || !process.stdout.isTTY || Boolean(process.env.CI) || process.env.NODE_ENV === "test") {
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"单据审批动作",
|
||||
`hose-use bill ${action || "approve"} ${actionTarget() || "<单号|ID>"} --yes`
|
||||
);
|
||||
}
|
||||
const { prompt } = await import("../helpers.js");
|
||||
const answer = await prompt("该操作会改变单据状态,确认继续?输入 yes 继续: ");
|
||||
if (!/^(y|yes|是)$/i.test(answer.trim())) throw new Error("已取消审批动作");
|
||||
};
|
||||
const listOption = (keys: string[]): string[] | undefined => {
|
||||
const value = stringOption(parsed.options, keys);
|
||||
if (!value) return undefined;
|
||||
const values = value.split(",").map((item) => item.trim()).filter(Boolean);
|
||||
return values.length ? values : undefined;
|
||||
};
|
||||
const actionOptions = () => ({
|
||||
currentStaffId: corp.staffId || corp.credentials.staffId,
|
||||
reminder: booleanOption(parsed.options, ["reminder", "remind"]),
|
||||
keepItSecret: booleanOption(parsed.options, ["keep-it-secret", "secret", "private"]),
|
||||
comment: stringOption(parsed.options, ["comment", "message", "opinion"]),
|
||||
participants: listOption(["participant", "participants"]),
|
||||
approverIds: listOption(["approver", "approver-id", "approverIds", "staff", "staff-id", "to"]),
|
||||
rejectTo: stringOption(parsed.options, ["reject-to", "rejectTo"]),
|
||||
resubmitMethod: (stringOption(parsed.options, ["resubmit-method", "resubmitMethod"]) || "TO_REJECTOR").toUpperCase() as "TO_REJECTOR" | "FROM_START",
|
||||
addNodeType: ((): "PRE_ADD_NODE" | "AFT_ADD_NODE" => {
|
||||
const mode = (stringOption(parsed.options, ["mode", "add-node-type", "addNodeType"]) || "pre").toLowerCase();
|
||||
return mode === "post" || mode === "after" || mode === "aft" || mode === "aft_add_node" ? "AFT_ADD_NODE" : "PRE_ADD_NODE";
|
||||
})(),
|
||||
});
|
||||
const resolveApproverIds = async (values: string[] | undefined): Promise<string[]> => {
|
||||
if (!values?.length) throw new Error("请通过 --approver-id、--staff 或 --to 指定员工 ID、工号或姓名");
|
||||
return resolveBillStaffIds(await getClient(), corpId, values);
|
||||
};
|
||||
|
||||
switch (action) {
|
||||
case "approve":
|
||||
case "agree": {
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill approve <单号|ID> --yes");
|
||||
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "同意单据审批", target, actionOptions());
|
||||
const result = await approveBill(await getClient(), corpId, target, actionOptions());
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `审批同意成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "reject":
|
||||
case "deny": {
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill reject <单号|ID> --comment <原因> --yes");
|
||||
const options = actionOptions();
|
||||
if (!options.comment?.trim()) throw new Error("驳回原因不能为空,请通过 --comment 提供原因");
|
||||
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "驳回单据审批", target, options);
|
||||
const result = await rejectBill(await getClient(), corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `驳回成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "transfer":
|
||||
case "shift": {
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill transfer <单号|ID> --approver-id <员工ID> --yes");
|
||||
const rawOptions = actionOptions();
|
||||
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "转交单据审批", target, rawOptions);
|
||||
const options = { ...rawOptions, approverIds: await resolveApproverIds(rawOptions.approverIds) };
|
||||
const result = await transferBill(await getClient(), corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `转交审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "add-node":
|
||||
case "addnode":
|
||||
case "countersign":
|
||||
case "counter-sign": {
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill add-node <单号|ID> --approver-id <员工ID> --yes");
|
||||
const rawOptions = actionOptions();
|
||||
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "单据加签", target, rawOptions);
|
||||
const options = { ...rawOptions, approverIds: await resolveApproverIds(rawOptions.approverIds) };
|
||||
const result = await addNodeBill(await getClient(), corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `加签审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "comment":
|
||||
case "remark": {
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供单号或单据 ID: hose-use bill comment <单号|ID> --comment <内容> --yes");
|
||||
const options = actionOptions();
|
||||
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "添加单据评论", target, options);
|
||||
const result = await commentBill(await getClient(), corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `单据评论成功\n单号: ${result.billCode || target}\n流程 ID: ${result.flowId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "list":
|
||||
case "search":
|
||||
case undefined: {
|
||||
const mine = booleanOption(parsed.options, ["mine", "my", "self"]);
|
||||
if (mine) {
|
||||
const { handleTaskCommand } = await import("./task.js");
|
||||
return handleTaskCommand(
|
||||
{
|
||||
...parsed,
|
||||
area: "task",
|
||||
action: "submitted",
|
||||
},
|
||||
runtime
|
||||
);
|
||||
}
|
||||
|
||||
const code = stringOption(parsed.options, ["code", "c"]);
|
||||
const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"]);
|
||||
const searchFields = stringOption(parsed.options, ["search-fields", "searchFields", "search-field", "sf"]);
|
||||
const stage = stringOption(parsed.options, ["stage"]);
|
||||
const state = stringOption(parsed.options, ["state", "s"]);
|
||||
const count = numberOption(parsed.options, ["count", "limit", "n"], 20);
|
||||
const since = stringOption(parsed.options, ["since", "days", "d"]);
|
||||
const startDate = stringOption(parsed.options, ["start-date", "startDate", "from", "start"]);
|
||||
const endDate = stringOption(parsed.options, ["end-date", "endDate", "to", "end"]);
|
||||
const rawOrder = stringOption(parsed.options, ["order", "sort", "direction"]);
|
||||
const order = rawOrder && /asc/i.test(rawOrder) ? "ASC" : "DESC";
|
||||
const filterBy = stringOption(parsed.options, ["filter-by", "filterBy", "filter"]);
|
||||
const select = stringOption(parsed.options, ["select", "fields"]);
|
||||
const distinct = booleanOption(parsed.options, ["distinct"]);
|
||||
|
||||
const result = await searchAndFormatBills(await getClient(), corpId, {
|
||||
code,
|
||||
keyword,
|
||||
searchFields,
|
||||
stage,
|
||||
state,
|
||||
count,
|
||||
since,
|
||||
startDate,
|
||||
endDate,
|
||||
order,
|
||||
filterBy,
|
||||
select,
|
||||
distinct,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
total: result.total,
|
||||
returned: result.returned,
|
||||
items: result.items,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "单据编号 (单号)", "单据名称", "阶段", "状态", "金额", "提交时间"];
|
||||
const rows = result.items.map((b, idx) => [
|
||||
idx + 1,
|
||||
b.billCode,
|
||||
b.billName,
|
||||
b.stage || "-",
|
||||
b.state || "-",
|
||||
b.amount || "-",
|
||||
b.submitDate || b.createTime || "-",
|
||||
]);
|
||||
|
||||
const filterSummary: string[] = [];
|
||||
if (since) filterSummary.push(`近 ${since}`);
|
||||
if (startDate || endDate) filterSummary.push(`${startDate || "起"} ~ ${endDate || "止"}`);
|
||||
if (code) filterSummary.push(`单号: ${code}`);
|
||||
if (keyword) {
|
||||
filterSummary.push(searchFields ? `关键字: ${keyword} (字段: ${searchFields})` : `关键字: ${keyword}`);
|
||||
}
|
||||
if (stage) filterSummary.push(`阶段: ${stage}`);
|
||||
if (state) filterSummary.push(`状态: ${state}`);
|
||||
const filterTag = filterSummary.length > 0 ? ` | 筛选: ${filterSummary.join(", ")}` : "";
|
||||
|
||||
const tableOutput = printTable(headers, rows);
|
||||
const title = `====== 单据与费用明细列表 (企业: ${corp.name}${filterTag} | 匹配总数: ${result.total} | 本次返回: ${result.returned}) ======\n`;
|
||||
const tip = `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`;
|
||||
|
||||
return {
|
||||
stdout: title + tableOutput + tip,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
case "get":
|
||||
case "show":
|
||||
case "find": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供要查询的单号或单据 ID: hose-use bill get <单号|ID>");
|
||||
}
|
||||
|
||||
const bills = await getBillByCodeOrId(await getClient(), corpId, target);
|
||||
|
||||
if (bills.length === 0) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ found: false, code: target, message: "未找到匹配单据" }),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 在企业 [${corp.name}] 下未找到单号或 ID 为 [${target}] 的单据\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const withRisk = booleanOption(parsed.options, ["risk", "with-risk", "audit"]);
|
||||
const riskReports = withRisk
|
||||
? await Promise.all(bills.map(async (bill) => getBillRisk(await getClient(), corpId, bill.billId || bill.billCode)))
|
||||
: [];
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
count: bills.length,
|
||||
bills: bills.map((bill, index) => withRisk ? { ...bill, risk: riskReports[index] ?? null } : bill),
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const outputs: string[] = [];
|
||||
for (let i = 0; i < bills.length; i++) {
|
||||
const b = bills[i];
|
||||
outputs.push(`\n====== 单据详情 [${i + 1}/${bills.length}] (单号: ${b.billCode}) ======`);
|
||||
outputs.push(` 单据 ID : ${b.billId}`);
|
||||
outputs.push(` 单据名称 : ${b.billName}`);
|
||||
if (b.title) outputs.push(` 单据标题 : ${b.title}`);
|
||||
if (b.stage) outputs.push(` 业务阶段 : ${b.stage}`);
|
||||
if (b.state) outputs.push(` 审批状态 : ${b.state}`);
|
||||
if (b.amount) outputs.push(` 单据金额 : ${b.amount}`);
|
||||
if (b.submitterId) outputs.push(` 提交人员 : ${b.submitterId}`);
|
||||
if (b.submitDate) outputs.push(` 提交时间 : ${b.submitDate}`);
|
||||
outputs.push(` 创建时间 : ${b.createTime}`);
|
||||
outputs.push(` 更新时间 : ${b.updateTime}`);
|
||||
outputs.push(`\n --- 结构化表单字段明细 ---`);
|
||||
|
||||
const detailEntries = Object.entries(b.details);
|
||||
if (detailEntries.length === 0) {
|
||||
outputs.push(` (无额外字段数据)`);
|
||||
} else {
|
||||
const maxKeyLen = Math.max(...detailEntries.map(([k]) => k.length), 0);
|
||||
for (const [k, v] of detailEntries) {
|
||||
const formattedVal = typeof v === "object" ? JSON.stringify(v) : String(v);
|
||||
outputs.push(` ${k.padEnd(maxKeyLen + 2)}: ${formattedVal}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (withRisk) {
|
||||
const risk = riskReports[i];
|
||||
outputs.push(`\n --- 费控风控与合规风险提示 ---`);
|
||||
if (!risk) {
|
||||
outputs.push(" (未找到审批流程风控快照)");
|
||||
} else {
|
||||
outputs.push(` 风控流程 ID : ${risk.flowId}`);
|
||||
outputs.push(` 预算超限 : ${risk.budgetExceeded ? "是" : "否"}`);
|
||||
if (risk.warnings.length === 0 && risk.invoiceWarnings.length === 0) {
|
||||
outputs.push(" 风险预警 : (暂无风险预警)");
|
||||
} else {
|
||||
for (const warning of risk.warnings) {
|
||||
outputs.push(` [${warning.riskLevel || "提示"}] ${warning.controlName || warning.title || warning.type || "风控规则"}: ${warning.messages.join(";") || "-"}`);
|
||||
}
|
||||
outputs.push(` 发票风险 : ${risk.invoiceWarnings.length} 条`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: outputs.join("\n") + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
case "schema":
|
||||
case "schemas":
|
||||
case "entities": {
|
||||
const { entities } = await getFieldDictionary(await getClient(), corpId, true);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
totalEntities: entities.length,
|
||||
entities,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "实体 ID", "实体名称", "类型", "字段数"];
|
||||
const rows = entities.map((e, idx) => [
|
||||
idx + 1,
|
||||
e.id,
|
||||
e.name || "-",
|
||||
e.type || "-",
|
||||
e.fields.length,
|
||||
]);
|
||||
|
||||
const tableOutput = printTable(headers, rows);
|
||||
const title = `====== 单据实体与数据模型字典 (企业: ${corp.name} | 共 ${entities.length} 个实体) ======\n`;
|
||||
return {
|
||||
stdout: title + tableOutput + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
case "flow":
|
||||
case "records":
|
||||
case "timeline": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询流程的单号或单据 ID: hose-use bill flow <单号|ID>");
|
||||
const flow = await getBillFlow(await getClient(), corpId, target);
|
||||
if (!flow) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据流程: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...flow }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const historyRows = flow.history.map((entry) => [
|
||||
entry.time ? new Date(entry.time).toLocaleString("zh-CN") : "-",
|
||||
entry.nodeName || "-",
|
||||
entry.action || "-",
|
||||
formatBillFlowOperator(entry.operator, entry.automatic, entry.operator?.id?.toLowerCase().includes("ebot")),
|
||||
entry.durationMs !== undefined ? `${Math.round(entry.durationMs / 1000)} 秒` : "-",
|
||||
entry.skipped ? "自动跳过" : entry.automatic ? "自动" : "",
|
||||
entry.comment || "-",
|
||||
]);
|
||||
const pendingRows = flow.pending.map((node) => [
|
||||
node.state || "-",
|
||||
node.name || "-",
|
||||
node.type || "-",
|
||||
node.approver?.name || node.approvers?.map((person) => person.name).filter(Boolean).join(", ") || "-",
|
||||
]);
|
||||
const output = [
|
||||
`====== 审批流程 (单号: ${flow.billCode || target} | 状态: ${flow.state || "-"}) ======`,
|
||||
`流程 ID: ${flow.flowId || "-"} 当前节点: ${flow.currentNode || "-"}`,
|
||||
"",
|
||||
"--- 历史流转 ---",
|
||||
flow.history.length ? printTable(["时间", "节点", "动作", "处理人", "停留时长", "标记", "意见"], historyRows) : " (暂无历史记录)",
|
||||
"",
|
||||
"--- 后续节点 ---",
|
||||
flow.pending.length ? printTable(["状态", "节点", "类型", "审批人"], pendingRows) : " (暂无后续节点)",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "risk":
|
||||
case "review":
|
||||
case "warnings": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询风控结果的单号或单据 ID: hose-use bill risk <单号|ID>");
|
||||
const report = await getBillRisk(await getClient(), corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据风控结果: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const warningRows = report.warnings.map((warning) => [
|
||||
warning.riskLevel || "-",
|
||||
warning.type || "-",
|
||||
warning.controlName || warning.title || "-",
|
||||
warning.messages.join(";") || "-",
|
||||
]);
|
||||
const output = [
|
||||
`====== 单据风控审查 (流程: ${report.flowId}) ======`,
|
||||
`预算超限: ${report.budgetExceeded ? "是" : "否"}`,
|
||||
"",
|
||||
"--- 风险预警 ---",
|
||||
report.warnings.length ? printTable(["等级", "类型", "规则", "提示"], warningRows) : " (暂无风险预警)",
|
||||
`发票风险: ${report.invoiceWarnings.length} 条`,
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "budget":
|
||||
case "budgets": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询预算状态的单号或单据 ID: hose-use bill budget <单号|ID>");
|
||||
const report = await getBillRisk(await getClient(), corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据预算状态: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, flowId: report.flowId, budgetExceeded: report.budgetExceeded, budget: report.budget || {} }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const budget = report.budget || {};
|
||||
const output = [
|
||||
`====== 单据预算状态 (流程: ${report.flowId}) ======`,
|
||||
`预算超限: ${report.budgetExceeded ? "是" : "否"}`,
|
||||
`状态: ${typeof budget.status === "string" ? budget.status : "-"}`,
|
||||
`可用余额: ${budget.availableAmount ?? budget.available ?? "-"}`,
|
||||
`占用金额: ${budget.occupiedAmount ?? budget.occupied ?? "-"}`,
|
||||
`预算明细: ${Object.keys(budget).length ? JSON.stringify(budget) : "-"}`,
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "refs":
|
||||
case "references":
|
||||
case "resolve": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要解析引用的单号或单据 ID: hose-use bill refs <单号|ID>");
|
||||
const report = await getBillReferences(await getClient(), corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据引用: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const person = (value: typeof report.submitter) => value ? `${value.name || "未解析"}${value.code ? ` (${value.code})` : ""} [${value.id}]` : "-";
|
||||
const output = [
|
||||
`====== 单据引用解析 (单号: ${report.billCode || target}) ======`,
|
||||
`标题: ${report.title || "-"}`,
|
||||
`提交人: ${person(report.submitter)}`,
|
||||
`归属人: ${person(report.owner)}`,
|
||||
`费用承担部门: ${report.department?.path || report.department?.name || "-"}${report.department?.id ? ` [${report.department.id}]` : ""}`,
|
||||
`法人实体: ${report.legalEntity ? `${report.legalEntity.name || "未解析"}${report.legalEntity.id ? ` [${report.legalEntity.id}]` : ""}` : "-"}`,
|
||||
`费用类型: ${report.feeTypes.length ? report.feeTypes.map((item) => `${item.name || "未解析"}${item.code ? ` (${item.code})` : ""} [${item.id}]`).join("、") : "-"}`,
|
||||
`核算维度: ${report.dimensions.length ? report.dimensions.map((item) => `${item.name || "未解析"}${item.code ? ` (${item.code})` : ""} [${item.id}]`).join("、") : "-"}`,
|
||||
report.unresolved.length ? `未解析 ID: ${report.unresolved.join("、")}` : "引用均已解析",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "relations":
|
||||
case "relation":
|
||||
case "links": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询关联关系的单号或单据 ID: hose-use bill relations <单号|ID>");
|
||||
const report = await getBillRelations(await getClient(), corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据关联关系: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const rows: string[][] = [];
|
||||
const visit = (node: typeof report.relations[number], depth = 0) => {
|
||||
rows.push([
|
||||
`${" ".repeat(depth)}${node.relation}`,
|
||||
node.code || node.id || "-",
|
||||
node.title || "-",
|
||||
node.amount || "-",
|
||||
]);
|
||||
for (const child of node.children) visit(child, depth + 1);
|
||||
};
|
||||
for (const node of report.relations) visit(node);
|
||||
const output = [
|
||||
`====== 单据关联关系 (单号: ${report.billCode || target}) ======`,
|
||||
`标题: ${report.title || "-"}`,
|
||||
rows.length ? printTable(["关系", "关联 ID/单号", "标题/名称", "金额"], rows) : "暂无可识别的前置单据、冲借款或合同关联",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "attachments":
|
||||
case "attachment":
|
||||
case "files": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询附件的单号或单据 ID: hose-use bill attachments <单号|ID>");
|
||||
const report = await getBillAttachments(await getClient(), corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据附件: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const rows = report.attachments.map((item) => [item.fileName || "-", item.fileId || "-", item.key || "-", item.url || "-"]);
|
||||
const output = [
|
||||
`====== 单据附件 (单号: ${report.billCode || target}) ======`,
|
||||
report.attachments.length ? printTable(["文件名", "fileId", "key", "URL"], rows) : "暂无附件或发票原件",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "download":
|
||||
case "file-download": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要下载附件的单号或单据 ID: hose-use bill download <单号|ID>");
|
||||
const outputDir = stringOption(parsed.options, ["output-dir", "dir"]) || `${process.cwd()}/downloads`;
|
||||
const fileId = stringOption(parsed.options, ["file-id", "file"]);
|
||||
const result = await downloadBillAttachments(await getClient(), corpId, target, outputDir, fileId);
|
||||
const summary = {
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
target: result.target,
|
||||
outputDir: result.outputDir,
|
||||
requestedFileId: result.requestedFileId,
|
||||
downloaded: result.downloaded,
|
||||
skipped: result.skipped,
|
||||
};
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(summary, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const rows = result.downloaded.map((item) => [item.fileName || item.key || item.fileId || "-", item.bytes, item.path]);
|
||||
const output = [
|
||||
`====== 单据附件下载 (单号: ${target}) ======`,
|
||||
`输出目录: ${result.outputDir}`,
|
||||
rows.length ? printTable(["文件名", "字节数", "本地路径"], rows) : "没有可下载的附件",
|
||||
result.skipped ? `跳过 ${result.skipped} 个缺少下载地址的附件` : "",
|
||||
"",
|
||||
].filter(Boolean).join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
case "link":
|
||||
case "url": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id", "c"]);
|
||||
if (!target) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use bill link <单号或ID>",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const items = await getBillByCodeOrId(await getClient(), corpId, target);
|
||||
if (!items || items.length === 0) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未找到单据: ${target}`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const item = items[0];
|
||||
const billId = item.billId;
|
||||
const billCode = item.billCode || target;
|
||||
const baseUrl = (corp.baseUrl || "https://app.ekuaibao.com").replace(/\/+$/, "");
|
||||
const webUrl = `${baseUrl}/#/invoice/detail?id=${encodeURIComponent(billId)}&corporationId=${encodeURIComponent(corpId)}`;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
code: billCode,
|
||||
id: billId,
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
url: webUrl,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const text = [
|
||||
`====== 合思单据 Web 直达链接 ======`,
|
||||
` 单据编号: ${billCode}`,
|
||||
` 单据 ID : ${billId}`,
|
||||
` 所属企业: ${corp.name} (${corpId})`,
|
||||
` 直达链接:`,
|
||||
` ${webUrl}`,
|
||||
``,
|
||||
`Markdown 链接: [查看单据 ${billCode}](${webUrl})`,
|
||||
].join("\n");
|
||||
|
||||
return {
|
||||
stdout: text + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
case "spec":
|
||||
case "specification": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["id", "spec", "specification", "specification-id", "specificationId"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供单据模板 ID (specificationId): hose-use bill spec <specificationId>");
|
||||
}
|
||||
|
||||
const inspection = await inspectFormSpecification(await getClient(), corpId, target);
|
||||
if (!inspection) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ found: false, specificationId: target }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 未找到单据模板定义: ${target}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const { specification: spec, warnings } = inspection;
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
...spec,
|
||||
warnings,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = spec.components.map((comp, idx) => {
|
||||
const priorityStr = formatFormPriorityList(comp.priorityList);
|
||||
const overrideRisk = hasLinkageOverridePriority(comp.priorityList) ? "⚠️ 联动覆盖手动" : "-";
|
||||
return [
|
||||
idx + 1,
|
||||
comp.name,
|
||||
comp.label || "-",
|
||||
comp.type,
|
||||
comp.optional === false ? "🔴 必填" : "⚪ 选填",
|
||||
comp.isLinkageAssignment ? "🟢 开启(true)" : "⚪ 关闭(false)",
|
||||
comp.assignmentRule || "-",
|
||||
priorityStr,
|
||||
overrideRisk,
|
||||
];
|
||||
});
|
||||
|
||||
const outLines = [
|
||||
`====== 单据模板定义 (${spec.name || spec.id}) ======`,
|
||||
` 模板 ID : ${spec.id}`,
|
||||
` 模板名称 : ${spec.name || "-"}`,
|
||||
` 单据类型 : ${spec.type || "-"}`,
|
||||
` 状态 : ${spec.active ? "🟢 启用" : "🔴 停用"}`,
|
||||
` 字段总数 : ${spec.components.length} 个`,
|
||||
"",
|
||||
rows.length
|
||||
? printTable(
|
||||
["#", "字段标识 (name)", "显示名称 (label)", "类型 (type)", "必填", "联动赋值 (isLinkageAssignment)", "联动规则 (assignmentRule)", "赋值优先级 (priorityList)", "覆盖风险"],
|
||||
rows
|
||||
)
|
||||
: "暂无表单组件定义",
|
||||
];
|
||||
|
||||
if (warnings.length > 0) {
|
||||
outLines.push("");
|
||||
outLines.push("── ⚠️ 联动赋值与优先级诊断 ──");
|
||||
for (const w of warnings) {
|
||||
outLines.push(` • ${w}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], spec <specificationId>, refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { addNodeBill, approveBill, commentBill, rejectBill, transferBill } from "../../../domains/bill/tools.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview } from "../../mutation.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
export async function handleApprove(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corpId } = ctx;
|
||||
await ctx.requireWriteConfirmation();
|
||||
const target = ctx.actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill approve <单号|ID> --yes");
|
||||
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "同意单据审批", target, ctx.actionOptions());
|
||||
const result = await approveBill(await ctx.getClient(), corpId, target, ctx.actionOptions());
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `审批同意成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleReject(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corpId } = ctx;
|
||||
await ctx.requireWriteConfirmation();
|
||||
const target = ctx.actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill reject <单号|ID> --comment <原因> --yes");
|
||||
const options = ctx.actionOptions();
|
||||
if (!options.comment?.trim()) throw new Error("驳回原因不能为空,请通过 --comment 提供原因");
|
||||
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "驳回单据审批", target, options);
|
||||
const result = await rejectBill(await ctx.getClient(), corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `驳回成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleTransfer(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corpId } = ctx;
|
||||
await ctx.requireWriteConfirmation();
|
||||
const target = ctx.actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill transfer <单号|ID> --approver-id <员工ID> --yes");
|
||||
const rawOptions = ctx.actionOptions();
|
||||
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "转交单据审批", target, rawOptions);
|
||||
const options = { ...rawOptions, approverIds: await ctx.resolveApproverIds(rawOptions.approverIds) };
|
||||
const result = await transferBill(await ctx.getClient(), corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `转交审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleAddNode(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corpId } = ctx;
|
||||
await ctx.requireWriteConfirmation();
|
||||
const target = ctx.actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill add-node <单号|ID> --approver-id <员工ID> --yes");
|
||||
const rawOptions = ctx.actionOptions();
|
||||
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "单据加签", target, rawOptions);
|
||||
const options = { ...rawOptions, approverIds: await ctx.resolveApproverIds(rawOptions.approverIds) };
|
||||
const result = await addNodeBill(await ctx.getClient(), corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `加签审批成功\n单号: ${result.billCode || target}\n任务 ID: ${result.backlogId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleComment(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corpId } = ctx;
|
||||
await ctx.requireWriteConfirmation();
|
||||
const target = ctx.actionTarget();
|
||||
if (!target) throw new Error("请提供单号或单据 ID: hose-use bill comment <单号|ID> --comment <内容> --yes");
|
||||
const options = ctx.actionOptions();
|
||||
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "添加单据评论", target, options);
|
||||
const result = await commentBill(await ctx.getClient(), corpId, target, options);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `单据评论成功\n单号: ${result.billCode || target}\n流程 ID: ${result.flowId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { createSessionClient } from "../../../core/http/session-client.js";
|
||||
import { resolveBillStaffIds } from "../../../domains/bill/tools.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { isDryRun, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||
|
||||
/**
|
||||
* bill 命令族共享的执行上下文:封装 corp 解析、会话客户端懒加载缓存、
|
||||
* 写确认与审批动作选项解析。由 handleBillCommand 每次调用时构建一次。
|
||||
*/
|
||||
export type BillActionContext = ReturnType<typeof createBillActionContext>;
|
||||
|
||||
export function createBillActionContext(parsed: CliParsedArgs, runtime: CliRuntime) {
|
||||
const corp = runtime.selectedCorp!;
|
||||
const action = parsed.action?.toLowerCase();
|
||||
const corpId = corp.corpId || corp.id;
|
||||
let client: Awaited<ReturnType<typeof createSessionClient>> | undefined;
|
||||
const getClient = async () => {
|
||||
client ??= await createSessionClient(corp);
|
||||
return client;
|
||||
};
|
||||
|
||||
const actionTarget = () => parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
const requireWriteConfirmation = async () => {
|
||||
if (isDryRun(parsed, runtime) || booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])) return;
|
||||
if (!process.stdin.isTTY || !process.stdout.isTTY || Boolean(process.env.CI) || process.env.NODE_ENV === "test") {
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"单据审批动作",
|
||||
`hose-use bill ${action || "approve"} ${actionTarget() || "<单号|ID>"} --yes`
|
||||
);
|
||||
}
|
||||
const { prompt } = await import("../../helpers.js");
|
||||
const answer = await prompt("该操作会改变单据状态,确认继续?输入 yes 继续: ");
|
||||
if (!/^(y|yes|是)$/i.test(answer.trim())) throw new Error("已取消审批动作");
|
||||
};
|
||||
const listOption = (keys: string[]): string[] | undefined => {
|
||||
const value = stringOption(parsed.options, keys);
|
||||
if (!value) return undefined;
|
||||
const values = value.split(",").map((item) => item.trim()).filter(Boolean);
|
||||
return values.length ? values : undefined;
|
||||
};
|
||||
const actionOptions = () => ({
|
||||
currentStaffId: corp.staffId || corp.credentials.staffId,
|
||||
reminder: booleanOption(parsed.options, ["reminder", "remind"]),
|
||||
keepItSecret: booleanOption(parsed.options, ["keep-it-secret", "secret", "private"]),
|
||||
comment: stringOption(parsed.options, ["comment", "message", "opinion"]),
|
||||
participants: listOption(["participant", "participants"]),
|
||||
approverIds: listOption(["approver", "approver-id", "approverIds", "staff", "staff-id", "to"]),
|
||||
rejectTo: stringOption(parsed.options, ["reject-to", "rejectTo"]),
|
||||
resubmitMethod: (stringOption(parsed.options, ["resubmit-method", "resubmitMethod"]) || "TO_REJECTOR").toUpperCase() as "TO_REJECTOR" | "FROM_START",
|
||||
addNodeType: ((): "PRE_ADD_NODE" | "AFT_ADD_NODE" => {
|
||||
const mode = (stringOption(parsed.options, ["mode", "add-node-type", "addNodeType"]) || "pre").toLowerCase();
|
||||
return mode === "post" || mode === "after" || mode === "aft" || mode === "aft_add_node" ? "AFT_ADD_NODE" : "PRE_ADD_NODE";
|
||||
})(),
|
||||
});
|
||||
const resolveApproverIds = async (values: string[] | undefined): Promise<string[]> => {
|
||||
if (!values?.length) throw new Error("请通过 --approver-id、--staff 或 --to 指定员工 ID、工号或姓名");
|
||||
return resolveBillStaffIds(await getClient(), corpId, values);
|
||||
};
|
||||
|
||||
return {
|
||||
parsed,
|
||||
runtime,
|
||||
corp,
|
||||
corpId,
|
||||
action,
|
||||
getClient,
|
||||
actionTarget,
|
||||
requireWriteConfirmation,
|
||||
listOption,
|
||||
actionOptions,
|
||||
resolveApproverIds,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { formatBillFlowOperator, getBillFlow, getBillRisk } from "../../../domains/bill/tools.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
export async function handleFlow(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询流程的单号或单据 ID: hose-use bill flow <单号|ID>");
|
||||
const flow = await getBillFlow(await ctx.getClient(), corpId, target);
|
||||
if (!flow) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据流程: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...flow }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const historyRows = flow.history.map((entry) => [
|
||||
entry.time ? new Date(entry.time).toLocaleString("zh-CN") : "-",
|
||||
entry.nodeName || "-",
|
||||
entry.action || "-",
|
||||
formatBillFlowOperator(entry.operator, entry.automatic, entry.operator?.id?.toLowerCase().includes("ebot")),
|
||||
entry.durationMs !== undefined ? `${Math.round(entry.durationMs / 1000)} 秒` : "-",
|
||||
entry.skipped ? "自动跳过" : entry.automatic ? "自动" : "",
|
||||
entry.comment || "-",
|
||||
]);
|
||||
const pendingRows = flow.pending.map((node) => [
|
||||
node.state || "-",
|
||||
node.name || "-",
|
||||
node.type || "-",
|
||||
node.approver?.name || node.approvers?.map((person) => person.name).filter(Boolean).join(", ") || "-",
|
||||
]);
|
||||
const output = [
|
||||
`====== 审批流程 (单号: ${flow.billCode || target} | 状态: ${flow.state || "-"}) ======`,
|
||||
`流程 ID: ${flow.flowId || "-"} 当前节点: ${flow.currentNode || "-"}`,
|
||||
"",
|
||||
"--- 历史流转 ---",
|
||||
flow.history.length ? printTable(["时间", "节点", "动作", "处理人", "停留时长", "标记", "意见"], historyRows) : " (暂无历史记录)",
|
||||
"",
|
||||
"--- 后续节点 ---",
|
||||
flow.pending.length ? printTable(["状态", "节点", "类型", "审批人"], pendingRows) : " (暂无后续节点)",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleRisk(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询风控结果的单号或单据 ID: hose-use bill risk <单号|ID>");
|
||||
const report = await getBillRisk(await ctx.getClient(), corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据风控结果: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const warningRows = report.warnings.map((warning) => [
|
||||
warning.riskLevel || "-",
|
||||
warning.type || "-",
|
||||
warning.controlName || warning.title || "-",
|
||||
warning.messages.join(";") || "-",
|
||||
]);
|
||||
const output = [
|
||||
`====== 单据风控审查 (流程: ${report.flowId}) ======`,
|
||||
`预算超限: ${report.budgetExceeded ? "是" : "否"}`,
|
||||
"",
|
||||
"--- 风险预警 ---",
|
||||
report.warnings.length ? printTable(["等级", "类型", "规则", "提示"], warningRows) : " (暂无风险预警)",
|
||||
`发票风险: ${report.invoiceWarnings.length} 条`,
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleBudget(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询预算状态的单号或单据 ID: hose-use bill budget <单号|ID>");
|
||||
const report = await getBillRisk(await ctx.getClient(), corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据预算状态: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, flowId: report.flowId, budgetExceeded: report.budgetExceeded, budget: report.budget || {} }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const budget = report.budget || {};
|
||||
const output = [
|
||||
`====== 单据预算状态 (流程: ${report.flowId}) ======`,
|
||||
`预算超限: ${report.budgetExceeded ? "是" : "否"}`,
|
||||
`状态: ${typeof budget.status === "string" ? budget.status : "-"}`,
|
||||
`可用余额: ${budget.availableAmount ?? budget.available ?? "-"}`,
|
||||
`占用金额: ${budget.occupiedAmount ?? budget.occupied ?? "-"}`,
|
||||
`预算明细: ${Object.keys(budget).length ? JSON.stringify(budget) : "-"}`,
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createBillActionContext } from "./context.js";
|
||||
import { handleApprove, handleReject, handleTransfer, handleAddNode, handleComment } from "./approve.js";
|
||||
import { handleList, handleGet } from "./search.js";
|
||||
import { handleFlow, handleRisk, handleBudget } from "./flow.js";
|
||||
import { handleRefs, handleRelations, handleAttachments, handleDownload } from "./related.js";
|
||||
import { handleSchema, handleLink, handleSpec } from "./meta.js";
|
||||
|
||||
export async function handleBillCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) {
|
||||
throw new Error(
|
||||
"未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。"
|
||||
);
|
||||
}
|
||||
|
||||
const ctx = createBillActionContext(parsed, runtime);
|
||||
const action = ctx.action;
|
||||
|
||||
switch (action) {
|
||||
case "approve":
|
||||
case "agree":
|
||||
return handleApprove(ctx);
|
||||
|
||||
case "reject":
|
||||
case "deny":
|
||||
return handleReject(ctx);
|
||||
|
||||
case "transfer":
|
||||
case "shift":
|
||||
return handleTransfer(ctx);
|
||||
|
||||
case "add-node":
|
||||
case "addnode":
|
||||
case "countersign":
|
||||
case "counter-sign":
|
||||
return handleAddNode(ctx);
|
||||
|
||||
case "comment":
|
||||
case "remark":
|
||||
return handleComment(ctx);
|
||||
|
||||
case "list":
|
||||
case "search":
|
||||
case undefined:
|
||||
return handleList(ctx);
|
||||
|
||||
case "get":
|
||||
case "show":
|
||||
case "find":
|
||||
return handleGet(ctx);
|
||||
|
||||
case "schema":
|
||||
case "schemas":
|
||||
case "entities":
|
||||
return handleSchema(ctx);
|
||||
|
||||
case "flow":
|
||||
case "records":
|
||||
case "timeline":
|
||||
return handleFlow(ctx);
|
||||
|
||||
case "risk":
|
||||
case "review":
|
||||
case "warnings":
|
||||
return handleRisk(ctx);
|
||||
|
||||
case "budget":
|
||||
case "budgets":
|
||||
return handleBudget(ctx);
|
||||
|
||||
case "refs":
|
||||
case "references":
|
||||
case "resolve":
|
||||
return handleRefs(ctx);
|
||||
|
||||
case "relations":
|
||||
case "relation":
|
||||
case "links":
|
||||
return handleRelations(ctx);
|
||||
|
||||
case "attachments":
|
||||
case "attachment":
|
||||
case "files":
|
||||
return handleAttachments(ctx);
|
||||
|
||||
case "download":
|
||||
case "file-download":
|
||||
return handleDownload(ctx);
|
||||
|
||||
case "link":
|
||||
case "url":
|
||||
return handleLink(ctx);
|
||||
|
||||
case "spec":
|
||||
case "specification":
|
||||
return handleSpec(ctx);
|
||||
|
||||
default:
|
||||
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号> [--risk], spec <specificationId>, refs <单号>, relations <单号>, attachments <单号>, download <单号>, flow <单号>, risk <单号>, budget <单号>, schema, link <单号>`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import {
|
||||
formatFormPriorityList,
|
||||
getFieldDictionary,
|
||||
getBillByCodeOrId,
|
||||
hasLinkageOverridePriority,
|
||||
inspectFormSpecification,
|
||||
} from "../../../domains/bill/tools.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
export async function handleSchema(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { runtime, corp, corpId } = ctx;
|
||||
const { entities } = await getFieldDictionary(await ctx.getClient(), corpId, true);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
totalEntities: entities.length,
|
||||
entities,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "实体 ID", "实体名称", "类型", "字段数"];
|
||||
const rows = entities.map((e, idx) => [
|
||||
idx + 1,
|
||||
e.id,
|
||||
e.name || "-",
|
||||
e.type || "-",
|
||||
e.fields.length,
|
||||
]);
|
||||
|
||||
const tableOutput = printTable(headers, rows);
|
||||
const title = `====== 单据实体与数据模型字典 (企业: ${corp.name} | 共 ${entities.length} 个实体) ======\n`;
|
||||
return {
|
||||
stdout: title + tableOutput + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleLink(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id", "c"]);
|
||||
if (!target) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use bill link <单号或ID>",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const items = await getBillByCodeOrId(await ctx.getClient(), corpId, target);
|
||||
if (!items || items.length === 0) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未找到单据: ${target}`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const item = items[0];
|
||||
const billId = item.billId;
|
||||
const billCode = item.billCode || target;
|
||||
const baseUrl = (corp.baseUrl || "https://app.ekuaibao.com").replace(/\/+$/, "");
|
||||
const webUrl = `${baseUrl}/#/invoice/detail?id=${encodeURIComponent(billId)}&corporationId=${encodeURIComponent(corpId)}`;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
code: billCode,
|
||||
id: billId,
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
url: webUrl,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const text = [
|
||||
`====== 合思单据 Web 直达链接 ======`,
|
||||
` 单据编号: ${billCode}`,
|
||||
` 单据 ID : ${billId}`,
|
||||
` 所属企业: ${corp.name} (${corpId})`,
|
||||
` 直达链接:`,
|
||||
` ${webUrl}`,
|
||||
``,
|
||||
`Markdown 链接: [查看单据 ${billCode}](${webUrl})`,
|
||||
].join("\n");
|
||||
|
||||
return {
|
||||
stdout: text + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleSpec(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["id", "spec", "specification", "specification-id", "specificationId"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供单据模板 ID (specificationId): hose-use bill spec <specificationId>");
|
||||
}
|
||||
|
||||
const inspection = await inspectFormSpecification(await ctx.getClient(), corpId, target);
|
||||
if (!inspection) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ found: false, specificationId: target }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 未找到单据模板定义: ${target}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const { specification: spec, warnings } = inspection;
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
...spec,
|
||||
warnings,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = spec.components.map((comp, idx) => {
|
||||
const priorityStr = formatFormPriorityList(comp.priorityList);
|
||||
const overrideRisk = hasLinkageOverridePriority(comp.priorityList) ? "⚠️ 联动覆盖手动" : "-";
|
||||
return [
|
||||
idx + 1,
|
||||
comp.name,
|
||||
comp.label || "-",
|
||||
comp.type,
|
||||
comp.optional === false ? "🔴 必填" : "⚪ 选填",
|
||||
comp.isLinkageAssignment ? "🟢 开启(true)" : "⚪ 关闭(false)",
|
||||
comp.assignmentRule || "-",
|
||||
priorityStr,
|
||||
overrideRisk,
|
||||
];
|
||||
});
|
||||
|
||||
const outLines = [
|
||||
`====== 单据模板定义 (${spec.name || spec.id}) ======`,
|
||||
` 模板 ID : ${spec.id}`,
|
||||
` 模板名称 : ${spec.name || "-"}`,
|
||||
` 单据类型 : ${spec.type || "-"}`,
|
||||
` 状态 : ${spec.active ? "🟢 启用" : "🔴 停用"}`,
|
||||
` 字段总数 : ${spec.components.length} 个`,
|
||||
"",
|
||||
rows.length
|
||||
? printTable(
|
||||
["#", "字段标识 (name)", "显示名称 (label)", "类型 (type)", "必填", "联动赋值 (isLinkageAssignment)", "联动规则 (assignmentRule)", "赋值优先级 (priorityList)", "覆盖风险"],
|
||||
rows
|
||||
)
|
||||
: "暂无表单组件定义",
|
||||
];
|
||||
|
||||
if (warnings.length > 0) {
|
||||
outLines.push("");
|
||||
outLines.push("── ⚠️ 联动赋值与优先级诊断 ──");
|
||||
for (const w of warnings) {
|
||||
outLines.push(` • ${w}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { downloadBillAttachments, getBillAttachments, getBillReferences, getBillRelations } from "../../../domains/bill/tools.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
export async function handleRefs(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要解析引用的单号或单据 ID: hose-use bill refs <单号|ID>");
|
||||
const report = await getBillReferences(await ctx.getClient(), corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据引用: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const person = (value: typeof report.submitter) => value ? `${value.name || "未解析"}${value.code ? ` (${value.code})` : ""} [${value.id}]` : "-";
|
||||
const output = [
|
||||
`====== 单据引用解析 (单号: ${report.billCode || target}) ======`,
|
||||
`标题: ${report.title || "-"}`,
|
||||
`提交人: ${person(report.submitter)}`,
|
||||
`归属人: ${person(report.owner)}`,
|
||||
`费用承担部门: ${report.department?.path || report.department?.name || "-"}${report.department?.id ? ` [${report.department.id}]` : ""}`,
|
||||
`法人实体: ${report.legalEntity ? `${report.legalEntity.name || "未解析"}${report.legalEntity.id ? ` [${report.legalEntity.id}]` : ""}` : "-"}`,
|
||||
`费用类型: ${report.feeTypes.length ? report.feeTypes.map((item) => `${item.name || "未解析"}${item.code ? ` (${item.code})` : ""} [${item.id}]`).join("、") : "-"}`,
|
||||
`核算维度: ${report.dimensions.length ? report.dimensions.map((item) => `${item.name || "未解析"}${item.code ? ` (${item.code})` : ""} [${item.id}]`).join("、") : "-"}`,
|
||||
report.unresolved.length ? `未解析 ID: ${report.unresolved.join("、")}` : "引用均已解析",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleRelations(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询关联关系的单号或单据 ID: hose-use bill relations <单号|ID>");
|
||||
const report = await getBillRelations(await ctx.getClient(), corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据关联关系: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const rows: string[][] = [];
|
||||
const visit = (node: typeof report.relations[number], depth = 0) => {
|
||||
rows.push([
|
||||
`${" ".repeat(depth)}${node.relation}`,
|
||||
node.code || node.id || "-",
|
||||
node.title || "-",
|
||||
node.amount || "-",
|
||||
]);
|
||||
for (const child of node.children) visit(child, depth + 1);
|
||||
};
|
||||
for (const node of report.relations) visit(node);
|
||||
const output = [
|
||||
`====== 单据关联关系 (单号: ${report.billCode || target}) ======`,
|
||||
`标题: ${report.title || "-"}`,
|
||||
rows.length ? printTable(["关系", "关联 ID/单号", "标题/名称", "金额"], rows) : "暂无可识别的前置单据、冲借款或合同关联",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleAttachments(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要查询附件的单号或单据 ID: hose-use bill attachments <单号|ID>");
|
||||
const report = await getBillAttachments(await ctx.getClient(), corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到单据附件: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const rows = report.attachments.map((item) => [item.fileName || "-", item.fileId || "-", item.key || "-", item.url || "-"]);
|
||||
const output = [
|
||||
`====== 单据附件 (单号: ${report.billCode || target}) ======`,
|
||||
report.attachments.length ? printTable(["文件名", "fileId", "key", "URL"], rows) : "暂无附件或发票原件",
|
||||
"",
|
||||
].join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleDownload(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) throw new Error("请提供要下载附件的单号或单据 ID: hose-use bill download <单号|ID>");
|
||||
const outputDir = stringOption(parsed.options, ["output-dir", "dir"]) || `${process.cwd()}/downloads`;
|
||||
const fileId = stringOption(parsed.options, ["file-id", "file"]);
|
||||
const result = await downloadBillAttachments(await ctx.getClient(), corpId, target, outputDir, fileId);
|
||||
const summary = {
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
target: result.target,
|
||||
outputDir: result.outputDir,
|
||||
requestedFileId: result.requestedFileId,
|
||||
downloaded: result.downloaded,
|
||||
skipped: result.skipped,
|
||||
};
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(summary, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
const rows = result.downloaded.map((item) => [item.fileName || item.key || item.fileId || "-", item.bytes, item.path]);
|
||||
const output = [
|
||||
`====== 单据附件下载 (单号: ${target}) ======`,
|
||||
`输出目录: ${result.outputDir}`,
|
||||
rows.length ? printTable(["文件名", "字节数", "本地路径"], rows) : "没有可下载的附件",
|
||||
result.skipped ? `跳过 ${result.skipped} 个缺少下载地址的附件` : "",
|
||||
"",
|
||||
].filter(Boolean).join("\n");
|
||||
return { stdout: output, stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import { getBillByCodeOrId, getBillRisk, searchAndFormatBills } from "../../../domains/bill/tools.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
import type { CliResult } from "../../types.js";
|
||||
import type { BillActionContext } from "./context.js";
|
||||
|
||||
export async function handleList(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const mine = booleanOption(parsed.options, ["mine", "my", "self"]);
|
||||
if (mine) {
|
||||
const { handleTaskCommand } = await import("./../task.js");
|
||||
return handleTaskCommand(
|
||||
{
|
||||
...parsed,
|
||||
area: "task",
|
||||
action: "submitted",
|
||||
},
|
||||
runtime
|
||||
);
|
||||
}
|
||||
|
||||
const code = stringOption(parsed.options, ["code", "c"]);
|
||||
const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"]);
|
||||
const searchFields = stringOption(parsed.options, ["search-fields", "searchFields", "search-field", "sf"]);
|
||||
const stage = stringOption(parsed.options, ["stage"]);
|
||||
const state = stringOption(parsed.options, ["state", "s"]);
|
||||
const count = numberOption(parsed.options, ["count", "limit", "n"], 20);
|
||||
const since = stringOption(parsed.options, ["since", "days", "d"]);
|
||||
const startDate = stringOption(parsed.options, ["start-date", "startDate", "from", "start"]);
|
||||
const endDate = stringOption(parsed.options, ["end-date", "endDate", "to", "end"]);
|
||||
const rawOrder = stringOption(parsed.options, ["order", "sort", "direction"]);
|
||||
const order = rawOrder && /asc/i.test(rawOrder) ? "ASC" : "DESC";
|
||||
const filterBy = stringOption(parsed.options, ["filter-by", "filterBy", "filter"]);
|
||||
const select = stringOption(parsed.options, ["select", "fields"]);
|
||||
const distinct = booleanOption(parsed.options, ["distinct"]);
|
||||
|
||||
const result = await searchAndFormatBills(await ctx.getClient(), corpId, {
|
||||
code,
|
||||
keyword,
|
||||
searchFields,
|
||||
stage,
|
||||
state,
|
||||
count,
|
||||
since,
|
||||
startDate,
|
||||
endDate,
|
||||
order,
|
||||
filterBy,
|
||||
select,
|
||||
distinct,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
total: result.total,
|
||||
returned: result.returned,
|
||||
items: result.items,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "单据编号 (单号)", "单据名称", "阶段", "状态", "金额", "提交时间"];
|
||||
const rows = result.items.map((b, idx) => [
|
||||
idx + 1,
|
||||
b.billCode,
|
||||
b.billName,
|
||||
b.stage || "-",
|
||||
b.state || "-",
|
||||
b.amount || "-",
|
||||
b.submitDate || b.createTime || "-",
|
||||
]);
|
||||
|
||||
const filterSummary: string[] = [];
|
||||
if (since) filterSummary.push(`近 ${since}`);
|
||||
if (startDate || endDate) filterSummary.push(`${startDate || "起"} ~ ${endDate || "止"}`);
|
||||
if (code) filterSummary.push(`单号: ${code}`);
|
||||
if (keyword) {
|
||||
filterSummary.push(searchFields ? `关键字: ${keyword} (字段: ${searchFields})` : `关键字: ${keyword}`);
|
||||
}
|
||||
if (stage) filterSummary.push(`阶段: ${stage}`);
|
||||
if (state) filterSummary.push(`状态: ${state}`);
|
||||
const filterTag = filterSummary.length > 0 ? ` | 筛选: ${filterSummary.join(", ")}` : "";
|
||||
|
||||
const tableOutput = printTable(headers, rows);
|
||||
const title = `====== 单据与费用明细列表 (企业: ${corp.name}${filterTag} | 匹配总数: ${result.total} | 本次返回: ${result.returned}) ======\n`;
|
||||
const tip = `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`;
|
||||
|
||||
return {
|
||||
stdout: title + tableOutput + tip,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleGet(ctx: BillActionContext): Promise<CliResult> {
|
||||
const { parsed, runtime, corp, corpId } = ctx;
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供要查询的单号或单据 ID: hose-use bill get <单号|ID>");
|
||||
}
|
||||
|
||||
const bills = await getBillByCodeOrId(await ctx.getClient(), corpId, target);
|
||||
|
||||
if (bills.length === 0) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ found: false, code: target, message: "未找到匹配单据" }),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 在企业 [${corp.name}] 下未找到单号或 ID 为 [${target}] 的单据\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const withRisk = booleanOption(parsed.options, ["risk", "with-risk", "audit"]);
|
||||
const riskReports = withRisk
|
||||
? await Promise.all(bills.map(async (bill) => getBillRisk(await ctx.getClient(), corpId, bill.billId || bill.billCode)))
|
||||
: [];
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
count: bills.length,
|
||||
bills: bills.map((bill, index) => withRisk ? { ...bill, risk: riskReports[index] ?? null } : bill),
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const outputs: string[] = [];
|
||||
for (let i = 0; i < bills.length; i++) {
|
||||
const b = bills[i];
|
||||
outputs.push(`\n====== 单据详情 [${i + 1}/${bills.length}] (单号: ${b.billCode}) ======`);
|
||||
outputs.push(` 单据 ID : ${b.billId}`);
|
||||
outputs.push(` 单据名称 : ${b.billName}`);
|
||||
if (b.title) outputs.push(` 单据标题 : ${b.title}`);
|
||||
if (b.stage) outputs.push(` 业务阶段 : ${b.stage}`);
|
||||
if (b.state) outputs.push(` 审批状态 : ${b.state}`);
|
||||
if (b.amount) outputs.push(` 单据金额 : ${b.amount}`);
|
||||
if (b.submitterId) outputs.push(` 提交人员 : ${b.submitterId}`);
|
||||
if (b.submitDate) outputs.push(` 提交时间 : ${b.submitDate}`);
|
||||
outputs.push(` 创建时间 : ${b.createTime}`);
|
||||
outputs.push(` 更新时间 : ${b.updateTime}`);
|
||||
outputs.push(`\n --- 结构化表单字段明细 ---`);
|
||||
|
||||
const detailEntries = Object.entries(b.details);
|
||||
if (detailEntries.length === 0) {
|
||||
outputs.push(` (无额外字段数据)`);
|
||||
} else {
|
||||
const maxKeyLen = Math.max(...detailEntries.map(([k]) => k.length), 0);
|
||||
for (const [k, v] of detailEntries) {
|
||||
const formattedVal = typeof v === "object" ? JSON.stringify(v) : String(v);
|
||||
outputs.push(` ${k.padEnd(maxKeyLen + 2)}: ${formattedVal}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (withRisk) {
|
||||
const risk = riskReports[i];
|
||||
outputs.push(`\n --- 费控风控与合规风险提示 ---`);
|
||||
if (!risk) {
|
||||
outputs.push(" (未找到审批流程风控快照)");
|
||||
} else {
|
||||
outputs.push(` 风控流程 ID : ${risk.flowId}`);
|
||||
outputs.push(` 预算超限 : ${risk.budgetExceeded ? "是" : "否"}`);
|
||||
if (risk.warnings.length === 0 && risk.invoiceWarnings.length === 0) {
|
||||
outputs.push(" 风险预警 : (暂无风险预警)");
|
||||
} else {
|
||||
for (const warning of risk.warnings) {
|
||||
outputs.push(` [${warning.riskLevel || "提示"}] ${warning.controlName || warning.title || warning.type || "风控规则"}: ${warning.messages.join(";") || "-"}`);
|
||||
}
|
||||
outputs.push(` 发票风险 : ${risk.invoiceWarnings.length} 条`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: outputs.join("\n") + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import { parseHeadersOrCurl } from "../../core/auth/login.js";
|
||||
import { resolveCorpCluster } from "../../core/http/unity-client.js";
|
||||
import { handleCorpsCommand } from "./corps.js";
|
||||
import { handleCorpsCommand } from "./corps/index.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
|
||||
describe("core/auth/login > parseHeadersOrCurl & URL link parsing", () => {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,95 @@
|
||||
import { canRefreshCorpAccessToken, hasOpenApiPersistentCredentials } from "../../../core/auth/login.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
|
||||
export async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const corpId = parsed.args[0];
|
||||
if (!corpId) {
|
||||
return { stdout: "", stderr: "用法: hose-use corps switch <企业ID>\n", exitCode: 1 };
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "切换当前工作企业", corpId, { defaultCorpId: corpId });
|
||||
}
|
||||
requireMutationConfirmation(parsed, runtime, "切换当前工作企业", `hose-use corps switch ${corpId} --yes`);
|
||||
|
||||
const success = runtime.corpContext.switchCorp(corpId);
|
||||
if (!success) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `企业 ${corpId} 不存在或未配置。可运行 hose-use corps list 查看可用列表。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const current = runtime.corpContext.getCurrent();
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 已切换到企业: ${current?.name} (${current?.id})\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const current = runtime.selectedCorp;
|
||||
if (!current) {
|
||||
return { stdout: "", stderr: "未选中任何企业\n", exitCode: 1 };
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const hasOpenApi = hasOpenApiPersistentCredentials(current);
|
||||
const isPersistent = canRefreshCorpAccessToken(current);
|
||||
|
||||
const pairs: Record<string, unknown> = {
|
||||
"企业 ID": current.id,
|
||||
"企业名称": current.name,
|
||||
"员工工号": current.credentials.staffId,
|
||||
"员工姓名": current.staffName || current.session?.staffName || "-",
|
||||
"凭证来源": formatSourceLabel(current.source, hasOpenApi),
|
||||
"持久化状态": isPersistent ? (hasOpenApi ? `✅ 已配置 OpenAPI 持久化密钥 (${current.credentials.appKey})` : "✅ 已绑定统一认证主账号") : "⚪ 短期临时会话",
|
||||
"Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime, isPersistent),
|
||||
"所属账号": current.accountId || "-",
|
||||
"主站地址": current.baseUrl || "https://app.ekuaibao.com",
|
||||
"适用上下文": "同时作为 hose-use 与 hose-aipro 的统一执行环境",
|
||||
};
|
||||
|
||||
if (current.session) {
|
||||
if (current.session.loginTime) {
|
||||
pairs["会话创建时间"] = new Date(current.session.loginTime).toLocaleString("zh-CN", { hour12: false });
|
||||
}
|
||||
if (current.session.platform) {
|
||||
pairs["官方平台类型"] = current.session.platform;
|
||||
}
|
||||
if (current.session.isAssistPlatform) {
|
||||
pairs["协助登录模式"] = "是 (Assist Platform)";
|
||||
if (current.session.operationUserName || current.session.operationUserId) {
|
||||
pairs["协助操作人员"] = `${current.session.operationUserName || ""} (${current.session.operationUserId || ""})`.trim();
|
||||
}
|
||||
if (current.session.assistId) {
|
||||
pairs["协助会话 ID"] = current.session.assistId;
|
||||
}
|
||||
}
|
||||
if (current.session.cellphone) {
|
||||
pairs["绑定手机号码"] = current.session.cellphone;
|
||||
}
|
||||
if (current.session.isAdmin !== undefined) {
|
||||
pairs["是否企业管理"] = current.session.isAdmin ? "是" : "否";
|
||||
}
|
||||
}
|
||||
|
||||
const output = printKeyValue(pairs);
|
||||
|
||||
return {
|
||||
stdout: `====== 当前激活企业 ======\n${output}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
elevateCorpWithOpenApiKey,
|
||||
extractOpenApiKeysFromLink,
|
||||
hasOpenApiPersistentCredentials,
|
||||
maskOpenApiSecurity,
|
||||
onboardHosePersistent,
|
||||
syncOpenApiFromSealUse,
|
||||
} from "../../../core/auth/login.js";
|
||||
import { resolveWritableEnterprisesDir } from "../../../core/config/loader.js";
|
||||
import { stringOption, booleanOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { resolveTargetCorpByArgOrContext } from "./shared.js";
|
||||
|
||||
export async function handleAddPersistent(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
let jsonPayload: Record<string, unknown> = {};
|
||||
const rawJsonArg = stringOption(parsed.options, ["data"]) || (parsed.args[0]?.trim().startsWith("{") ? parsed.args[0] : undefined);
|
||||
if (rawJsonArg) {
|
||||
try {
|
||||
jsonPayload = JSON.parse(rawJsonArg);
|
||||
} catch {
|
||||
return { stdout: "", stderr: "错误:提供的 JSON 参数无法解析\n", exitCode: 1 };
|
||||
}
|
||||
}
|
||||
|
||||
const appKey =
|
||||
stringOption(parsed.options, ["app-key", "appKey", "key"]) ||
|
||||
(typeof jsonPayload.appKey === "string" ? jsonPayload.appKey : undefined);
|
||||
const appSecurity =
|
||||
stringOption(parsed.options, ["app-security", "appSecurity", "secret", "password"]) ||
|
||||
(typeof jsonPayload.appSecurity === "string" ? jsonPayload.appSecurity : undefined);
|
||||
const domain =
|
||||
stringOption(parsed.options, ["domain", "base-url", "baseUrl"]) ||
|
||||
(typeof jsonPayload.domain === "string" ? jsonPayload.domain : undefined);
|
||||
const corpId =
|
||||
stringOption(parsed.options, ["corp-id", "corpId", "corp"]) ||
|
||||
(typeof jsonPayload.corpId === "string" ? jsonPayload.corpId : undefined);
|
||||
const staffId =
|
||||
stringOption(parsed.options, ["staff-id", "staffId", "proxyStaffBizId"]) ||
|
||||
(typeof jsonPayload.staffId === "string" ? jsonPayload.staffId : undefined);
|
||||
const staffName =
|
||||
stringOption(parsed.options, ["staff-name", "staffName"]) ||
|
||||
(typeof jsonPayload.staffName === "string" ? jsonPayload.staffName : undefined);
|
||||
const staffPhone =
|
||||
stringOption(parsed.options, ["staff-phone", "staffPhone"]) ||
|
||||
(typeof jsonPayload.staffPhone === "string" ? jsonPayload.staffPhone : undefined);
|
||||
const role =
|
||||
stringOption(parsed.options, ["role"]) ||
|
||||
(typeof jsonPayload.role === "string" ? jsonPayload.role : undefined);
|
||||
const name =
|
||||
stringOption(parsed.options, ["name"]) ||
|
||||
(typeof jsonPayload.name === "string" ? jsonPayload.name : undefined);
|
||||
const overwrite = booleanOption(parsed.options, ["overwrite"], Boolean(jsonPayload.overwrite));
|
||||
const force = booleanOption(parsed.options, ["force", "f"], Boolean(jsonPayload.force));
|
||||
|
||||
if (!appKey || !appSecurity) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "错误:必须提供 appKey 与 appSecurity!用法: hose-use corps add-persistent --app-key=<key> --app-security=<secret> [--staff-id=<id>] [--force] [--overwrite] --yes\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "通过 OpenAPI 持久化密钥接入企业", name || corpId || appKey, {
|
||||
source: "openapi",
|
||||
appKey,
|
||||
domain: domain || "auto-probe",
|
||||
staffId: staffId || "auto-discover",
|
||||
overwrite,
|
||||
});
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"通过 OpenAPI 持久化密钥接入企业",
|
||||
`hose-use corps add-persistent --app-key=${appKey} --app-security=<redacted> --yes`
|
||||
);
|
||||
|
||||
const saved = await onboardHosePersistent({
|
||||
name,
|
||||
appKey,
|
||||
appSecurity,
|
||||
domain,
|
||||
corpId,
|
||||
staffId,
|
||||
staffName,
|
||||
staffPhone,
|
||||
role,
|
||||
force,
|
||||
overwrite,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(saved, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const targetDir = resolveWritableEnterprisesDir();
|
||||
const savedPath = join(targetDir, `${saved.id}.json`);
|
||||
const summaryText = printKeyValue({
|
||||
"企业名称": saved.name,
|
||||
"企业 ID": saved.id,
|
||||
"服务节点": saved.baseUrl,
|
||||
"员工工号": saved.credentials.staffId,
|
||||
"员工姓名": saved.staffName || saved.session?.staffName || "-",
|
||||
"接入账号 (appKey)": saved.credentials.appKey,
|
||||
"凭证来源": formatSourceLabel(saved.source, true),
|
||||
"保存路径": savedPath,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 成功接入并持久化企业 OpenAPI 凭证!\n${summaryText}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleExtractKeys(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const linkUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
|
||||
if (!linkUrl) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use corps extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--overwrite]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const reveal = booleanOption(parsed.options, ["reveal", "r", "plain"], false);
|
||||
const save = booleanOption(parsed.options, ["save", "add", "persist"], false);
|
||||
const name = stringOption(parsed.options, ["name"]);
|
||||
const overwrite = booleanOption(parsed.options, ["overwrite"], true);
|
||||
const force = booleanOption(parsed.options, ["force", "f"], false);
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
|
||||
|
||||
if (save) {
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "从协助链接提取并持久化 OpenAPI 密钥", name || "待解析企业", {
|
||||
save: true,
|
||||
overwrite,
|
||||
appKey: appKey || "auto-select",
|
||||
});
|
||||
}
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"从协助链接提取并持久化 OpenAPI 密钥",
|
||||
`hose-use corps extract-keys "<url>" --save --yes`
|
||||
);
|
||||
}
|
||||
|
||||
const extracted = await extractOpenApiKeysFromLink(linkUrl, {
|
||||
save,
|
||||
name,
|
||||
overwrite,
|
||||
force,
|
||||
appKey,
|
||||
keyId,
|
||||
});
|
||||
|
||||
const formattedKeys = extracted.keys.map((k) => ({
|
||||
id: k.id,
|
||||
name: k.name || "-",
|
||||
appKey: k.appKey,
|
||||
appSecurity: reveal ? k.appSecurity : maskOpenApiSecurity(k.appSecurity),
|
||||
active: k.active,
|
||||
createTime: k.createTime,
|
||||
updateTime: k.updateTime,
|
||||
}));
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId: extracted.corpId,
|
||||
corpName: extracted.corpName || extracted.corpId,
|
||||
baseUrl: extracted.baseUrl,
|
||||
staffId: extracted.staffId,
|
||||
keyCount: formattedKeys.length,
|
||||
keys: formattedKeys,
|
||||
...(extracted.savedCorp ? { saved: true, savedCorpId: extracted.savedCorp.id } : {}),
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: reveal,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = formattedKeys.map((k, i) => [
|
||||
i + 1,
|
||||
k.name,
|
||||
k.appKey,
|
||||
k.appSecurity,
|
||||
k.active ? "🟢 启用" : "⚪ 停用",
|
||||
]);
|
||||
const table = printTable(["#", "应用名称", "appKey", "appSecurity", "状态"], rows);
|
||||
const savedNotice = extracted.savedCorp
|
||||
? `\n[SUCCESS] 已将密钥 (${extracted.selectedKey?.appKey}) 持久化保存至企业 [${extracted.savedCorp.name} (${extracted.savedCorp.id})]`
|
||||
: "";
|
||||
|
||||
return {
|
||||
stdout: `====== 协助链接 OpenAPI 密钥提取结果 (${extracted.corpName || extracted.corpId}) ======\n${table}${savedNotice}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: reveal,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleElevateCorp(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const elevateAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
|
||||
const force = booleanOption(parsed.options, ["force", "f"], true);
|
||||
|
||||
if (elevateAll) {
|
||||
const allCorps = typeof runtime.corpContext.getAllCorps === "function"
|
||||
? runtime.corpContext.getAllCorps()
|
||||
: [];
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "批量提取并持久化全部企业 OpenAPI 密钥", `共 ${allCorps.length} 家企业`, {
|
||||
count: allCorps.length,
|
||||
});
|
||||
}
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"批量提取并持久化全部企业 OpenAPI 密钥",
|
||||
`hose-use corps elevate --all --yes`
|
||||
);
|
||||
|
||||
const results: Array<{ corpId: string; name: string; appKey?: string; status: string }> = [];
|
||||
for (const corp of allCorps) {
|
||||
if (hasOpenApiPersistentCredentials(corp)) {
|
||||
results.push({ corpId: corp.id, name: corp.name, appKey: corp.credentials.appKey, status: "✅ 已持久化" });
|
||||
continue;
|
||||
}
|
||||
const selected = await elevateCorpWithOpenApiKey(corp, { force: true, silent: true });
|
||||
if (selected) {
|
||||
results.push({ corpId: corp.id, name: corp.name, appKey: selected.appKey, status: "✨ 新提权成功" });
|
||||
} else {
|
||||
results.push({ corpId: corp.id, name: corp.name, status: "⚪ 无密钥或会话过期" });
|
||||
}
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ results }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const rows = results.map((r, i) => [i + 1, r.corpId, r.name, r.appKey || "-", r.status]);
|
||||
return {
|
||||
stdout: `====== 批量提权企业 OpenAPI 持久化密钥结果 ======\n${printTable(["#", "企业 ID", "企业名称", "appKey", "状态"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const targetCorp = resolveTargetCorpByArgOrContext(parsed.args[0], runtime);
|
||||
if (!targetCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "未找到目标企业,请通过 --corp=<id> 或参数指定企业,或使用 --all 批量提权\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "提取并持久化企业 OpenAPI 密钥", `${targetCorp.name} (${targetCorp.id})`, {
|
||||
corpId: targetCorp.id,
|
||||
appKey: appKey || "auto-select",
|
||||
});
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"提取并持久化企业 OpenAPI 密钥",
|
||||
`hose-use corps elevate ${targetCorp.id} --yes`
|
||||
);
|
||||
|
||||
const selected = await elevateCorpWithOpenApiKey(targetCorp, {
|
||||
appKey,
|
||||
keyId,
|
||||
force,
|
||||
});
|
||||
|
||||
if (!selected) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未能为企业 [${targetCorp.name}] 提取到可用的 OpenAPI 密钥\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId: targetCorp.id,
|
||||
corpName: targetCorp.name,
|
||||
appKey: selected.appKey,
|
||||
appSecurity: maskOpenApiSecurity(selected.appSecurity),
|
||||
keyName: selected.name || "-",
|
||||
persistent: true,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 已将企业 [${targetCorp.name} (${targetCorp.id})] 提权为 OpenAPI 持久化配置 (appKey: ${selected.appKey})!\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleSyncFromSeal(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const filter = parsed.args[0] || stringOption(parsed.options, ["corp", "filter", "keyword"]);
|
||||
const sealDir = stringOption(parsed.options, ["seal-dir", "sealDir"]);
|
||||
const verify = booleanOption(parsed.options, ["verify"], false);
|
||||
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], true);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "从 seal-use 同步企业 OpenAPI 持久化密钥", filter || "全部合思企业", {
|
||||
filter: filter || null,
|
||||
verify,
|
||||
overwrite,
|
||||
});
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"从 seal-use 同步企业 OpenAPI 持久化密钥",
|
||||
`hose-use corps sync-seal${filter ? ` ${filter}` : ""} --yes`
|
||||
);
|
||||
|
||||
const synced = await syncOpenApiFromSealUse({
|
||||
filter,
|
||||
sealEnterprisesDir: sealDir,
|
||||
verify,
|
||||
overwrite,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(synced, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (synced.items.length === 0) {
|
||||
return {
|
||||
stdout: `未在 ${synced.sealDir} 中找到可同步的合思 OpenAPI 持久化密钥配置${filter ? ` (过滤条件: ${filter})` : ""}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = synced.items.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.corpId,
|
||||
item.name,
|
||||
item.appKey,
|
||||
item.staffId,
|
||||
item.action === "merged" ? "🔄 合并增强" : item.action === "created" ? "✨ 新增企业" : "⏭️ 跳过",
|
||||
]);
|
||||
const table = printTable(["#", "企业 ID", "企业名称", "appKey", "默认工号", "同步动作"], rows);
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 已从 seal-use 同步 ${synced.items.length} 家企业的 OpenAPI 持久化凭证!\n${table}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { stringOption } from "../../parser.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { handleList, handleSearch } from "./query.js";
|
||||
import { handleSwitch, handleCurrent } from "./context.js";
|
||||
import { handleGenerateCorpLink, handleAddLink } from "./link.js";
|
||||
import { handleAddPersistent, handleExtractKeys, handleElevateCorp, handleSyncFromSeal } from "./credentials.js";
|
||||
import { handleProbeHose, handleHoseStaffs } from "./probe.js";
|
||||
import { isHttpUrl, resolveTargetCorpByArgOrContext } from "./shared.js";
|
||||
|
||||
// 供 auth.ts 等跨命令复用的 handler 与 helper 维持原有命名导出。
|
||||
export { handleGenerateCorpLink } from "./link.js";
|
||||
export { handleAddPersistent, handleExtractKeys, handleElevateCorp, handleSyncFromSeal } from "./credentials.js";
|
||||
export { isHttpUrl, resolveTargetCorpByArgOrContext } from "./shared.js";
|
||||
|
||||
export async function handleCorpsCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const action = parsed.action || "list";
|
||||
|
||||
switch (action) {
|
||||
case "list":
|
||||
case "ls":
|
||||
return handleList(parsed, runtime);
|
||||
case "search":
|
||||
case "find":
|
||||
case "query":
|
||||
case "filter":
|
||||
return handleSearch(parsed, runtime);
|
||||
case "switch":
|
||||
case "use":
|
||||
return handleSwitch(parsed, runtime);
|
||||
case "current":
|
||||
case "whoami":
|
||||
case "status":
|
||||
case "active":
|
||||
return handleCurrent(parsed, runtime);
|
||||
case "add-link":
|
||||
case "import-link":
|
||||
return handleAddLink(parsed, runtime);
|
||||
case "link": {
|
||||
const maybeUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
|
||||
if (isHttpUrl(maybeUrl)) {
|
||||
return handleAddLink(parsed, runtime);
|
||||
}
|
||||
return handleGenerateCorpLink(parsed, runtime);
|
||||
}
|
||||
case "hose-link":
|
||||
case "auth-link":
|
||||
case "login-link":
|
||||
return handleGenerateCorpLink(parsed, runtime);
|
||||
case "add-persistent":
|
||||
case "add-hose-persistent":
|
||||
case "add-openapi":
|
||||
case "add-hose":
|
||||
return handleAddPersistent(parsed, runtime);
|
||||
case "extract-keys":
|
||||
case "extract-key":
|
||||
case "hose-extract-keys":
|
||||
case "extract-hose-keys":
|
||||
return handleExtractKeys(parsed, runtime);
|
||||
case "elevate":
|
||||
case "elevate-hose":
|
||||
return handleElevateCorp(parsed, runtime);
|
||||
case "sync-seal":
|
||||
case "sync-from-seal":
|
||||
case "import-seal":
|
||||
return handleSyncFromSeal(parsed, runtime);
|
||||
case "probe-hose":
|
||||
return handleProbeHose(parsed, runtime);
|
||||
case "hose-staffs":
|
||||
return handleHoseStaffs(parsed, runtime);
|
||||
case "help":
|
||||
return handleCorpsHelp();
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 corps 子命令: ${action}。支持: list, search, switch, current, link, add-link, add-persistent, extract-keys, elevate, sync-seal\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function printCorpsHelp(): string {
|
||||
return `
|
||||
用法:
|
||||
hose-use corps <子命令> [参数] [选项]
|
||||
|
||||
子命令:
|
||||
list 列出本地已保存的所有企业配置 (别名: ls)
|
||||
search <关键词> 根据关键词模糊搜索企业(支持 id, name, corpId, staffId, staffName, accountId,别名: find)
|
||||
switch <企业ID> 切换当前激活的工作企业 (别名: use)
|
||||
current 查看当前激活的企业配置与凭证详情
|
||||
link [企业ID|名称] 生成企业合思 Web 免密登录直达链接 (别名: hose-link)
|
||||
add-link <URL> 从第三方协助/免密链接导入企业凭证(默认自动探测并持久化 OpenAPI 密钥)
|
||||
add-persistent 通过 OpenAPI 密钥 (appKey + appSecurity) 持久化接入企业 (别名: add-hose-persistent)
|
||||
extract-keys <URL> 从协助链接提取企业 OpenAPI 密钥(附加 --save 可直接持久化保存)
|
||||
elevate [企业ID] 为已登录/已导入的企业提取并持久化保存 OpenAPI 密钥
|
||||
sync-seal [关键词] 从本机 seal-use 配置目录同步企业级 OpenAPI 持久化密钥
|
||||
|
||||
选项:
|
||||
--json, -j 以 JSON 格式输出
|
||||
--help, -h 查看帮助信息
|
||||
|
||||
示例:
|
||||
hose-use corps list
|
||||
hose-use corps search 某企业
|
||||
hose-use corps search 17718556446
|
||||
hose-use corps switch ID01MCcOgJl1td
|
||||
hose-use corps link 新转转集团
|
||||
hose-use corps add-link "<url>" --elevate --yes
|
||||
hose-use corps add-persistent --app-key=... --app-security=... --yes
|
||||
`.trim();
|
||||
}
|
||||
|
||||
function handleCorpsHelp(): CliResult {
|
||||
return {
|
||||
stdout: printCorpsHelp() + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { getCorpProvisionalAuthLink, hasOpenApiPersistentCredentials, importFromLink } from "../../../core/auth/login.js";
|
||||
import { resolveWritableEnterprisesDir } from "../../../core/config/loader.js";
|
||||
import { stringOption, booleanOption } from "../../parser.js";
|
||||
import { prompt } from "../../helpers.js";
|
||||
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { resolveTargetCorpByArgOrContext } from "./shared.js";
|
||||
|
||||
export async function handleGenerateCorpLink(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const targetArg = parsed.args[0];
|
||||
const targetCorp = resolveTargetCorpByArgOrContext(targetArg, runtime);
|
||||
if (!targetCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未找到目标企业${targetArg ? ` [${targetArg}]` : ""}。请通过 --corp=<id> 或参数指定已配置的企业。\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const expiresIn =
|
||||
stringOption(parsed.options, ["expires-in", "expiresIn", "expire", "expires", "ttl"]) || 7200;
|
||||
const pageType = stringOption(parsed.options, ["page-type", "pageType"]) || "home";
|
||||
const force = booleanOption(parsed.options, ["force", "refresh", "f"]);
|
||||
|
||||
const linkRes = await getCorpProvisionalAuthLink(targetCorp, {
|
||||
expiresIn,
|
||||
pageType,
|
||||
force,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
corpId: linkRes.corpId,
|
||||
corpName: linkRes.corpName,
|
||||
staffId: linkRes.staffId,
|
||||
...(linkRes.staffName ? { staffName: linkRes.staffName } : {}),
|
||||
link: linkRes.url,
|
||||
expiresAt: linkRes.expiresAt,
|
||||
expiresIn: linkRes.expiresIn,
|
||||
token: linkRes.token,
|
||||
persistent: linkRes.persistent,
|
||||
method: linkRes.method,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: true,
|
||||
};
|
||||
}
|
||||
|
||||
const lines = [
|
||||
`====== 合思企业 Web 免密登录直达链接 ======`,
|
||||
` 企业名称 : ${linkRes.corpName} (${linkRes.corpId})`,
|
||||
` 操作人身份: ${linkRes.staffName ? `${linkRes.staffName} (${linkRes.staffId})` : linkRes.staffId}`,
|
||||
` 签发通道 : ${linkRes.method === "provisional-openapi" ? "OpenAPI 持久化密钥动态签发 (getProvisionalAuth)" : "当前有效会话令牌拼装 (session-token)"}`,
|
||||
` 过期时间 : ${linkRes.expiresAt}`,
|
||||
` 直达链接 :`,
|
||||
` ${linkRes.url}`,
|
||||
``,
|
||||
`Markdown 链接: [打开 ${linkRes.corpName} 合思后台](${linkRes.url})`,
|
||||
];
|
||||
|
||||
return {
|
||||
stdout: `${lines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: true,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
let linkUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
|
||||
const name = stringOption(parsed.options, ["name"]);
|
||||
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false);
|
||||
const ttl = stringOption(parsed.options, ["ttl"]);
|
||||
const expires = stringOption(parsed.options, ["expires", "days"]);
|
||||
const elevate = booleanOption(parsed.options, ["elevate", "elevate-hose", "as-hose"], false);
|
||||
const noElevate = booleanOption(parsed.options, ["no-elevate"], false);
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
|
||||
const force = booleanOption(parsed.options, ["force", "f"], false);
|
||||
|
||||
if (!linkUrl && process.stdin.isTTY && !process.env.CI && process.env.NODE_ENV !== "test") {
|
||||
linkUrl = await prompt("请输入第三方协助/免密登录链接 URL: ");
|
||||
}
|
||||
|
||||
if (!linkUrl) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "错误:必须提供协助/免密链接 URL!用法: hose-use corps add-link <url> [--name <企业别名>] [--elevate] [--ttl 3d|--expires 3] [--overwrite]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
let targetCorpId = "";
|
||||
try {
|
||||
const parsedUrl = new URL(linkUrl);
|
||||
targetCorpId = parsedUrl.searchParams.get("ekbCorpId") || "";
|
||||
} catch {}
|
||||
|
||||
const targetDir = resolveWritableEnterprisesDir();
|
||||
const existsAlready = Boolean(targetCorpId && existsSync(join(targetDir, `${targetCorpId}.json`)));
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(
|
||||
parsed,
|
||||
runtime,
|
||||
"从协助链接导入企业凭证",
|
||||
name || (targetCorpId ? `企业 [${targetCorpId}]` : "待解析企业"),
|
||||
{
|
||||
source: "assistance-link",
|
||||
elevate: elevate ? "required" : noElevate ? "disabled" : "auto-best-effort",
|
||||
overwrite,
|
||||
alreadyExists: existsAlready,
|
||||
ttl: ttl || null,
|
||||
expires: expires || null,
|
||||
note: existsAlready && !overwrite ? "检测到本地已存在该企业配置,导入执行时请带上 --overwrite 参数" : undefined,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const nextConfirmCmd = existsAlready && !overwrite
|
||||
? `hose-use corps add-link <url> --overwrite --yes`
|
||||
: `hose-use corps add-link <url> --yes`;
|
||||
|
||||
const confirmOp = existsAlready && !overwrite
|
||||
? `从协助链接导入企业凭证(检测到目标企业 [${targetCorpId}] 已存在,需覆盖更新)`
|
||||
: "从协助链接导入企业凭证";
|
||||
|
||||
requireMutationConfirmation(parsed, runtime, confirmOp, nextConfirmCmd);
|
||||
|
||||
try {
|
||||
const corp = await importFromLink(linkUrl, {
|
||||
name,
|
||||
overwrite,
|
||||
ttl,
|
||||
expires,
|
||||
appKey,
|
||||
keyId,
|
||||
elevate: elevate ? true : noElevate ? false : undefined,
|
||||
autoElevate: !noElevate,
|
||||
force,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(corp, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const savedPath = join(targetDir, `${corp.id}.json`);
|
||||
const hasOpenApi = hasOpenApiPersistentCredentials(corp);
|
||||
|
||||
const summaryPairs: Record<string, unknown> = {
|
||||
"企业名称": corp.name,
|
||||
"企业 ID": corp.id,
|
||||
"集群环境": corp.cluster || "app",
|
||||
"员工工号": corp.credentials.staffId,
|
||||
"员工姓名": corp.staffName || corp.session?.staffName || "-",
|
||||
"手机号码": corp.session?.cellphone || "-",
|
||||
"是否管理": corp.session?.isAdmin ? "是" : "否",
|
||||
"凭证来源": formatSourceLabel(corp.source, hasOpenApi),
|
||||
"持久化密钥": hasOpenApi ? `✅ 已自动提权持久化 (appKey: ${corp.credentials.appKey})` : "⚪ 未提取到 OpenAPI 密钥 (短期会话)",
|
||||
"服务节点": corp.baseUrl,
|
||||
"过期时间": formatExpiresAt(corp.auth?.expiresAt || corp.session?.expTime, hasOpenApi),
|
||||
"保存路径": savedPath,
|
||||
};
|
||||
|
||||
if (corp.session?.isAssistPlatform) {
|
||||
summaryPairs["协助平台"] = "是 (Assist Platform 调试授权)";
|
||||
if (corp.session.operationUserName || corp.session.operationUserId) {
|
||||
summaryPairs["协助操作人"] = `${corp.session.operationUserName || ""} (${corp.session.operationUserId || ""})`.trim();
|
||||
}
|
||||
if (corp.session.assistId) {
|
||||
summaryPairs["协助会话 ID"] = corp.session.assistId;
|
||||
}
|
||||
}
|
||||
|
||||
const summaryText = printKeyValue(summaryPairs);
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 成功导入并保存企业凭证!\n${summaryText}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] 导入协助链接失败: ${error instanceof Error ? error.message : String(error)}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { fetchHoseRoleDefGroups, listHoseStaffsByOpenApi, probeHoseDomain } from "../../../core/auth/login.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue, printTable } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
|
||||
export async function handleProbeHose(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const appSecurity = stringOption(parsed.options, ["app-security", "appSecurity", "secret"]);
|
||||
const domain = stringOption(parsed.options, ["domain", "base-url"]);
|
||||
|
||||
if (!appKey || !appSecurity) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use corps probe-hose --app-key=<key> --app-security=<secret> [--domain=<url>]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const probe = await probeHoseDomain(appKey, appSecurity, domain);
|
||||
const roleGroups = await fetchHoseRoleDefGroups(probe.domain, probe.openapiToken).catch(() => []);
|
||||
const payload = {
|
||||
domain: probe.domain,
|
||||
corpId: probe.corpId,
|
||||
name: probe.corpName || probe.corpId,
|
||||
roleCount: roleGroups.reduce((acc, g) => acc + g.roleDefs.length, 0),
|
||||
roleGroups,
|
||||
};
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(payload, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `====== OpenAPI 域名与企业探测结果 ======\n${printKeyValue({
|
||||
"企业 ID": payload.corpId,
|
||||
"企业名称": payload.name,
|
||||
"服务节点": payload.domain,
|
||||
"角色数量": payload.roleCount,
|
||||
})}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleHoseStaffs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const appSecurity = stringOption(parsed.options, ["app-security", "appSecurity", "secret"]);
|
||||
const domain = stringOption(parsed.options, ["domain", "base-url"]);
|
||||
const role = stringOption(parsed.options, ["role", "roleDefId"]);
|
||||
|
||||
if (!appKey || !appSecurity) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use corps hose-staffs --app-key=<key> --app-security=<secret> [--role=admin]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const res = await listHoseStaffsByOpenApi({ appKey, appSecurity, domain, role });
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(res, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const rows = res.staffs.map((s, i) => [i + 1, s.id, s.name, s.cellphone || "-", s.active ? "在职" : "离职"]);
|
||||
return {
|
||||
stdout: `====== 角色成员列表 (${res.roleName || res.roleId}) ======\n${printTable(["#", "员工 ID", "姓名", "手机号", "状态"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import { canRefreshCorpAccessToken } from "../../../core/auth/login.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, formatExpiresAt } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
|
||||
const FIELD_LABEL_MAP: Record<string, string> = {
|
||||
id: "配置ID",
|
||||
name: "企业名称",
|
||||
corpId: "企业ID",
|
||||
staffId: "员工工号",
|
||||
staffName: "员工姓名",
|
||||
accountId: "所属账号",
|
||||
};
|
||||
|
||||
export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const keyword = parsed.args[0] || stringOption(parsed.options, ["keyword", "query", "k", "q", "name", "id"]);
|
||||
if (!keyword || !keyword.trim()) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use corps search <关键词>\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const kw = keyword.trim().toLowerCase();
|
||||
|
||||
// 从 CorpContext 中获取企业列表
|
||||
const rawCorps = typeof runtime.corpContext.getAllCorps === "function"
|
||||
? runtime.corpContext.getAllCorps()
|
||||
: null;
|
||||
|
||||
const normalizedCorps = rawCorps
|
||||
? rawCorps.map((c) => ({
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
corpId: c.corpId || c.credentials?.corpId || c.id,
|
||||
staffId: c.staffId || c.credentials?.staffId || "",
|
||||
staffName: c.staffName || c.session?.staffName || "",
|
||||
accountId: c.accountId || "",
|
||||
source: c.source || "manual",
|
||||
baseUrl: c.baseUrl,
|
||||
current: c.id === runtime.selectedCorp?.id,
|
||||
expiresAt: c.auth?.expiresAt || (c.session?.expTime ?? undefined),
|
||||
persistent: canRefreshCorpAccessToken(c),
|
||||
}))
|
||||
: runtime.corpContext.listCorps().map((c) => ({
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
corpId: c.corpId || c.id,
|
||||
staffId: c.staffId || "",
|
||||
staffName: c.staffName || "",
|
||||
accountId: c.accountId || "",
|
||||
source: c.source || "manual",
|
||||
baseUrl: c.baseUrl,
|
||||
current: c.current || c.id === runtime.selectedCorp?.id,
|
||||
expiresAt: c.expiresAt,
|
||||
persistent: c.persistent,
|
||||
}));
|
||||
|
||||
const matches: Array<typeof normalizedCorps[number] & { matchedFields: string[] }> = [];
|
||||
|
||||
for (const corp of normalizedCorps) {
|
||||
const matchedFields: string[] = [];
|
||||
|
||||
if (corp.id && corp.id.toLowerCase().includes(kw)) {
|
||||
matchedFields.push("id");
|
||||
}
|
||||
if (corp.name && corp.name.toLowerCase().includes(kw)) {
|
||||
matchedFields.push("name");
|
||||
}
|
||||
if (corp.corpId && corp.corpId.toLowerCase().includes(kw) && !matchedFields.includes("corpId") && corp.corpId !== corp.id) {
|
||||
matchedFields.push("corpId");
|
||||
}
|
||||
if (corp.staffId && corp.staffId.toLowerCase().includes(kw)) {
|
||||
matchedFields.push("staffId");
|
||||
}
|
||||
if (corp.staffName && corp.staffName.toLowerCase().includes(kw)) {
|
||||
matchedFields.push("staffName");
|
||||
}
|
||||
if (corp.accountId && corp.accountId.toLowerCase().includes(kw)) {
|
||||
matchedFields.push("accountId");
|
||||
}
|
||||
|
||||
if (matchedFields.length > 0) {
|
||||
matches.push({ ...corp, matchedFields });
|
||||
}
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
keyword: keyword.trim(),
|
||||
count: matches.length,
|
||||
activeCorpId: runtime.selectedCorp?.id,
|
||||
corporations: matches.map((m) => ({
|
||||
id: m.id,
|
||||
name: m.name,
|
||||
corpId: m.corpId,
|
||||
staffId: m.staffId,
|
||||
staffName: m.staffName || undefined,
|
||||
accountId: m.accountId || undefined,
|
||||
source: m.source,
|
||||
baseUrl: m.baseUrl,
|
||||
current: m.current,
|
||||
expiresAt: m.expiresAt,
|
||||
persistent: m.persistent,
|
||||
matchedFields: m.matchedFields,
|
||||
})),
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (matches.length === 0) {
|
||||
return {
|
||||
stdout: `未找到匹配 "${keyword.trim()}" 的企业配置\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = matches.map((m, i) => {
|
||||
const isCurrent = m.current;
|
||||
const matchLabels = m.matchedFields.map((f) => FIELD_LABEL_MAP[f] || f);
|
||||
return [
|
||||
isCurrent ? `* ${i + 1}` : ` ${i + 1}`,
|
||||
m.matchedFields.includes("id") || m.matchedFields.includes("corpId") ? `[${m.id}]` : m.id,
|
||||
m.matchedFields.includes("name") ? `[${m.name}]` : m.name,
|
||||
m.matchedFields.includes("staffId") ? `[${m.staffId}]` : m.staffId,
|
||||
m.staffName ? (m.matchedFields.includes("staffName") ? `[${m.staffName}]` : m.staffName) : "-",
|
||||
m.accountId ? (m.matchedFields.includes("accountId") ? `[${m.accountId}]` : m.accountId) : "-",
|
||||
matchLabels.map((l) => `命中${l}`).join(", "),
|
||||
formatExpiresAt(m.expiresAt, m.persistent),
|
||||
];
|
||||
});
|
||||
|
||||
const table = printTable(
|
||||
["#", "企业 ID", "企业名称", "员工工号", "员工姓名", "所属账号", "匹配项", "Token 过期时间"],
|
||||
rows
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: `====== 企业搜索结果 (关键词: "${keyword.trim()}", 找到 ${matches.length} 家) ======\n${table}\n\n提示:\n - 标记 * 为当前激活企业\n - 标记 [...] 为命中关键词的字段\n - 使用 hose-use corps switch <企业ID> 切换工作企业\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const corps = runtime.corpContext.listCorps();
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
activeCorpId: runtime.selectedCorp?.id,
|
||||
corporations: corps,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (corps.length === 0) {
|
||||
return { stdout: "未找到任何企业配置,请先运行 hose-use auth login\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const rows = corps.map((c, i) => [
|
||||
c.current ? `* ${i + 1}` : ` ${i + 1}`,
|
||||
c.id,
|
||||
c.name,
|
||||
c.staffId,
|
||||
c.source || "manual",
|
||||
formatExpiresAt(c.expiresAt, c.persistent),
|
||||
c.accountId || "-",
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
["#", "企业 ID", "企业名称", "员工工号", "来源", "Token 过期时间", "所属账号"],
|
||||
rows
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: `====== 已配置企业列表 (${corps.length} 家) ======\n${table}\n\n提示:\n - 标记 * 为当前激活企业(同时作为 hose-use 与 hose-aipro 的统一默认执行上下文)\n - 使用 hose-use corps switch <企业ID> 切换工作企业\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { CorpConfig } from "../../../core/config/types.js";
|
||||
import type { CliRuntime } from "../../types.js";
|
||||
|
||||
export function isHttpUrl(val?: string): boolean {
|
||||
return Boolean(val && /^https?:\/\//i.test(val.trim()));
|
||||
}
|
||||
|
||||
export function resolveTargetCorpByArgOrContext(
|
||||
targetArg: string | undefined,
|
||||
runtime: CliRuntime
|
||||
): CorpConfig | null {
|
||||
if (targetArg && !isHttpUrl(targetArg)) {
|
||||
try {
|
||||
return runtime.corpContext.resolve(targetArg);
|
||||
} catch {
|
||||
const allCorps = typeof runtime.corpContext.getAllCorps === "function"
|
||||
? runtime.corpContext.getAllCorps()
|
||||
: [];
|
||||
const kw = targetArg.trim().toLowerCase();
|
||||
const matched = allCorps.find(
|
||||
(c) =>
|
||||
c.id.toLowerCase() === kw ||
|
||||
(c.corpId && c.corpId.toLowerCase() === kw) ||
|
||||
c.name.toLowerCase().includes(kw)
|
||||
);
|
||||
if (matched) return matched;
|
||||
}
|
||||
}
|
||||
return runtime.selectedCorp;
|
||||
}
|
||||
@@ -516,7 +516,7 @@ export async function handleFeeTypeCommand(
|
||||
|
||||
// ── 8. 查看单据模板定义 (spec / specification) ─────────────────────────────
|
||||
if (["spec", "specification"].includes(action)) {
|
||||
const { handleBillCommand } = await import("./bill.js");
|
||||
const { handleBillCommand } = await import("./bill/index.js");
|
||||
return handleBillCommand({ ...parsed, area: "bill", action: "spec" }, runtime);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getOpenApiSchema, listOpenApiPaths, type OpenApiType } from "../../core/embedded-openapi.js";
|
||||
import { getOpenApiSchema, listOpenApiPaths, type OpenApiType } from "../../packaging/embedded-openapi.js";
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { printJson, printKeyValue, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it, spyOn, afterEach } from "bun:test";
|
||||
import { handlePlatformCommand } from "./platform.js";
|
||||
import { handlePlatformCommand } from "./platform/index.js";
|
||||
import * as api from "../../domains/datalink/api.js";
|
||||
import * as services from "../../domains/datalink/services.js";
|
||||
import * as helpers from "../helpers.js";
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import {
|
||||
getImportResult,
|
||||
listImportJobs,
|
||||
listAllPlatforms,
|
||||
listPlatformEntities,
|
||||
listPlatforms,
|
||||
} from "../../../domains/datalink/services.js";
|
||||
import { createClientsForCorp } from "../../helpers.js";
|
||||
import { booleanOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { cell, resolveAppAndEntity } from "./shared.js";
|
||||
|
||||
export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const isAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const platforms = isAll
|
||||
? await listAllPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId)
|
||||
: await listPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId);
|
||||
|
||||
if (runtime.jsonMode) return { stdout: printJson({ count: platforms.length, all: isAll, platforms }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
if (platforms.length === 0) return { stdout: `企业 [${runtime.selectedCorp!.name}] 下暂无自建应用\n`, stderr: "", exitCode: 0 };
|
||||
const rows = platforms.map((p, i) => [i + 1, p.id, p.name, p.code, p.active ? "🟢 已启用" : "⚪ 未启用"]);
|
||||
const label = isAll ? "自建应用与模板全量列表" : "自建应用列表";
|
||||
return { stdout: `====== [${runtime.selectedCorp!.name}] ${label} (共 ${platforms.length} 个) ======\n${printTable(["#", "自建应用 ID", "应用名称", "编码", "状态"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const { platform } = await resolveAppAndEntity(parsed, runtime);
|
||||
if (runtime.jsonMode) return { stdout: printJson(platform, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 自建应用详情: ${platform.name} ======\n${printTable(["字段", "值"], [
|
||||
["ID", platform.id], ["编码", platform.code], ["状态", platform.active ? "已启用" : "未启用"],
|
||||
["管理员数量", platform.adminIds.length], ["可见人员数量", platform.staffIds.length],
|
||||
["可见角色数量", platform.roleIds.length], ["可见部门数量", platform.departmentIds.length],
|
||||
["包含子部门", platform.departmentsIncludeChildren ? "是" : "否"],
|
||||
])}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleEntities(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const { clients, corpId, platform } = await resolveAppAndEntity(parsed, runtime);
|
||||
const entities = await listPlatformEntities(clients.ekbClient, corpId, platform.id);
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q"])?.toLowerCase();
|
||||
const filtered = keyword ? entities.filter((entity) => [entity.id, entity.name, entity.code].some((value) => value.toLowerCase().includes(keyword))) : entities;
|
||||
if (runtime.jsonMode) return { stdout: printJson({ platform, keyword, total: entities.length, count: filtered.length, entities: filtered }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = filtered.map((entity, i) => [i + 1, entity.id, entity.name, entity.code, entity.fields.length, entity.active ? "🟢 已启用" : "⚪ 未启用"]);
|
||||
return { stdout: `====== 应用 [${platform.name}] 业务对象 (匹配 ${filtered.length} / 共 ${entities.length} 个) ======\n${printTable(["#", "对象 ID", "对象名称", "编码", "字段数", "状态"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleSchema(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
const entities = resolved.entity ? [resolved.entity] : await listPlatformEntities(resolved.clients.ekbClient, resolved.corpId, resolved.platform.id);
|
||||
const fieldKeyword = stringOption(parsed.options, ["keyword", "field", "name"])?.toLowerCase();
|
||||
const output = entities.map((entity) => ({ ...entity, fields: fieldKeyword ? entity.fields.filter((field) => [field.name, field.label, field.type].some((value) => value.toLowerCase().includes(fieldKeyword))) : entity.fields }));
|
||||
if (runtime.jsonMode) return { stdout: printJson({ platform: resolved.platform, count: output.length, entities: output }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = output.flatMap((entity) => entity.fields.map((field): Array<string | number | boolean | null | undefined> => [entity.name, field.name, field.label, field.type, field.optional === false ? "必填" : "可选", cell(field.entity)]));
|
||||
return { stdout: `====== 应用 [${resolved.platform.name}] 字段定义 ======\n${printTable(["业务对象", "字段名", "显示名", "类型", "必填性", "引用对象"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handlePermissions(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
const appPermission = { adminIds: resolved.platform.adminIds, staffIds: resolved.platform.staffIds, roleIds: resolved.platform.roleIds, departmentIds: resolved.platform.departmentIds, departmentsIncludeChildren: resolved.platform.departmentsIncludeChildren };
|
||||
const result = resolved.entity ? { platform: resolved.platform, entity: resolved.entity, appPermission } : { platform: resolved.platform, appPermission };
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows: Array<Array<string | number | boolean | null | undefined>> = [["应用管理员", resolved.platform.adminIds.length], ["应用可见人员", resolved.platform.staffIds.length], ["应用可见角色", resolved.platform.roleIds.length], ["应用可见部门", resolved.platform.departmentIds.length]];
|
||||
if (resolved.entity) rows.push(["对象可见性", cell(resolved.entity.visibility)], ["首页可见性", cell(resolved.entity.homeVisibility)], ["导出权限", cell(resolved.entity.exportVisibility)], ["数据过滤", cell(resolved.entity.dataFilter)]);
|
||||
return { stdout: `====== 权限信息: ${resolved.platform.name}${resolved.entity ? ` / ${resolved.entity.name}` : ""} ======\n${printTable(["权限项", "值"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleImports(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform imports <应用> <业务对象>");
|
||||
const [jobs, latestResult] = await Promise.all([
|
||||
listImportJobs(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id),
|
||||
getImportResult(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id),
|
||||
]);
|
||||
const result = { platform: resolved.platform, entity: resolved.entity, jobs, latestResult };
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 导入任务: ${resolved.platform.name} / ${resolved.entity.name} ======\n${printTable(["#", "任务"], jobs.map((job, i) => [i + 1, cell(job)]))}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { booleanOption } from "../../parser.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { handleList, handleGet, handleEntities, handleSchema, handlePermissions, handleImports } from "./app-info.js";
|
||||
import { handleRecords, handleAudit } from "./records.js";
|
||||
import { handleRecordAction } from "./record-actions.js";
|
||||
|
||||
export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
if (!runtime.selectedCorp) {
|
||||
return { stdout: "", stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n", exitCode: 1 };
|
||||
}
|
||||
|
||||
const action = parsed.action || "list";
|
||||
const isWorkbench = action === "workbench" || booleanOption(parsed.options, ["workbench", "w"], false);
|
||||
if (isWorkbench) {
|
||||
const { handleAppCommand } = await import("./../app.js");
|
||||
return handleAppCommand(parsed, runtime);
|
||||
}
|
||||
|
||||
switch (action) {
|
||||
case "list":
|
||||
case "ls":
|
||||
case "apps": return handleList(parsed, runtime);
|
||||
case "get":
|
||||
case "show": return handleGet(parsed, runtime);
|
||||
case "entities":
|
||||
case "objects": return handleEntities(parsed, runtime);
|
||||
case "schema":
|
||||
case "fields": return handleSchema(parsed, runtime);
|
||||
case "records":
|
||||
case "data":
|
||||
case "search": return handleRecords(parsed, runtime);
|
||||
case "audit":
|
||||
case "check":
|
||||
case "health": return handleAudit(parsed, runtime);
|
||||
case "record":
|
||||
case "record-get":
|
||||
case "record-toggle":
|
||||
case "record-edit":
|
||||
case "record-batch-edit":
|
||||
case "batch-edit":
|
||||
case "record-recompute": return handleRecordAction(parsed, runtime);
|
||||
case "permissions":
|
||||
case "permission":
|
||||
case "auth": return handlePermissions(parsed, runtime);
|
||||
case "imports":
|
||||
case "import-jobs": return handleImports(parsed, runtime);
|
||||
default:
|
||||
return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, audit, record, permissions, imports\n`, exitCode: 1 };
|
||||
}
|
||||
}
|
||||
@@ -1,282 +1,21 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import * as api from "../../domains/datalink/api.js";
|
||||
import {
|
||||
auditEntityRecords,
|
||||
batchSafeEditRecords,
|
||||
buildKeywordFilter,
|
||||
buildSafeRecordEditPayload,
|
||||
editRecord,
|
||||
fetchAllEntityRecords,
|
||||
resolveEntity,
|
||||
resolvePlatform,
|
||||
selectRecordFields,
|
||||
getRecordDetail,
|
||||
recomputeRecordLedger,
|
||||
toggleRecordState,
|
||||
type BatchEditTargetItem,
|
||||
} from "../../domains/datalink/services.js";
|
||||
import { createClientsForCorp } from "../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printKeyValue, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
|
||||
function requiredTarget(parsed: CliParsedArgs, index: number, usage: string): string {
|
||||
const target = parsed.args[index]?.trim();
|
||||
if (!target) throw new Error(`请提供目标参数: ${usage}`);
|
||||
return target;
|
||||
}
|
||||
|
||||
function splitFields(value?: string): string[] {
|
||||
return value ? value.split(",").map((field) => field.trim()).filter(Boolean) : [];
|
||||
}
|
||||
|
||||
function cell(value: unknown): string {
|
||||
if (value === undefined || value === null) return "";
|
||||
if (typeof value === "object") return JSON.stringify(value);
|
||||
return String(value);
|
||||
}
|
||||
|
||||
async function resolveAppAndEntity(parsed: CliParsedArgs, runtime: CliRuntime, appIndex = 0, entityIndex = 1) {
|
||||
const appTarget = requiredTarget(parsed, appIndex, "hose-use platform <子命令> <应用 ID|名称>");
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const corpId = runtime.selectedCorp!.credentials.corpId;
|
||||
const platform = await resolvePlatform(clients.ekbClient, corpId, appTarget);
|
||||
if (!platform) throw new Error(`[NOT FOUND] 当前企业下未找到自建应用: ${appTarget}`);
|
||||
|
||||
const entityTarget = parsed.args[entityIndex]?.trim();
|
||||
if (!entityTarget) return { clients, corpId, platform, entity: undefined };
|
||||
const entity = await resolveEntity(clients.ekbClient, corpId, platform, entityTarget);
|
||||
if (!entity) throw new Error(`[NOT FOUND] 应用 [${platform.name}] 下未找到业务对象: ${entityTarget}`);
|
||||
return { clients, corpId, platform, entity };
|
||||
}
|
||||
|
||||
export async function handlePlatformCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
if (!runtime.selectedCorp) {
|
||||
return { stdout: "", stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n", exitCode: 1 };
|
||||
}
|
||||
|
||||
const action = parsed.action || "list";
|
||||
const isWorkbench = action === "workbench" || booleanOption(parsed.options, ["workbench", "w"], false);
|
||||
if (isWorkbench) {
|
||||
const { handleAppCommand } = await import("./app.js");
|
||||
return handleAppCommand(parsed, runtime);
|
||||
}
|
||||
|
||||
switch (action) {
|
||||
case "list":
|
||||
case "ls":
|
||||
case "apps": return handleList(parsed, runtime);
|
||||
case "get":
|
||||
case "show": return handleGet(parsed, runtime);
|
||||
case "entities":
|
||||
case "objects": return handleEntities(parsed, runtime);
|
||||
case "schema":
|
||||
case "fields": return handleSchema(parsed, runtime);
|
||||
case "records":
|
||||
case "data":
|
||||
case "search": return handleRecords(parsed, runtime);
|
||||
case "audit":
|
||||
case "check":
|
||||
case "health": return handleAudit(parsed, runtime);
|
||||
case "record":
|
||||
case "record-get":
|
||||
case "record-toggle":
|
||||
case "record-edit":
|
||||
case "record-batch-edit":
|
||||
case "batch-edit":
|
||||
case "record-recompute": return handleRecordAction(parsed, runtime);
|
||||
case "permissions":
|
||||
case "permission":
|
||||
case "auth": return handlePermissions(parsed, runtime);
|
||||
case "imports":
|
||||
case "import-jobs": return handleImports(parsed, runtime);
|
||||
default:
|
||||
return { stdout: "", stderr: `未知 platform 子命令: ${action}。支持: list, get, entities, schema, records, audit, record, permissions, imports\n`, exitCode: 1 };
|
||||
}
|
||||
}
|
||||
|
||||
async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const isAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const platforms = isAll
|
||||
? await api.listAllPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId)
|
||||
: await api.listPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId);
|
||||
|
||||
if (runtime.jsonMode) return { stdout: printJson({ count: platforms.length, all: isAll, platforms }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
if (platforms.length === 0) return { stdout: `企业 [${runtime.selectedCorp!.name}] 下暂无自建应用\n`, stderr: "", exitCode: 0 };
|
||||
const rows = platforms.map((p, i) => [i + 1, p.id, p.name, p.code, p.active ? "🟢 已启用" : "⚪ 未启用"]);
|
||||
const label = isAll ? "自建应用与模板全量列表" : "自建应用列表";
|
||||
return { stdout: `====== [${runtime.selectedCorp!.name}] ${label} (共 ${platforms.length} 个) ======\n${printTable(["#", "自建应用 ID", "应用名称", "编码", "状态"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const { platform } = await resolveAppAndEntity(parsed, runtime);
|
||||
if (runtime.jsonMode) return { stdout: printJson(platform, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 自建应用详情: ${platform.name} ======\n${printTable(["字段", "值"], [
|
||||
["ID", platform.id], ["编码", platform.code], ["状态", platform.active ? "已启用" : "未启用"],
|
||||
["管理员数量", platform.adminIds.length], ["可见人员数量", platform.staffIds.length],
|
||||
["可见角色数量", platform.roleIds.length], ["可见部门数量", platform.departmentIds.length],
|
||||
["包含子部门", platform.departmentsIncludeChildren ? "是" : "否"],
|
||||
])}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleEntities(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const { clients, corpId, platform } = await resolveAppAndEntity(parsed, runtime);
|
||||
const entities = await api.listPlatformEntities(clients.ekbClient, corpId, platform.id);
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q"])?.toLowerCase();
|
||||
const filtered = keyword ? entities.filter((entity) => [entity.id, entity.name, entity.code].some((value) => value.toLowerCase().includes(keyword))) : entities;
|
||||
if (runtime.jsonMode) return { stdout: printJson({ platform, keyword, total: entities.length, count: filtered.length, entities: filtered }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = filtered.map((entity, i) => [i + 1, entity.id, entity.name, entity.code, entity.fields.length, entity.active ? "🟢 已启用" : "⚪ 未启用"]);
|
||||
return { stdout: `====== 应用 [${platform.name}] 业务对象 (匹配 ${filtered.length} / 共 ${entities.length} 个) ======\n${printTable(["#", "对象 ID", "对象名称", "编码", "字段数", "状态"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleSchema(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
const entities = resolved.entity ? [resolved.entity] : await api.listPlatformEntities(resolved.clients.ekbClient, resolved.corpId, resolved.platform.id);
|
||||
const fieldKeyword = stringOption(parsed.options, ["keyword", "field", "name"])?.toLowerCase();
|
||||
const output = entities.map((entity) => ({ ...entity, fields: fieldKeyword ? entity.fields.filter((field) => [field.name, field.label, field.type].some((value) => value.toLowerCase().includes(fieldKeyword))) : entity.fields }));
|
||||
if (runtime.jsonMode) return { stdout: printJson({ platform: resolved.platform, count: output.length, entities: output }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = output.flatMap((entity) => entity.fields.map((field): Array<string | number | boolean | null | undefined> => [entity.name, field.name, field.label, field.type, field.optional === false ? "必填" : "可选", cell(field.entity)]));
|
||||
return { stdout: `====== 应用 [${resolved.platform.name}] 字段定义 ======\n${printTable(["业务对象", "字段名", "显示名", "类型", "必填性", "引用对象"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform records <应用> <业务对象>");
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (keyword ? buildKeywordFilter(keyword) : undefined);
|
||||
const fetchAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const start = numberOption(parsed.options, ["start", "offset"], 0);
|
||||
const count = numberOption(parsed.options, ["count", "limit"], 20);
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
|
||||
const fields = splitFields(stringOption(parsed.options, ["fields", "select"]));
|
||||
const page = fetchAll
|
||||
? await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { filterBy, pageSize })
|
||||
: await api.searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
|
||||
const data = fields.length ? page.data.map((item) => selectRecordFields(item, fields, resolved.entity!.fields)) : page.data;
|
||||
const result = {
|
||||
platform: resolved.platform,
|
||||
entity: resolved.entity,
|
||||
query: { start: fetchAll ? 0 : start, count: fetchAll ? data.length : count, all: fetchAll, filterBy, fields },
|
||||
total: page.total,
|
||||
returned: data.length,
|
||||
data,
|
||||
};
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
const rows = data.map((item, i): Array<string | number | boolean | null | undefined> => {
|
||||
const source = item.dataLink && typeof item.dataLink === "object" && !Array.isArray(item.dataLink) ? (item.dataLink as Record<string, unknown>) : item;
|
||||
const id = source.id ?? item.id;
|
||||
const active = source.active ?? item.active;
|
||||
const updateTime = source.updateTime ?? item.updateTime;
|
||||
const nameVal = source.name ?? source["名称"] ?? (nameField ? source[nameField.name] : undefined) ?? source[`E_${resolved.entity!.id}_name`];
|
||||
const codeVal = source.code ?? source["编码"] ?? (codeField ? source[codeField.name] : undefined) ?? source[`E_${resolved.entity!.id}_code`];
|
||||
const formattedTime = typeof updateTime === "number" ? new Date(updateTime).toLocaleString("zh-CN", { hour12: false }) : cell(updateTime);
|
||||
return [i + 1, cell(id), cell(nameVal), cell(codeVal), active === false ? "停用" : "启用", formattedTime];
|
||||
});
|
||||
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${page.total}, 当前: ${data.length}${fetchAll ? ", 全量导出" : ""}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleAudit(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
if (!resolved.entity) {
|
||||
throw new Error("请提供业务对象 ID、编码或名称: hose-use platform audit <应用> <业务对象> [--check-fields=字段1,字段2] [--active-only]");
|
||||
}
|
||||
const checkFields = splitFields(stringOption(parsed.options, ["check-fields", "checkFields", "fields"]));
|
||||
const activeOnly = booleanOption(parsed.options, ["active-only", "activeOnly"], false);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (activeOnly ? "(active==true)" : undefined);
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
|
||||
|
||||
const page = await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, {
|
||||
filterBy,
|
||||
pageSize,
|
||||
});
|
||||
const report = auditEntityRecords(page.data, resolved.entity, {
|
||||
checkFields,
|
||||
activeOnly,
|
||||
total: page.total,
|
||||
});
|
||||
|
||||
const output = {
|
||||
platform: { id: resolved.platform.id, name: resolved.platform.name, code: resolved.platform.code },
|
||||
entity: { id: resolved.entity.id, name: resolved.entity.name, code: resolved.entity.code },
|
||||
...report,
|
||||
};
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const issueRows = report.issues.map((issue, idx) => [
|
||||
idx + 1,
|
||||
issue.recordId,
|
||||
issue.recordCode || "-",
|
||||
issue.recordName || "-",
|
||||
issue.active ? "🟢 启用" : "🔴 停用",
|
||||
issue.type,
|
||||
issue.fieldLabel,
|
||||
issue.message,
|
||||
]);
|
||||
|
||||
const patchRows = report.suggestedPatches.map((patch, idx) => [
|
||||
idx + 1,
|
||||
patch.id,
|
||||
patch.code || "-",
|
||||
patch.name || "-",
|
||||
JSON.stringify(patch.form),
|
||||
patch.reason,
|
||||
]);
|
||||
|
||||
const outLines = [
|
||||
`====== 台账数据健康度体检: [${resolved.platform.name}] ${resolved.entity.name} (${resolved.entity.id}) ======`,
|
||||
printKeyValue({
|
||||
"总记录数": report.totalRecords,
|
||||
"本次体检记录数": report.auditedRecords,
|
||||
"健康记录数": report.healthyRecords,
|
||||
"异常记录数": report.affectedRecordCount,
|
||||
"总问题项数": report.issueCount,
|
||||
"关键字段缺失 (MISSING_FIELD)": report.summary.missingFieldCount,
|
||||
"引用对象已停用 (DISABLED_REFERENCE)": report.summary.disabledReferenceCount,
|
||||
"跨表同名维度待回填 (CROSS_LEDGER_MISSING_SYNC)": report.summary.crossLedgerMissingSyncCount,
|
||||
"跨表同名维度不一致 (CROSS_LEDGER_MISMATCH)": report.summary.crossLedgerMismatchCount,
|
||||
}),
|
||||
"",
|
||||
"── 异常诊断明细 ──",
|
||||
issueRows.length
|
||||
? printTable(["#", "记录 ID", "编码", "名称", "状态", "问题类型", "字段", "详细说明"], issueRows)
|
||||
: "✅ 未发现任何字段缺失、停用引用或跨表维度不一致问题",
|
||||
];
|
||||
|
||||
if (patchRows.length > 0) {
|
||||
outLines.push("");
|
||||
outLines.push(`── 💡 建议自动回填修复清单 (共 ${patchRows.length} 条记录,可通过 platform record batch-edit 执行) ──`);
|
||||
outLines.push(printTable(["#", "记录 ID", "编码", "名称", "建议 Patch Form", "依据"], patchRows));
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handlePermissions(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
const appPermission = { adminIds: resolved.platform.adminIds, staffIds: resolved.platform.staffIds, roleIds: resolved.platform.roleIds, departmentIds: resolved.platform.departmentIds, departmentsIncludeChildren: resolved.platform.departmentsIncludeChildren };
|
||||
const result = resolved.entity ? { platform: resolved.platform, entity: resolved.entity, appPermission } : { platform: resolved.platform, appPermission };
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows: Array<Array<string | number | boolean | null | undefined>> = [["应用管理员", resolved.platform.adminIds.length], ["应用可见人员", resolved.platform.staffIds.length], ["应用可见角色", resolved.platform.roleIds.length], ["应用可见部门", resolved.platform.departmentIds.length]];
|
||||
if (resolved.entity) rows.push(["对象可见性", cell(resolved.entity.visibility)], ["首页可见性", cell(resolved.entity.homeVisibility)], ["导出权限", cell(resolved.entity.exportVisibility)], ["数据过滤", cell(resolved.entity.dataFilter)]);
|
||||
return { stdout: `====== 权限信息: ${resolved.platform.name}${resolved.entity ? ` / ${resolved.entity.name}` : ""} ======\n${printTable(["权限项", "值"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleImports(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform imports <应用> <业务对象>");
|
||||
const [jobs, latestResult] = await Promise.all([
|
||||
api.listImportJobs(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id),
|
||||
api.getImportResult(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id),
|
||||
]);
|
||||
const result = { platform: resolved.platform, entity: resolved.entity, jobs, latestResult };
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 导入任务: ${resolved.platform.name} / ${resolved.entity.name} ======\n${printTable(["#", "任务"], jobs.map((job, i) => [i + 1, cell(job)]))}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
type SafeRecordEditOptions,
|
||||
} from "../../../domains/datalink/services.js";
|
||||
import { createClientsForCorp } from "../../helpers.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import { cell, requiredTarget, resolveAppAndEntity, splitFields } from "./shared.js";
|
||||
|
||||
function formatDirectRecordFieldValue(val: unknown): string {
|
||||
if (val === undefined || val === null || val === "") return "";
|
||||
@@ -308,7 +47,7 @@ async function handleDirectRecordGet(
|
||||
): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const corpId = runtime.selectedCorp!.credentials.corpId;
|
||||
const detail = await api.getRecordDetail(clients.ekbClient, corpId, recordId);
|
||||
const detail = await getRecordDetail(clients.ekbClient, corpId, recordId);
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -563,7 +302,7 @@ async function handleBatchEdit(
|
||||
};
|
||||
}
|
||||
|
||||
async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
export async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const action = parsed.action?.toLowerCase() || "record";
|
||||
let subAction: string;
|
||||
let appIndex: number;
|
||||
@@ -625,7 +364,7 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
case "get":
|
||||
case "show":
|
||||
case "detail": {
|
||||
const detail = await api.getRecordDetail(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
const detail = await getRecordDetail(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
if (runtime.jsonMode) return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const record = ((detail.dataLink ?? (detail as any).data?.dataLink ?? detail) as Record<string, unknown>);
|
||||
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
@@ -686,7 +425,7 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
active: explicitState ?? "toggle",
|
||||
});
|
||||
}
|
||||
const res = await api.toggleRecordState(resolved.clients.ekbClient, resolved.corpId, recordId, explicitState);
|
||||
const res = await toggleRecordState(resolved.clients.ekbClient, resolved.corpId, recordId, explicitState);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ success: true, recordId: res.recordId, active: res.active, app: resolved.platform.name, entity: resolved.entity.name }, runtime.outputOptions),
|
||||
@@ -714,7 +453,7 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
`hose-use platform record edit ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
|
||||
);
|
||||
|
||||
let payload: api.SafeRecordEditOptions extends never ? never : ReturnType<typeof api.buildSafeRecordEditPayload>;
|
||||
let payload: SafeRecordEditOptions extends never ? never : ReturnType<typeof buildSafeRecordEditPayload>;
|
||||
if (isRaw) {
|
||||
payload = {
|
||||
dataLinkEntityId: resolved.entity.id,
|
||||
@@ -725,14 +464,14 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
} else {
|
||||
let detail: Record<string, unknown> = {};
|
||||
try {
|
||||
detail = await api.getRecordDetail(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
detail = await getRecordDetail(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
} catch (error) {
|
||||
// 在部分仅 mock 了 editRecord 的单元测试中,ekbClient.get 可能未定义,此时退化为空基础详情以兼容测试
|
||||
if (typeof (resolved.clients.ekbClient as any)?.get === "function") {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
payload = api.buildSafeRecordEditPayload({
|
||||
payload = buildSafeRecordEditPayload({
|
||||
entityId: resolved.entity.id,
|
||||
recordId,
|
||||
detail,
|
||||
@@ -745,7 +484,7 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "编辑业务对象记录", recordId, payload);
|
||||
}
|
||||
const result = await api.editRecord(resolved.clients.ekbClient, resolved.corpId, payload);
|
||||
const result = await editRecord(resolved.clients.ekbClient, resolved.corpId, payload);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 字段更新成功。\n`,
|
||||
@@ -768,7 +507,7 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
entityId: resolved.entity.id,
|
||||
});
|
||||
}
|
||||
const result = await api.recomputeRecordLedger(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
const result = await recomputeRecordLedger(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ success: true, recordId, result }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: `✅ 应用 [${resolved.platform.name}] 业务对象 [${resolved.entity.name}] 记录 [${recordId}] 台账重算任务已成功触发。\n`,
|
||||
@@ -780,4 +519,3 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
throw new Error(`未知 record 动作: ${subAction}。支持: get, toggle, edit, batch-edit, recompute`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import {
|
||||
auditEntityRecords,
|
||||
buildKeywordFilter,
|
||||
fetchAllEntityRecords,
|
||||
searchEntityRecords,
|
||||
selectRecordFields,
|
||||
} from "../../../domains/datalink/services.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { cell, resolveAppAndEntity, splitFields } from "./shared.js";
|
||||
|
||||
export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
if (!resolved.entity) throw new Error("请提供业务对象 ID、编码或名称: hose-use platform records <应用> <业务对象>");
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (keyword ? buildKeywordFilter(keyword) : undefined);
|
||||
const fetchAll = booleanOption(parsed.options, ["all", "a"], false);
|
||||
const start = numberOption(parsed.options, ["start", "offset"], 0);
|
||||
const count = numberOption(parsed.options, ["count", "limit"], 20);
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
|
||||
const fields = splitFields(stringOption(parsed.options, ["fields", "select"]));
|
||||
const page = fetchAll
|
||||
? await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { filterBy, pageSize })
|
||||
: await searchEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, { start, count, filterBy });
|
||||
const data = fields.length ? page.data.map((item) => selectRecordFields(item, fields, resolved.entity!.fields)) : page.data;
|
||||
const result = {
|
||||
platform: resolved.platform,
|
||||
entity: resolved.entity,
|
||||
query: { start: fetchAll ? 0 : start, count: fetchAll ? data.length : count, all: fetchAll, filterBy, fields },
|
||||
total: page.total,
|
||||
returned: data.length,
|
||||
data,
|
||||
};
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
const rows = data.map((item, i): Array<string | number | boolean | null | undefined> => {
|
||||
const source = item.dataLink && typeof item.dataLink === "object" && !Array.isArray(item.dataLink) ? (item.dataLink as Record<string, unknown>) : item;
|
||||
const id = source.id ?? item.id;
|
||||
const active = source.active ?? item.active;
|
||||
const updateTime = source.updateTime ?? item.updateTime;
|
||||
const nameVal = source.name ?? source["名称"] ?? (nameField ? source[nameField.name] : undefined) ?? source[`E_${resolved.entity!.id}_name`];
|
||||
const codeVal = source.code ?? source["编码"] ?? (codeField ? source[codeField.name] : undefined) ?? source[`E_${resolved.entity!.id}_code`];
|
||||
const formattedTime = typeof updateTime === "number" ? new Date(updateTime).toLocaleString("zh-CN", { hour12: false }) : cell(updateTime);
|
||||
return [i + 1, cell(id), cell(nameVal), cell(codeVal), active === false ? "停用" : "启用", formattedTime];
|
||||
});
|
||||
return { stdout: `====== [${resolved.platform.name}] ${resolved.entity.name} 记录 (总数: ${page.total}, 当前: ${data.length}${fetchAll ? ", 全量导出" : ""}) ======\n${printTable(["#", "记录 ID", "名称", "编码", "状态", "更新时间"], rows)}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleAudit(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const resolved = await resolveAppAndEntity(parsed, runtime);
|
||||
if (!resolved.entity) {
|
||||
throw new Error("请提供业务对象 ID、编码或名称: hose-use platform audit <应用> <业务对象> [--check-fields=字段1,字段2] [--active-only]");
|
||||
}
|
||||
const checkFields = splitFields(stringOption(parsed.options, ["check-fields", "checkFields", "fields"]));
|
||||
const activeOnly = booleanOption(parsed.options, ["active-only", "activeOnly"], false);
|
||||
const filterBy = stringOption(parsed.options, ["filter", "filter-by", "filterBy"]) || (activeOnly ? "(active==true)" : undefined);
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize"], 500);
|
||||
|
||||
const page = await fetchAllEntityRecords(resolved.clients.ekbClient, resolved.corpId, resolved.entity.id, {
|
||||
filterBy,
|
||||
pageSize,
|
||||
});
|
||||
const report = auditEntityRecords(page.data, resolved.entity, {
|
||||
checkFields,
|
||||
activeOnly,
|
||||
total: page.total,
|
||||
});
|
||||
|
||||
const output = {
|
||||
platform: { id: resolved.platform.id, name: resolved.platform.name, code: resolved.platform.code },
|
||||
entity: { id: resolved.entity.id, name: resolved.entity.name, code: resolved.entity.code },
|
||||
...report,
|
||||
};
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const issueRows = report.issues.map((issue, idx) => [
|
||||
idx + 1,
|
||||
issue.recordId,
|
||||
issue.recordCode || "-",
|
||||
issue.recordName || "-",
|
||||
issue.active ? "🟢 启用" : "🔴 停用",
|
||||
issue.type,
|
||||
issue.fieldLabel,
|
||||
issue.message,
|
||||
]);
|
||||
|
||||
const patchRows = report.suggestedPatches.map((patch, idx) => [
|
||||
idx + 1,
|
||||
patch.id,
|
||||
patch.code || "-",
|
||||
patch.name || "-",
|
||||
JSON.stringify(patch.form),
|
||||
patch.reason,
|
||||
]);
|
||||
|
||||
const outLines = [
|
||||
`====== 台账数据健康度体检: [${resolved.platform.name}] ${resolved.entity.name} (${resolved.entity.id}) ======`,
|
||||
printKeyValue({
|
||||
"总记录数": report.totalRecords,
|
||||
"本次体检记录数": report.auditedRecords,
|
||||
"健康记录数": report.healthyRecords,
|
||||
"异常记录数": report.affectedRecordCount,
|
||||
"总问题项数": report.issueCount,
|
||||
"关键字段缺失 (MISSING_FIELD)": report.summary.missingFieldCount,
|
||||
"引用对象已停用 (DISABLED_REFERENCE)": report.summary.disabledReferenceCount,
|
||||
"跨表同名维度待回填 (CROSS_LEDGER_MISSING_SYNC)": report.summary.crossLedgerMissingSyncCount,
|
||||
"跨表同名维度不一致 (CROSS_LEDGER_MISMATCH)": report.summary.crossLedgerMismatchCount,
|
||||
}),
|
||||
"",
|
||||
"── 异常诊断明细 ──",
|
||||
issueRows.length
|
||||
? printTable(["#", "记录 ID", "编码", "名称", "状态", "问题类型", "字段", "详细说明"], issueRows)
|
||||
: "✅ 未发现任何字段缺失、停用引用或跨表维度不一致问题",
|
||||
];
|
||||
|
||||
if (patchRows.length > 0) {
|
||||
outLines.push("");
|
||||
outLines.push(`── 💡 建议自动回填修复清单 (共 ${patchRows.length} 条记录,可通过 platform record batch-edit 执行) ──`);
|
||||
outLines.push(printTable(["#", "记录 ID", "编码", "名称", "建议 Patch Form", "依据"], patchRows));
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { resolveEntity, resolvePlatform } from "../../../domains/datalink/services.js";
|
||||
import { createClientsForCorp } from "../../helpers.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||
|
||||
export function requiredTarget(parsed: CliParsedArgs, index: number, usage: string): string {
|
||||
const target = parsed.args[index]?.trim();
|
||||
if (!target) throw new Error(`请提供目标参数: ${usage}`);
|
||||
return target;
|
||||
}
|
||||
|
||||
export function splitFields(value?: string): string[] {
|
||||
return value ? value.split(",").map((field) => field.trim()).filter(Boolean) : [];
|
||||
}
|
||||
|
||||
export function cell(value: unknown): string {
|
||||
if (value === undefined || value === null) return "";
|
||||
if (typeof value === "object") return JSON.stringify(value);
|
||||
return String(value);
|
||||
}
|
||||
|
||||
export async function resolveAppAndEntity(parsed: CliParsedArgs, runtime: CliRuntime, appIndex = 0, entityIndex = 1) {
|
||||
const appTarget = requiredTarget(parsed, appIndex, "hose-use platform <子命令> <应用 ID|名称>");
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const corpId = runtime.selectedCorp!.credentials.corpId;
|
||||
const platform = await resolvePlatform(clients.ekbClient, corpId, appTarget);
|
||||
if (!platform) throw new Error(`[NOT FOUND] 当前企业下未找到自建应用: ${appTarget}`);
|
||||
|
||||
const entityTarget = parsed.args[entityIndex]?.trim();
|
||||
if (!entityTarget) return { clients, corpId, platform, entity: undefined };
|
||||
const entity = await resolveEntity(clients.ekbClient, corpId, platform, entityTarget);
|
||||
if (!entity) throw new Error(`[NOT FOUND] 应用 [${platform.name}] 下未找到业务对象: ${entityTarget}`);
|
||||
return { clients, corpId, platform, entity };
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { canRefreshCorpAccessToken, hasOpenApiPersistentCredentials } from "../../core/auth/login.js";
|
||||
import { createSessionClient, getEasoClient } from "../../core/http/index.js";
|
||||
import * as api from "../../domains/platform/api.js";
|
||||
import * as api from "../../domains/platform/services.js";
|
||||
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
|
||||
@@ -25,10 +25,11 @@ export async function handleServiceCommand(
|
||||
const corpId = corp.corpId || corp.id;
|
||||
const client = await createSessionClient(corp);
|
||||
const limit = numberOption(parsed.options, ["limit", "count", "n"], 50) || 50;
|
||||
const store = new EventStore(join(SERVICE_STATE_DIR, `events-${corpId}.json`));
|
||||
const stateFile = stringOption(parsed.options, ["state-file", "stateFile"]);
|
||||
const store = new EventStore(stateFile || `corp:${corpId}`);
|
||||
const result = await pollEvents(client, corpId, store, limit);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 事件轮询 (企业: ${corp.name}) ======\n${printKeyValue({ "待办扫描": result.scanned.todo, "未读消息扫描": result.scanned.messages, "新增事件": result.newEvents.length, "重复事件": result.duplicateCount, "事件状态文件": join(SERVICE_STATE_DIR, `events-${corpId}.json`) })}\n`, stderr: "", exitCode: 0 };
|
||||
return { stdout: `====== 事件轮询 (企业: ${corp.name}) ======\n${printKeyValue({ "待办扫描": result.scanned.todo, "未读消息扫描": result.scanned.messages, "新增事件": result.newEvents.length, "重复事件": result.duplicateCount, "存储后端": stateFile || "SQLite (observed_events)" })}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const config: ServiceConfig = {
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
getDefaultGlobalSkillDir,
|
||||
getSkillContent,
|
||||
installSkillFiles,
|
||||
} from "../../core/embedded-skill.js";
|
||||
} from "../../packaging/embedded-skill.js";
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { printJson, printKeyValue } from "../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
normalizeRepo,
|
||||
isValidRepo,
|
||||
type GitHubAsset,
|
||||
} from "./update.js";
|
||||
} from "./update/index.js";
|
||||
|
||||
describe("update version comparator", () => {
|
||||
test("correctly identifies newer semantic versions", () => {
|
||||
|
||||
@@ -1,18 +1,32 @@
|
||||
import { chmodSync, existsSync, mkdirSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { chmodSync, existsSync, mkdirSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { isCompiledBinary, resolveAppRoot } from "../../core/runtime.js";
|
||||
import { syncGlobalSkillIfPresent } from "../../core/embedded-skill.js";
|
||||
import { loadGlobalConfig } from "../../core/config/loader.js";
|
||||
import { VERSION } from "../../version.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printKeyValue } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "../types.js";
|
||||
|
||||
const DEFAULT_GITHUB_REPO = "yunyingk/hose-use";
|
||||
const GITHUB_REPO_ENV = "HOSE_USE_GITHUB_REPO";
|
||||
|
||||
export type UpdateSourcePreference = "auto" | "github" | "gitea";
|
||||
import { isCompiledBinary, resolveAppRoot } from "../../../packaging/runtime.js";
|
||||
import { syncGlobalSkillIfPresent } from "../../../packaging/embedded-skill.js";
|
||||
import { loadGlobalConfig } from "../../../core/config/loader.js";
|
||||
import { VERSION } from "../../../version.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "../../types.js";
|
||||
import {
|
||||
compareSemVer,
|
||||
detectArch,
|
||||
detectPlatform,
|
||||
downloadFile,
|
||||
extractTarGz,
|
||||
extractZip,
|
||||
fetchGitHubRelease,
|
||||
fetchGitHubReleases,
|
||||
isNewerVersion,
|
||||
isValidRepo,
|
||||
matchAssetForPlatform,
|
||||
normalizeRepo,
|
||||
DEFAULT_GITHUB_REPO,
|
||||
GITHUB_REPO_ENV,
|
||||
type GitHubAsset,
|
||||
type GitHubRelease,
|
||||
type UpdateSourcePreference,
|
||||
} from "./releases.js";
|
||||
|
||||
export type UpdateOptions = {
|
||||
checkOnly?: boolean;
|
||||
@@ -24,16 +38,22 @@ export type UpdateOptions = {
|
||||
sourcePreference: UpdateSourcePreference;
|
||||
};
|
||||
|
||||
export function normalizeRepo(raw: string): string {
|
||||
let repo = raw.trim();
|
||||
repo = repo.replace(/^(https?:\/\/)?(www\.)?github\.com\//i, "");
|
||||
repo = repo.replace(/\.git$/i, "").replace(/\/+$/, "");
|
||||
return repo;
|
||||
}
|
||||
|
||||
export function isValidRepo(repo: string): boolean {
|
||||
return /^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(repo);
|
||||
}
|
||||
// 维持模块级兼容导出:测试与外部此前均从 "./update.js" 导入这些成员。
|
||||
export {
|
||||
compareSemVer,
|
||||
downloadFile,
|
||||
fetchGitHubRelease,
|
||||
fetchGitHubReleases,
|
||||
isValidRepo,
|
||||
isNewerVersion,
|
||||
matchAssetForPlatform,
|
||||
normalizeRepo,
|
||||
DEFAULT_GITHUB_REPO,
|
||||
GITHUB_REPO_ENV,
|
||||
type GitHubAsset,
|
||||
type GitHubRelease,
|
||||
type UpdateSourcePreference,
|
||||
} from "./releases.js";
|
||||
|
||||
export async function handleUpdateCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -512,452 +532,6 @@ export async function handleUpdateCommand(
|
||||
}
|
||||
}
|
||||
|
||||
function detectPlatform(): "darwin" | "linux" | "windows" {
|
||||
if (process.platform === "darwin") return "darwin";
|
||||
if (process.platform === "win32") return "windows";
|
||||
return "linux";
|
||||
}
|
||||
|
||||
function detectArch(): "arm64" | "x64" {
|
||||
return process.arch === "arm64" ? "arm64" : "x64";
|
||||
}
|
||||
|
||||
export type GitHubAsset = {
|
||||
name: string;
|
||||
downloadUrl: string;
|
||||
size: number;
|
||||
};
|
||||
|
||||
export type GitHubRelease = {
|
||||
version: string;
|
||||
tagName: string;
|
||||
name?: string;
|
||||
publishedAt?: string;
|
||||
author?: string;
|
||||
notes: string;
|
||||
htmlUrl: string;
|
||||
assets: GitHubAsset[];
|
||||
};
|
||||
|
||||
export async function fetchGitHubReleases(
|
||||
repo: string,
|
||||
limit = 20,
|
||||
sourcePreference: UpdateSourcePreference = "auto"
|
||||
): Promise<GitHubRelease[]> {
|
||||
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
||||
const headers: Record<string, string> = {
|
||||
"User-Agent": `hose-use/${VERSION}`,
|
||||
Accept: "application/vnd.github.v3+json",
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
};
|
||||
|
||||
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
|
||||
const allowGitea = isDefaultRepo && sourcePreference !== "github";
|
||||
|
||||
const urls: string[] = [];
|
||||
if (sourcePreference === "github") {
|
||||
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
|
||||
} else if (sourcePreference === "gitea") {
|
||||
if (allowGitea) {
|
||||
urls.push(`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${limit}`);
|
||||
}
|
||||
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
|
||||
} else {
|
||||
if (allowGitea) {
|
||||
urls.push(`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${limit}`);
|
||||
}
|
||||
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
|
||||
}
|
||||
|
||||
let fallbackList: GitHubRelease[] = [];
|
||||
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
|
||||
if (!res.ok) continue;
|
||||
const json = (await res.json()) as Array<{
|
||||
tag_name?: string;
|
||||
name?: string;
|
||||
body?: string;
|
||||
html_url?: string;
|
||||
published_at?: string;
|
||||
author?: { login?: string };
|
||||
assets?: Array<{ name: string; browser_download_url: string; size?: number }>;
|
||||
}>;
|
||||
|
||||
if (!Array.isArray(json) || json.length === 0) continue;
|
||||
|
||||
const list: GitHubRelease[] = [];
|
||||
for (const item of json) {
|
||||
const tagName = item.tag_name ?? "";
|
||||
const version = tagName.replace(/^v/, "");
|
||||
if (!version) continue;
|
||||
const assets: GitHubAsset[] = (item.assets ?? []).map((a) => ({
|
||||
name: a.name,
|
||||
downloadUrl: a.browser_download_url,
|
||||
size: a.size ?? 0,
|
||||
}));
|
||||
list.push({
|
||||
version,
|
||||
tagName,
|
||||
name: item.name ?? tagName,
|
||||
publishedAt: item.published_at,
|
||||
author: item.author?.login,
|
||||
notes: item.body ?? "",
|
||||
htmlUrl: item.html_url ?? "",
|
||||
assets,
|
||||
});
|
||||
}
|
||||
if (list.length > 0) {
|
||||
if (list.some((r) => r.assets.length > 0)) {
|
||||
return list;
|
||||
}
|
||||
if (fallbackList.length === 0) {
|
||||
fallbackList = list;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// try next source
|
||||
}
|
||||
}
|
||||
|
||||
return fallbackList;
|
||||
}
|
||||
|
||||
export async function fetchGitHubRelease(
|
||||
repo: string,
|
||||
targetVersion?: string,
|
||||
sourcePreference: UpdateSourcePreference = "auto"
|
||||
): Promise<GitHubRelease | undefined> {
|
||||
const tag = targetVersion ? (targetVersion.startsWith("v") ? targetVersion : `v${targetVersion}`) : undefined;
|
||||
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
||||
const headers: Record<string, string> = {
|
||||
"User-Agent": `hose-use/${VERSION}`,
|
||||
Accept: "application/vnd.github.v3+json",
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
};
|
||||
|
||||
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
|
||||
const allowGitea = isDefaultRepo && sourcePreference !== "github";
|
||||
|
||||
const urls: string[] = [];
|
||||
const giteaTagUrl = tag
|
||||
? `https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/tags/${tag}`
|
||||
: `https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest`;
|
||||
const githubTagUrl = tag
|
||||
? `https://api.github.com/repos/${repo}/releases/tags/${tag}`
|
||||
: `https://api.github.com/repos/${repo}/releases/latest`;
|
||||
|
||||
if (sourcePreference === "github") {
|
||||
urls.push(githubTagUrl);
|
||||
} else if (sourcePreference === "gitea") {
|
||||
if (allowGitea) urls.push(giteaTagUrl);
|
||||
urls.push(githubTagUrl);
|
||||
} else {
|
||||
if (allowGitea) urls.push(giteaTagUrl);
|
||||
urls.push(githubTagUrl);
|
||||
}
|
||||
|
||||
let fallbackRelease: GitHubRelease | undefined;
|
||||
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
|
||||
if (!res.ok) continue;
|
||||
const json = (await res.json()) as {
|
||||
tag_name?: string;
|
||||
name?: string;
|
||||
body?: string;
|
||||
html_url?: string;
|
||||
published_at?: string;
|
||||
author?: { login?: string };
|
||||
assets?: Array<{ name: string; browser_download_url: string; size?: number }>;
|
||||
};
|
||||
|
||||
const tagName = json.tag_name ?? "";
|
||||
const version = tagName.replace(/^v/, "");
|
||||
if (!version) continue;
|
||||
|
||||
const assets: GitHubAsset[] = (json.assets ?? []).map((item) => ({
|
||||
name: item.name,
|
||||
downloadUrl: item.browser_download_url,
|
||||
size: item.size ?? 0,
|
||||
}));
|
||||
|
||||
const candidateRelease: GitHubRelease = {
|
||||
version,
|
||||
tagName,
|
||||
name: json.name ?? tagName,
|
||||
publishedAt: json.published_at,
|
||||
author: json.author?.login,
|
||||
notes: json.body ?? "",
|
||||
htmlUrl: json.html_url ?? "",
|
||||
assets,
|
||||
};
|
||||
|
||||
if (assets.length > 0) {
|
||||
return candidateRelease;
|
||||
}
|
||||
|
||||
if (!fallbackRelease) {
|
||||
fallbackRelease = candidateRelease;
|
||||
}
|
||||
} catch {
|
||||
// try next source
|
||||
}
|
||||
}
|
||||
|
||||
return fallbackRelease;
|
||||
}
|
||||
|
||||
export function matchAssetForPlatform(
|
||||
assets: GitHubAsset[],
|
||||
platform: "darwin" | "linux" | "windows",
|
||||
arch: "arm64" | "x64"
|
||||
): GitHubAsset | undefined {
|
||||
const platformKeywords: Record<string, string[]> = {
|
||||
darwin: ["darwin", "macos", "osx", "apple"],
|
||||
linux: ["linux"],
|
||||
windows: ["windows", "win32", "win64", ".exe"],
|
||||
};
|
||||
const archKeywords: Record<string, string[]> = {
|
||||
arm64: ["arm64", "aarch64"],
|
||||
x64: ["x64", "x86_64", "amd64"],
|
||||
};
|
||||
|
||||
const pKeys = platformKeywords[platform] || [];
|
||||
const aKeys = archKeywords[arch] || [];
|
||||
|
||||
const matched = assets.filter((asset) => {
|
||||
const lower = asset.name.toLowerCase();
|
||||
const matchesP = pKeys.some((k) => lower.includes(k));
|
||||
const matchesA = aKeys.some((k) => lower.includes(k));
|
||||
return matchesP && matchesA;
|
||||
});
|
||||
|
||||
// Prefer compressed archives (.tar.gz / .zip) over raw binary for faster downloads (25MB vs 65MB+)
|
||||
const archive = matched.find(
|
||||
(asset) =>
|
||||
asset.name.endsWith(".tar.gz") ||
|
||||
asset.name.endsWith(".tgz") ||
|
||||
asset.name.endsWith(".zip")
|
||||
);
|
||||
if (archive) return archive;
|
||||
|
||||
// Fallback to direct raw binary if available
|
||||
const directBinary = matched.find(
|
||||
(asset) =>
|
||||
!asset.name.endsWith(".tar.gz") &&
|
||||
!asset.name.endsWith(".tgz") &&
|
||||
!asset.name.endsWith(".zip") &&
|
||||
!asset.name.endsWith(".sha256")
|
||||
);
|
||||
return directBinary || matched[0];
|
||||
}
|
||||
|
||||
function logProgress(msg: string) {
|
||||
try {
|
||||
process.stderr.write(`${msg}\n`);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
export async function downloadFile(
|
||||
url: string,
|
||||
destPath: string,
|
||||
tagName?: string,
|
||||
assetName?: string,
|
||||
repo: string = DEFAULT_GITHUB_REPO,
|
||||
sourcePreference: UpdateSourcePreference = "auto"
|
||||
) {
|
||||
const candidates: string[] = [];
|
||||
const tag = tagName ? (tagName.startsWith("v") ? tagName : `v${tagName}`) : undefined;
|
||||
const fileName = assetName || url.split("/").pop() || "";
|
||||
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
|
||||
const allowGitea = isDefaultRepo && sourcePreference !== "github";
|
||||
|
||||
// 1. High-speed Gitea direct mirror first (only for default official repo)
|
||||
if (allowGitea) {
|
||||
if (tag && fileName) {
|
||||
candidates.push(`https://git.ying-qing.cn/gitea/hose-use/releases/download/${tag}/${fileName}`);
|
||||
}
|
||||
if (url.startsWith("https://git.ying-qing.cn")) {
|
||||
candidates.push(url);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Fast GitHub CDN proxies and direct GitHub fallback (dynamic repo)
|
||||
if (tag && fileName) {
|
||||
const ghDirectUrl = `https://github.com/${repo}/releases/download/${tag}/${fileName}`;
|
||||
if (sourcePreference !== "gitea") {
|
||||
candidates.push(`https://ghfast.top/${ghDirectUrl}`);
|
||||
candidates.push(`https://ghproxy.net/${ghDirectUrl}`);
|
||||
candidates.push(`https://gh.ddlc.top/${ghDirectUrl}`);
|
||||
candidates.push(`https://mirror.ghproxy.com/${ghDirectUrl}`);
|
||||
}
|
||||
candidates.push(ghDirectUrl);
|
||||
} else if (url.includes("github.com")) {
|
||||
if (sourcePreference !== "gitea") {
|
||||
candidates.push(`https://ghfast.top/${url}`);
|
||||
candidates.push(`https://ghproxy.net/${url}`);
|
||||
candidates.push(`https://gh.ddlc.top/${url}`);
|
||||
candidates.push(`https://mirror.ghproxy.com/${url}`);
|
||||
}
|
||||
candidates.push(url);
|
||||
} else {
|
||||
candidates.push(url);
|
||||
}
|
||||
|
||||
const uniqueCandidates = Array.from(new Set(candidates));
|
||||
|
||||
let lastError: Error | undefined;
|
||||
for (let i = 0; i < uniqueCandidates.length; i++) {
|
||||
const candidate = uniqueCandidates[i]!;
|
||||
try {
|
||||
logProgress(`==> [${i + 1}/${uniqueCandidates.length}] 正在下载更新: ${candidate}`);
|
||||
const reqHeaders: Record<string, string> = {
|
||||
"User-Agent": `hose-use/${VERSION}`,
|
||||
};
|
||||
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
||||
if (token && candidate.includes("github.com")) {
|
||||
reqHeaders["Authorization"] = `Bearer ${token}`;
|
||||
}
|
||||
const res = await fetch(candidate, {
|
||||
headers: reqHeaders,
|
||||
signal: AbortSignal.timeout(600_000), // 放宽至 600 秒(10 分钟),保障大体积二进制完整下载
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status} ${res.statusText}`);
|
||||
}
|
||||
|
||||
const totalBytes = Number(res.headers.get("content-length")) || 0;
|
||||
const reader = res.body?.getReader();
|
||||
if (!reader) {
|
||||
const buffer = Buffer.from(await res.arrayBuffer());
|
||||
if (buffer.length < 1000) {
|
||||
throw new Error(`下载文件异常(大小仅 ${buffer.length} 字节)`);
|
||||
}
|
||||
writeFileSync(destPath, buffer);
|
||||
logProgress(`✓ 下载完成 (${(buffer.length / 1024 / 1024).toFixed(1)} MB)`);
|
||||
return;
|
||||
}
|
||||
|
||||
const chunks: Uint8Array[] = [];
|
||||
let receivedBytes = 0;
|
||||
let lastReport = 0;
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (value) {
|
||||
chunks.push(value);
|
||||
receivedBytes += value.length;
|
||||
const now = Date.now();
|
||||
if (now - lastReport > 200) {
|
||||
lastReport = now;
|
||||
const percent = totalBytes ? Math.round((receivedBytes / totalBytes) * 100) : 0;
|
||||
const receivedMb = (receivedBytes / (1024 * 1024)).toFixed(1);
|
||||
const totalMb = totalBytes ? (totalBytes / (1024 * 1024)).toFixed(1) : "?";
|
||||
try {
|
||||
process.stderr.write(`\r ↳ 进度: ${percent}% (${receivedMb} / ${totalMb} MB)...`);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
process.stderr.write("\n");
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
const completeBuffer = Buffer.concat(chunks);
|
||||
if (completeBuffer.length < 1000) {
|
||||
throw new Error(`下载文件异常(大小仅 ${completeBuffer.length} 字节)`);
|
||||
}
|
||||
writeFileSync(destPath, completeBuffer);
|
||||
logProgress(`✓ 下载完成 (${(completeBuffer.length / 1024 / 1024).toFixed(1)} MB)`);
|
||||
return;
|
||||
} catch (err) {
|
||||
lastError = err instanceof Error ? err : new Error(String(err));
|
||||
logProgress(` ↳ 节点失败: ${lastError.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`所有下载镜像均失败: ${lastError?.message}`);
|
||||
}
|
||||
|
||||
function extractTarGz(archivePath: string, targetDir: string, platform: string): string {
|
||||
const result = spawnSync("tar", ["-xzf", archivePath, "-C", targetDir], { stdio: "pipe" });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`解压 tar 归档失败: ${result.stderr.toString()}`);
|
||||
}
|
||||
unlinkSync(archivePath);
|
||||
|
||||
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
|
||||
.stdout.trim()
|
||||
.split("\n")
|
||||
.filter(Boolean);
|
||||
|
||||
// Exact match for hose-use or hose-use.exe
|
||||
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
|
||||
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
|
||||
if (exact) return exact;
|
||||
|
||||
// Next match for hose-use-darwin-arm64 etc., excluding hose-aipro
|
||||
const platformBinary = files.find((f) => {
|
||||
const base = f.split("/").pop() || "";
|
||||
return base.startsWith("hose-use-") && !base.endsWith(".cmd") && !base.endsWith(".json");
|
||||
});
|
||||
if (platformBinary) return platformBinary;
|
||||
|
||||
return files.find((f) => !f.endsWith("hose-aipro")) || files[0] || archivePath;
|
||||
}
|
||||
|
||||
function extractZip(archivePath: string, targetDir: string, platform: string): string {
|
||||
const result = spawnSync("unzip", ["-q", "-o", archivePath, "-d", targetDir], { stdio: "pipe" });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`解压 zip 归档失败: ${result.stderr.toString()}`);
|
||||
}
|
||||
unlinkSync(archivePath);
|
||||
|
||||
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
|
||||
.stdout.trim()
|
||||
.split("\n")
|
||||
.filter(Boolean);
|
||||
|
||||
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
|
||||
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
|
||||
if (exact) return exact;
|
||||
|
||||
const platformBinary = files.find((f) => {
|
||||
const base = f.split("/").pop() || "";
|
||||
return base.startsWith("hose-use-") && !base.endsWith(".cmd") && !base.endsWith(".json");
|
||||
});
|
||||
if (platformBinary) return platformBinary;
|
||||
|
||||
return files.find((f) => !f.endsWith("hose-aipro")) || files[0] || archivePath;
|
||||
}
|
||||
|
||||
export function compareSemVer(v1: string, v2: string): number {
|
||||
const p1 = v1.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
|
||||
const p2 = v2.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
|
||||
for (let i = 0; i < Math.max(p1.length, p2.length); i++) {
|
||||
const a = p1[i] ?? 0;
|
||||
const b = p2[i] ?? 0;
|
||||
if (a > b) return 1;
|
||||
if (a < b) return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function isNewerVersion(latest: string, current: string): boolean {
|
||||
return compareSemVer(latest, current) > 0;
|
||||
}
|
||||
|
||||
function runCommand(command: string, args: string[], options: { cwd?: string } = {}) {
|
||||
const result = spawnSync(command, args, {
|
||||
cwd: options.cwd,
|
||||
@@ -0,0 +1,465 @@
|
||||
import { unlinkSync, writeFileSync } from "node:fs";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { VERSION } from "../../../version.js";
|
||||
|
||||
export const DEFAULT_GITHUB_REPO = "yunyingk/hose-use";
|
||||
export const GITHUB_REPO_ENV = "HOSE_USE_GITHUB_REPO";
|
||||
|
||||
export type UpdateSourcePreference = "auto" | "github" | "gitea";
|
||||
|
||||
export function normalizeRepo(raw: string): string {
|
||||
let repo = raw.trim();
|
||||
repo = repo.replace(/^(https?:\/\/)?(www\.)?github\.com\//i, "");
|
||||
repo = repo.replace(/\.git$/i, "").replace(/\/+$/, "");
|
||||
return repo;
|
||||
}
|
||||
|
||||
export function isValidRepo(repo: string): boolean {
|
||||
return /^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(repo);
|
||||
}
|
||||
|
||||
export function detectPlatform(): "darwin" | "linux" | "windows" {
|
||||
if (process.platform === "darwin") return "darwin";
|
||||
if (process.platform === "win32") return "windows";
|
||||
return "linux";
|
||||
}
|
||||
|
||||
export function detectArch(): "arm64" | "x64" {
|
||||
return process.arch === "arm64" ? "arm64" : "x64";
|
||||
}
|
||||
|
||||
export type GitHubAsset = {
|
||||
name: string;
|
||||
downloadUrl: string;
|
||||
size: number;
|
||||
};
|
||||
|
||||
export type GitHubRelease = {
|
||||
version: string;
|
||||
tagName: string;
|
||||
name?: string;
|
||||
publishedAt?: string;
|
||||
author?: string;
|
||||
notes: string;
|
||||
htmlUrl: string;
|
||||
assets: GitHubAsset[];
|
||||
};
|
||||
|
||||
export async function fetchGitHubReleases(
|
||||
repo: string,
|
||||
limit = 20,
|
||||
sourcePreference: UpdateSourcePreference = "auto"
|
||||
): Promise<GitHubRelease[]> {
|
||||
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
||||
const headers: Record<string, string> = {
|
||||
"User-Agent": `hose-use/${VERSION}`,
|
||||
Accept: "application/vnd.github.v3+json",
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
};
|
||||
|
||||
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
|
||||
const allowGitea = isDefaultRepo && sourcePreference !== "github";
|
||||
|
||||
const urls: string[] = [];
|
||||
if (sourcePreference === "github") {
|
||||
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
|
||||
} else if (sourcePreference === "gitea") {
|
||||
if (allowGitea) {
|
||||
urls.push(`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${limit}`);
|
||||
}
|
||||
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
|
||||
} else {
|
||||
if (allowGitea) {
|
||||
urls.push(`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${limit}`);
|
||||
}
|
||||
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
|
||||
}
|
||||
|
||||
let fallbackList: GitHubRelease[] = [];
|
||||
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
|
||||
if (!res.ok) continue;
|
||||
const json = (await res.json()) as Array<{
|
||||
tag_name?: string;
|
||||
name?: string;
|
||||
body?: string;
|
||||
html_url?: string;
|
||||
published_at?: string;
|
||||
author?: { login?: string };
|
||||
assets?: Array<{ name: string; browser_download_url: string; size?: number }>;
|
||||
}>;
|
||||
|
||||
if (!Array.isArray(json) || json.length === 0) continue;
|
||||
|
||||
const list: GitHubRelease[] = [];
|
||||
for (const item of json) {
|
||||
const tagName = item.tag_name ?? "";
|
||||
const version = tagName.replace(/^v/, "");
|
||||
if (!version) continue;
|
||||
const assets: GitHubAsset[] = (item.assets ?? []).map((a) => ({
|
||||
name: a.name,
|
||||
downloadUrl: a.browser_download_url,
|
||||
size: a.size ?? 0,
|
||||
}));
|
||||
list.push({
|
||||
version,
|
||||
tagName,
|
||||
name: item.name ?? tagName,
|
||||
publishedAt: item.published_at,
|
||||
author: item.author?.login,
|
||||
notes: item.body ?? "",
|
||||
htmlUrl: item.html_url ?? "",
|
||||
assets,
|
||||
});
|
||||
}
|
||||
if (list.length > 0) {
|
||||
if (list.some((r) => r.assets.length > 0)) {
|
||||
return list;
|
||||
}
|
||||
if (fallbackList.length === 0) {
|
||||
fallbackList = list;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// try next source
|
||||
}
|
||||
}
|
||||
|
||||
return fallbackList;
|
||||
}
|
||||
|
||||
export async function fetchGitHubRelease(
|
||||
repo: string,
|
||||
targetVersion?: string,
|
||||
sourcePreference: UpdateSourcePreference = "auto"
|
||||
): Promise<GitHubRelease | undefined> {
|
||||
const tag = targetVersion ? (targetVersion.startsWith("v") ? targetVersion : `v${targetVersion}`) : undefined;
|
||||
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
||||
const headers: Record<string, string> = {
|
||||
"User-Agent": `hose-use/${VERSION}`,
|
||||
Accept: "application/vnd.github.v3+json",
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
};
|
||||
|
||||
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
|
||||
const allowGitea = isDefaultRepo && sourcePreference !== "github";
|
||||
|
||||
const urls: string[] = [];
|
||||
const giteaTagUrl = tag
|
||||
? `https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/tags/${tag}`
|
||||
: `https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest`;
|
||||
const githubTagUrl = tag
|
||||
? `https://api.github.com/repos/${repo}/releases/tags/${tag}`
|
||||
: `https://api.github.com/repos/${repo}/releases/latest`;
|
||||
|
||||
if (sourcePreference === "github") {
|
||||
urls.push(githubTagUrl);
|
||||
} else if (sourcePreference === "gitea") {
|
||||
if (allowGitea) urls.push(giteaTagUrl);
|
||||
urls.push(githubTagUrl);
|
||||
} else {
|
||||
if (allowGitea) urls.push(giteaTagUrl);
|
||||
urls.push(githubTagUrl);
|
||||
}
|
||||
|
||||
let fallbackRelease: GitHubRelease | undefined;
|
||||
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
|
||||
if (!res.ok) continue;
|
||||
const json = (await res.json()) as {
|
||||
tag_name?: string;
|
||||
name?: string;
|
||||
body?: string;
|
||||
html_url?: string;
|
||||
published_at?: string;
|
||||
author?: { login?: string };
|
||||
assets?: Array<{ name: string; browser_download_url: string; size?: number }>;
|
||||
};
|
||||
|
||||
const tagName = json.tag_name ?? "";
|
||||
const version = tagName.replace(/^v/, "");
|
||||
if (!version) continue;
|
||||
|
||||
const assets: GitHubAsset[] = (json.assets ?? []).map((item) => ({
|
||||
name: item.name,
|
||||
downloadUrl: item.browser_download_url,
|
||||
size: item.size ?? 0,
|
||||
}));
|
||||
|
||||
const candidateRelease: GitHubRelease = {
|
||||
version,
|
||||
tagName,
|
||||
name: json.name ?? tagName,
|
||||
publishedAt: json.published_at,
|
||||
author: json.author?.login,
|
||||
notes: json.body ?? "",
|
||||
htmlUrl: json.html_url ?? "",
|
||||
assets,
|
||||
};
|
||||
|
||||
if (assets.length > 0) {
|
||||
return candidateRelease;
|
||||
}
|
||||
|
||||
if (!fallbackRelease) {
|
||||
fallbackRelease = candidateRelease;
|
||||
}
|
||||
} catch {
|
||||
// try next source
|
||||
}
|
||||
}
|
||||
|
||||
return fallbackRelease;
|
||||
}
|
||||
|
||||
export function matchAssetForPlatform(
|
||||
assets: GitHubAsset[],
|
||||
platform: "darwin" | "linux" | "windows",
|
||||
arch: "arm64" | "x64"
|
||||
): GitHubAsset | undefined {
|
||||
const platformKeywords: Record<string, string[]> = {
|
||||
darwin: ["darwin", "macos", "osx", "apple"],
|
||||
linux: ["linux"],
|
||||
windows: ["windows", "win32", "win64", ".exe"],
|
||||
};
|
||||
const archKeywords: Record<string, string[]> = {
|
||||
arm64: ["arm64", "aarch64"],
|
||||
x64: ["x64", "x86_64", "amd64"],
|
||||
};
|
||||
|
||||
const pKeys = platformKeywords[platform] || [];
|
||||
const aKeys = archKeywords[arch] || [];
|
||||
|
||||
const matched = assets.filter((asset) => {
|
||||
const lower = asset.name.toLowerCase();
|
||||
const matchesP = pKeys.some((k) => lower.includes(k));
|
||||
const matchesA = aKeys.some((k) => lower.includes(k));
|
||||
return matchesP && matchesA;
|
||||
});
|
||||
|
||||
// Prefer compressed archives (.tar.gz / .zip) over raw binary for faster downloads (25MB vs 65MB+)
|
||||
const archive = matched.find(
|
||||
(asset) =>
|
||||
asset.name.endsWith(".tar.gz") ||
|
||||
asset.name.endsWith(".tgz") ||
|
||||
asset.name.endsWith(".zip")
|
||||
);
|
||||
if (archive) return archive;
|
||||
|
||||
// Fallback to direct raw binary if available
|
||||
const directBinary = matched.find(
|
||||
(asset) =>
|
||||
!asset.name.endsWith(".tar.gz") &&
|
||||
!asset.name.endsWith(".tgz") &&
|
||||
!asset.name.endsWith(".zip") &&
|
||||
!asset.name.endsWith(".sha256")
|
||||
);
|
||||
return directBinary || matched[0];
|
||||
}
|
||||
|
||||
function logProgress(msg: string) {
|
||||
try {
|
||||
process.stderr.write(`${msg}\n`);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
export async function downloadFile(
|
||||
url: string,
|
||||
destPath: string,
|
||||
tagName?: string,
|
||||
assetName?: string,
|
||||
repo: string = DEFAULT_GITHUB_REPO,
|
||||
sourcePreference: UpdateSourcePreference = "auto"
|
||||
) {
|
||||
const candidates: string[] = [];
|
||||
const tag = tagName ? (tagName.startsWith("v") ? tagName : `v${tagName}`) : undefined;
|
||||
const fileName = assetName || url.split("/").pop() || "";
|
||||
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
|
||||
const allowGitea = isDefaultRepo && sourcePreference !== "github";
|
||||
|
||||
// 1. High-speed Gitea direct mirror first (only for default official repo)
|
||||
if (allowGitea) {
|
||||
if (tag && fileName) {
|
||||
candidates.push(`https://git.ying-qing.cn/gitea/hose-use/releases/download/${tag}/${fileName}`);
|
||||
}
|
||||
if (url.startsWith("https://git.ying-qing.cn")) {
|
||||
candidates.push(url);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Fast GitHub CDN proxies and direct GitHub fallback (dynamic repo)
|
||||
if (tag && fileName) {
|
||||
const ghDirectUrl = `https://github.com/${repo}/releases/download/${tag}/${fileName}`;
|
||||
if (sourcePreference !== "gitea") {
|
||||
candidates.push(`https://ghfast.top/${ghDirectUrl}`);
|
||||
candidates.push(`https://ghproxy.net/${ghDirectUrl}`);
|
||||
candidates.push(`https://gh.ddlc.top/${ghDirectUrl}`);
|
||||
candidates.push(`https://mirror.ghproxy.com/${ghDirectUrl}`);
|
||||
}
|
||||
candidates.push(ghDirectUrl);
|
||||
} else if (url.includes("github.com")) {
|
||||
if (sourcePreference !== "gitea") {
|
||||
candidates.push(`https://ghfast.top/${url}`);
|
||||
candidates.push(`https://ghproxy.net/${url}`);
|
||||
candidates.push(`https://gh.ddlc.top/${url}`);
|
||||
candidates.push(`https://mirror.ghproxy.com/${url}`);
|
||||
}
|
||||
candidates.push(url);
|
||||
} else {
|
||||
candidates.push(url);
|
||||
}
|
||||
|
||||
const uniqueCandidates = Array.from(new Set(candidates));
|
||||
|
||||
let lastError: Error | undefined;
|
||||
for (let i = 0; i < uniqueCandidates.length; i++) {
|
||||
const candidate = uniqueCandidates[i]!;
|
||||
try {
|
||||
logProgress(`==> [${i + 1}/${uniqueCandidates.length}] 正在下载更新: ${candidate}`);
|
||||
const reqHeaders: Record<string, string> = {
|
||||
"User-Agent": `hose-use/${VERSION}`,
|
||||
};
|
||||
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
||||
if (token && candidate.includes("github.com")) {
|
||||
reqHeaders["Authorization"] = `Bearer ${token}`;
|
||||
}
|
||||
const res = await fetch(candidate, {
|
||||
headers: reqHeaders,
|
||||
signal: AbortSignal.timeout(600_000), // 放宽至 600 秒(10 分钟),保障大体积二进制完整下载
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status} ${res.statusText}`);
|
||||
}
|
||||
|
||||
const totalBytes = Number(res.headers.get("content-length")) || 0;
|
||||
const reader = res.body?.getReader();
|
||||
if (!reader) {
|
||||
const buffer = Buffer.from(await res.arrayBuffer());
|
||||
if (buffer.length < 1000) {
|
||||
throw new Error(`下载文件异常(大小仅 ${buffer.length} 字节)`);
|
||||
}
|
||||
writeFileSync(destPath, buffer);
|
||||
logProgress(`✓ 下载完成 (${(buffer.length / 1024 / 1024).toFixed(1)} MB)`);
|
||||
return;
|
||||
}
|
||||
|
||||
const chunks: Uint8Array[] = [];
|
||||
let receivedBytes = 0;
|
||||
let lastReport = 0;
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (value) {
|
||||
chunks.push(value);
|
||||
receivedBytes += value.length;
|
||||
const now = Date.now();
|
||||
if (now - lastReport > 200) {
|
||||
lastReport = now;
|
||||
const percent = totalBytes ? Math.round((receivedBytes / totalBytes) * 100) : 0;
|
||||
const receivedMb = (receivedBytes / (1024 * 1024)).toFixed(1);
|
||||
const totalMb = totalBytes ? (totalBytes / (1024 * 1024)).toFixed(1) : "?";
|
||||
try {
|
||||
process.stderr.write(`\r ↳ 进度: ${percent}% (${receivedMb} / ${totalMb} MB)...`);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
process.stderr.write("\n");
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
const completeBuffer = Buffer.concat(chunks);
|
||||
if (completeBuffer.length < 1000) {
|
||||
throw new Error(`下载文件异常(大小仅 ${completeBuffer.length} 字节)`);
|
||||
}
|
||||
writeFileSync(destPath, completeBuffer);
|
||||
logProgress(`✓ 下载完成 (${(completeBuffer.length / 1024 / 1024).toFixed(1)} MB)`);
|
||||
return;
|
||||
} catch (err) {
|
||||
lastError = err instanceof Error ? err : new Error(String(err));
|
||||
logProgress(` ↳ 节点失败: ${lastError.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`所有下载镜像均失败: ${lastError?.message}`);
|
||||
}
|
||||
|
||||
export function extractTarGz(archivePath: string, targetDir: string, platform: string): string {
|
||||
const result = spawnSync("tar", ["-xzf", archivePath, "-C", targetDir], { stdio: "pipe" });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`解压 tar 归档失败: ${result.stderr.toString()}`);
|
||||
}
|
||||
unlinkSync(archivePath);
|
||||
|
||||
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
|
||||
.stdout.trim()
|
||||
.split("\n")
|
||||
.filter(Boolean);
|
||||
|
||||
// Exact match for hose-use or hose-use.exe
|
||||
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
|
||||
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
|
||||
if (exact) return exact;
|
||||
|
||||
// Next match for hose-use-darwin-arm64 etc., excluding hose-aipro
|
||||
const platformBinary = files.find((f) => {
|
||||
const base = f.split("/").pop() || "";
|
||||
return base.startsWith("hose-use-") && !base.endsWith(".cmd") && !base.endsWith(".json");
|
||||
});
|
||||
if (platformBinary) return platformBinary;
|
||||
|
||||
return files.find((f) => !f.endsWith("hose-aipro")) || files[0] || archivePath;
|
||||
}
|
||||
|
||||
export function extractZip(archivePath: string, targetDir: string, platform: string): string {
|
||||
const result = spawnSync("unzip", ["-q", "-o", archivePath, "-d", targetDir], { stdio: "pipe" });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`解压 zip 归档失败: ${result.stderr.toString()}`);
|
||||
}
|
||||
unlinkSync(archivePath);
|
||||
|
||||
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
|
||||
.stdout.trim()
|
||||
.split("\n")
|
||||
.filter(Boolean);
|
||||
|
||||
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
|
||||
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
|
||||
if (exact) return exact;
|
||||
|
||||
const platformBinary = files.find((f) => {
|
||||
const base = f.split("/").pop() || "";
|
||||
return base.startsWith("hose-use-") && !base.endsWith(".cmd") && !base.endsWith(".json");
|
||||
});
|
||||
if (platformBinary) return platformBinary;
|
||||
|
||||
return files.find((f) => !f.endsWith("hose-aipro")) || files[0] || archivePath;
|
||||
}
|
||||
|
||||
export function compareSemVer(v1: string, v2: string): number {
|
||||
const p1 = v1.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
|
||||
const p2 = v2.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
|
||||
for (let i = 0; i < Math.max(p1.length, p2.length); i++) {
|
||||
const a = p1[i] ?? 0;
|
||||
const b = p2[i] ?? 0;
|
||||
if (a > b) return 1;
|
||||
if (a < b) return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function isNewerVersion(latest: string, current: string): boolean {
|
||||
return compareSemVer(latest, current) > 0;
|
||||
}
|
||||
@@ -1,981 +0,0 @@
|
||||
import {
|
||||
listAllWorkflows,
|
||||
findWorkflowsByTaskType,
|
||||
} from "../../domains/platform/services.js";
|
||||
import * as api from "../../domains/platform/api.js";
|
||||
import { stringOption, numberOption, booleanOption } from "../parser.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../helpers.js";
|
||||
import { printJson, printTable, printKeyValue } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import {
|
||||
analyzeWorkflow,
|
||||
extractWorkflowSpecificationIds,
|
||||
type WorkflowFormSpecLike,
|
||||
} from "../../domains/platform/analysis.js";
|
||||
import { getFormSpecification } from "../../domains/bill/tools.js";
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { WorkflowDetailSchema, type WorkflowTaskExecution } from "../../domains/platform/types.js";
|
||||
import {
|
||||
createWorkflowDraft,
|
||||
beginWorkflowSave,
|
||||
commitWorkflowSave,
|
||||
failWorkflowSave,
|
||||
hasWorkflowVersionConflict,
|
||||
applyWorkflowPathPatch,
|
||||
} from "../../domains/platform/workflow-state.js";
|
||||
import { WorkflowAlertStore } from "../../domains/platform/workflow-alert-store.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
|
||||
const WORKFLOW_STATE_DIR = process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
|
||||
const PLATFORM_ID_OPTION_KEYS = ["platform-id", "platformId", "app-id", "appId"];
|
||||
|
||||
export async function handleWorkflowCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const currentCorp = runtime.selectedCorp;
|
||||
if (!currentCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const action = parsed.action || "list";
|
||||
|
||||
switch (action) {
|
||||
case "list":
|
||||
case "list-all":
|
||||
case "ls":
|
||||
return handleList(parsed, runtime);
|
||||
case "get":
|
||||
case "detail":
|
||||
case "info":
|
||||
return handleGet(parsed, runtime);
|
||||
case "find":
|
||||
case "search":
|
||||
return handleFind(parsed, runtime);
|
||||
case "toggle":
|
||||
return handleToggle(parsed, runtime);
|
||||
case "publish":
|
||||
case "enable":
|
||||
return handlePublish(parsed, runtime);
|
||||
case "save":
|
||||
case "update":
|
||||
return handleSave(parsed, runtime);
|
||||
case "patch":
|
||||
return handlePatch(parsed, runtime);
|
||||
case "history":
|
||||
case "snapshots":
|
||||
return handleHistory(parsed, runtime);
|
||||
case "logs":
|
||||
case "log":
|
||||
return handleLogs(parsed, runtime);
|
||||
case "job":
|
||||
case "execution":
|
||||
return handleJob(parsed, runtime);
|
||||
case "check":
|
||||
case "health":
|
||||
return handleCheck(parsed, runtime);
|
||||
case "analyze":
|
||||
case "analyse":
|
||||
return handleAnalyze(parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, check\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePatch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
const file = stringOption(parsed.options, ["file", "input", "from"]);
|
||||
const path = stringOption(parsed.options, ["path", "field"]);
|
||||
const rawValue = parsed.options.value;
|
||||
const output = stringOption(parsed.options, ["output", "output-file", "outputFile"]);
|
||||
const inPlace = booleanOption(parsed.options, ["in-place", "inPlace"]);
|
||||
if (!pipelineId || !file || !path || typeof rawValue !== "string" || (!output && !inPlace)) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use workflow patch <pipelineId> --file=<workflow.json> --path=<tasks.0.code> --value=<值> (--output=<patched.json>|--in-place) [--value-json]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
let source: unknown;
|
||||
try {
|
||||
source = JSON.parse(readFileSync(file, "utf8"));
|
||||
} catch (error) {
|
||||
throw new Error(`无法读取工作流 JSON 文件 [${file}]: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
const sourceWorkflow = WorkflowDetailSchema.parse(source);
|
||||
if (sourceWorkflow.id !== pipelineId) {
|
||||
throw new Error(`工作流 ID 不匹配:参数为 [${pipelineId}],文件中为 [${sourceWorkflow.id}]`);
|
||||
}
|
||||
|
||||
let value: unknown = rawValue;
|
||||
if (booleanOption(parsed.options, ["value-json", "valueJson"])) {
|
||||
try {
|
||||
value = JSON.parse(rawValue);
|
||||
} catch (error) {
|
||||
throw new Error(`--value-json 不是合法 JSON: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
const patched = applyWorkflowPathPatch(sourceWorkflow, path, value);
|
||||
const target = inPlace ? file : output!;
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"写入工作流草稿文件",
|
||||
`hose-use workflow patch ${pipelineId} --file=${file} --path=${path} --value='${rawValue}' ${inPlace ? "--in-place" : `--output=${target}`} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "写入工作流草稿文件", target, {
|
||||
pipelineId,
|
||||
path,
|
||||
value,
|
||||
tasksVersion: patched.tasksVersion,
|
||||
});
|
||||
}
|
||||
writeFileSync(target, `${JSON.stringify(patched, null, 2)}\n`, "utf8");
|
||||
const result = { success: true, pipelineId, path, output: target, tasksVersion: patched.tasksVersion };
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `✅ 已生成工作流草稿 [${target}],修改路径: ${path}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
const file = stringOption(parsed.options, ["file", "input", "from"]);
|
||||
if (!pipelineId || !file) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use workflow save <pipelineId> --file=<workflow.json> [--force-write]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
let draftWorkflow: unknown;
|
||||
try {
|
||||
draftWorkflow = JSON.parse(readFileSync(file, "utf8"));
|
||||
} catch (error) {
|
||||
throw new Error(`无法读取工作流 JSON 文件 [${file}]: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
|
||||
const parsedWorkflow = WorkflowDetailSchema.parse(draftWorkflow);
|
||||
if (parsedWorkflow.id !== pipelineId) {
|
||||
throw new Error(`工作流 ID 不匹配:参数为 [${pipelineId}],文件中为 [${parsedWorkflow.id}]`);
|
||||
}
|
||||
|
||||
const forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]);
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"保存工作流草稿到远端",
|
||||
`hose-use workflow save ${pipelineId} --file=${file} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "保存工作流草稿到远端", pipelineId, {
|
||||
file,
|
||||
tasksVersion: parsedWorkflow.tasksVersion,
|
||||
forceWrite,
|
||||
});
|
||||
}
|
||||
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const platformId = await resolveWorkflowPlatformId(parsed, clients, pipelineId);
|
||||
const piperClient = await createPiperClientForCorp(runtime.selectedCorp!, platformId);
|
||||
const remote = await api.getWorkflowDetail(piperClient, pipelineId);
|
||||
let state = createWorkflowDraft(parsedWorkflow);
|
||||
state = {
|
||||
...state,
|
||||
revision: 1,
|
||||
status: "dirty",
|
||||
dirtyPaths: ["*"],
|
||||
};
|
||||
|
||||
if (!forceWrite && hasWorkflowVersionConflict(state, remote)) {
|
||||
throw new Error(
|
||||
`工作流版本已变化,拒绝覆盖:远端 tasksVersion=${remote.tasksVersion}, 文件 tasksVersion=${parsedWorkflow.tasksVersion}。确认来源后使用 --force-write。`
|
||||
);
|
||||
}
|
||||
|
||||
state = beginWorkflowSave(state);
|
||||
try {
|
||||
const payload = state.workflow.inputs?.length
|
||||
? state.workflow
|
||||
: { ...state.workflow, inputs: [{ key: "$platformId", value: platformId }] };
|
||||
const saved = await api.updateWorkflow(piperClient, payload);
|
||||
state = commitWorkflowSave(state, saved);
|
||||
const result = {
|
||||
success: true,
|
||||
pipelineId,
|
||||
status: state.status,
|
||||
tasksVersion: saved.tasksVersion,
|
||||
updateTime: saved.updateTime,
|
||||
};
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: `✅ 工作流 [${pipelineId}] 草稿保存成功,tasksVersion=${saved.tasksVersion}。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (error) {
|
||||
state = failWorkflowSave(state, error);
|
||||
throw new Error(`工作流保存失败(${state.status}): ${state.error}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveWorkflowPlatformId(
|
||||
parsed: CliParsedArgs,
|
||||
clients: Awaited<ReturnType<typeof createClientsForCorp>>,
|
||||
pipelineId: string
|
||||
): Promise<string> {
|
||||
const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
||||
if (explicit) return explicit;
|
||||
const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 });
|
||||
const match = all.workflows.find((workflow) => workflow.id === pipelineId);
|
||||
if (!match?.platformId) {
|
||||
throw new Error(`无法确定工作流 [${pipelineId}] 所属自建应用,请使用 --platform-id=<platformId> 或 --app-id=<appId>`);
|
||||
}
|
||||
return match.platformId;
|
||||
}
|
||||
|
||||
async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow analyze <pipelineId>\n", exitCode: 1 };
|
||||
const { client, clients } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await api.getWorkflowDetail(client, pipelineId);
|
||||
const specIds = extractWorkflowSpecificationIds(detail);
|
||||
const specifications: Record<string, WorkflowFormSpecLike | undefined> = {};
|
||||
if (specIds.length > 0) {
|
||||
const corpId = runtime.selectedCorp!.corpId || runtime.selectedCorp!.id;
|
||||
await Promise.all(
|
||||
specIds.map(async (specId) => {
|
||||
try {
|
||||
const spec = await getFormSpecification(clients.ekbClient, corpId, specId);
|
||||
if (spec) specifications[specId] = spec;
|
||||
} catch {
|
||||
// Ignore specification fetch failure in offline or restricted environments
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
const result = analyzeWorkflow(detail, { specifications });
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const diagnosticRows = result.diagnostics.map((item) => [item.severity, item.code, item.path, item.message]);
|
||||
const dependencyRows = result.dependencies.map((item) => [item.path, item.taskType, item.references.join(", ")]);
|
||||
return { stdout: [
|
||||
`====== 工作流静态分析 (${detail.label || detail.id}) ======`,
|
||||
printKeyValue({
|
||||
"工作流 ID": detail.id,
|
||||
"状态": detail.state === 1 ? "🟢 启用 (state=1)" : "⚪ 停用/草稿 (state=0)",
|
||||
"根节点数": result.ast.length,
|
||||
"依赖节点数": result.dependencies.length,
|
||||
"诊断数": result.diagnostics.length,
|
||||
}),
|
||||
`\n依赖引用:\n${dependencyRows.length ? printTable(["节点路径", "类型", "引用"], dependencyRows) : "暂无代码引用"}`,
|
||||
`\n诊断:\n${diagnosticRows.length ? printTable(["级别", "代码", "节点路径", "说明"], diagnosticRows) : "未发现明显配置问题"}`, "",
|
||||
].join("\n"), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
async function handleHistory(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow history <pipelineId> [--page=1] [--page-size=10]\n", exitCode: 1 };
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize", "size"]) || 10;
|
||||
const result = await api.listWorkflowSnapshots(client, pipelineId, page, pageSize);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = result.items.map((snapshot, index) => [
|
||||
(page - 1) * pageSize + index + 1,
|
||||
snapshot.version,
|
||||
snapshot.id,
|
||||
snapshot.updateTime,
|
||||
snapshot.staffName || snapshot.staffId || "-",
|
||||
]);
|
||||
return {
|
||||
stdout: `====== 工作流版本历史 [${pipelineId}](共 ${result.totalItems} 个) ======\n${printTable(["#", "版本", "快照 ID", "更新时间", "操作者"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs <pipelineId> [--state=FAILED] [--has-error] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 };
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const rawResult = await api.listWorkflowLogs(client, pipelineId, {
|
||||
state: stringOption(parsed.options, ["state"]),
|
||||
page: numberOption(parsed.options, ["page"]),
|
||||
pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size"]),
|
||||
startTime: stringOption(parsed.options, ["start-time", "startTime"]),
|
||||
endTime: stringOption(parsed.options, ["end-time", "endTime"]),
|
||||
});
|
||||
const hasErrorFilter = booleanOption(parsed.options, ["has-error", "hasError", "errors"]);
|
||||
const filteredJobList = hasErrorFilter
|
||||
? rawResult.jobList.filter(
|
||||
(job) => job.hasError === true || job.errorTaskCount > 0 || job.state === "FAILED"
|
||||
)
|
||||
: rawResult.jobList;
|
||||
const result = hasErrorFilter
|
||||
? { ...rawResult, jobList: filteredJobList }
|
||||
: rawResult;
|
||||
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
|
||||
const rows = result.jobList.map((job, idx) => [
|
||||
idx + 1,
|
||||
job.id,
|
||||
job.state,
|
||||
job.successTaskCount,
|
||||
job.errorTaskCount,
|
||||
job.hasError || job.errorTaskCount > 0 ? "⚠️ 是 (true)" : "否 (false)",
|
||||
job.durationTime ?? "-",
|
||||
job.startTime || "-",
|
||||
]);
|
||||
const tableStr = rows.length
|
||||
? printTable(
|
||||
["#", "Job ID", "状态 (state)", "成功节点 (successTaskCount)", "失败节点 (errorTaskCount)", "有错误 (hasError)", "耗时(ms)", "开始时间"],
|
||||
rows
|
||||
)
|
||||
: "暂无匹配的运行记录";
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`====== 工作流运行日志 [${pipelineId}] ======`,
|
||||
printKeyValue({
|
||||
"执行次数": result.executeCount,
|
||||
"成功次数": result.successCount,
|
||||
"错误次数": result.errorCount,
|
||||
"日志条数": result.totalItems,
|
||||
"当前返回记录": result.jobList.length,
|
||||
}),
|
||||
"",
|
||||
tableStr,
|
||||
"\n提示: 运行 hose-use workflow job <jobId> [--failed] 下钻查看单次 Job 节点级报错与入参明细\n",
|
||||
].join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function createJobPiperClient(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<Awaited<ReturnType<typeof createPiperClientForCorp>>> {
|
||||
const corp = runtime.selectedCorp!;
|
||||
const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
||||
if (explicit) {
|
||||
return createPiperClientForCorp(corp, explicit);
|
||||
}
|
||||
const clients = await createClientsForCorp(corp);
|
||||
try {
|
||||
const corpId = corp.corpId || corp.id;
|
||||
const platforms = await api.listPlatforms(clients.ekbClient, corpId);
|
||||
const firstActive = platforms.find((p) => p.active) ?? platforms[0];
|
||||
if (firstActive?.id) {
|
||||
return await createPiperClientForCorp(corp, firstActive.id);
|
||||
}
|
||||
} catch {
|
||||
// Fall back to default easoClient
|
||||
}
|
||||
return clients.easoClient;
|
||||
}
|
||||
|
||||
async function enrichFailedExecutions(
|
||||
client: Awaited<ReturnType<typeof createPiperClientForCorp>>,
|
||||
jobId: string,
|
||||
items: WorkflowTaskExecution[]
|
||||
): Promise<WorkflowTaskExecution[]> {
|
||||
const parentCache = new Map<string, WorkflowTaskExecution[]>();
|
||||
const enriched: WorkflowTaskExecution[] = [];
|
||||
|
||||
for (const item of items) {
|
||||
if (item.parentId && (!item.currentLoopPath || !item.name || !item.form)) {
|
||||
let siblings = parentCache.get(item.parentId);
|
||||
if (!siblings) {
|
||||
try {
|
||||
const level = await api.getJobExecutionLevel(client, jobId, {
|
||||
parentId: item.parentId,
|
||||
page: 1,
|
||||
pageSize: 100,
|
||||
});
|
||||
siblings = level.items;
|
||||
} catch {
|
||||
siblings = [];
|
||||
}
|
||||
parentCache.set(item.parentId, siblings);
|
||||
}
|
||||
const matched = siblings.find((s) => s.id === item.id);
|
||||
if (matched) {
|
||||
const itemInputs = item.inputs;
|
||||
const matchedInputs = matched.inputs;
|
||||
const hasItemInputs = Array.isArray(itemInputs)
|
||||
? itemInputs.length > 0
|
||||
: Boolean(itemInputs && typeof itemInputs === "object" && Object.keys(itemInputs as Record<string, unknown>).length > 0);
|
||||
const itemOutputs = item.outputs;
|
||||
const matchedOutputs = matched.outputs;
|
||||
const hasItemOutputs = Boolean(
|
||||
itemOutputs && typeof itemOutputs === "object" && Object.keys(itemOutputs as Record<string, unknown>).length > 0
|
||||
);
|
||||
enriched.push({
|
||||
...matched,
|
||||
...item,
|
||||
name: item.name || matched.name,
|
||||
label: item.label || matched.label,
|
||||
displayName: item.displayName || matched.displayName,
|
||||
type: item.type || matched.type,
|
||||
status: item.status || matched.status,
|
||||
currentLoopPath: item.currentLoopPath || matched.currentLoopPath,
|
||||
levelIndex: item.levelIndex?.length ? item.levelIndex : matched.levelIndex,
|
||||
form: item.form ?? matched.form,
|
||||
details: item.details ?? matched.details,
|
||||
inputs: hasItemInputs ? itemInputs : matchedInputs,
|
||||
outputs: hasItemOutputs ? itemOutputs : matchedOutputs,
|
||||
error: item.error ?? matched.error,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
}
|
||||
enriched.push(item);
|
||||
}
|
||||
return enriched;
|
||||
}
|
||||
|
||||
async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const jobId = parsed.args[0] || stringOption(parsed.options, ["id", "job-id", "jobId"]);
|
||||
if (!jobId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use workflow job <jobId> [--failed] [--parent=<executionId>] [--logs=<executionId>]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const client = await createJobPiperClient(parsed, runtime);
|
||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize", "size"]) || 100;
|
||||
const logsExecutionId = stringOption(parsed.options, ["logs", "log", "execution-logs"]);
|
||||
const parentExecutionId = stringOption(parsed.options, ["parent", "parent-id", "parentId"]);
|
||||
const onlyFailed = booleanOption(parsed.options, ["failed", "fail", "errors"]);
|
||||
|
||||
// 1. --logs=<executionId>
|
||||
if (logsExecutionId) {
|
||||
const logs = await api.getExecutionLogs(client, logsExecutionId);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ jobId, executionId: logsExecutionId, logs }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
const rows = logs.map((log, i) => [
|
||||
i + 1,
|
||||
String(log.id ?? "-"),
|
||||
String(log.createAt ?? (log as Record<string, unknown>).createTime ?? (log as Record<string, unknown>).timestamp ?? "-"),
|
||||
String(log.level || "INFO"),
|
||||
String(log.message || JSON.stringify(log)),
|
||||
]);
|
||||
return {
|
||||
stdout: [
|
||||
`====== 节点执行日志 (Job: ${jobId} | Execution: ${logsExecutionId}) ======`,
|
||||
rows.length ? printTable(["#", "日志 ID", "时间", "级别", "内容"], rows) : "该节点暂无输出日志",
|
||||
"",
|
||||
].join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. --parent=<executionId>
|
||||
if (parentExecutionId) {
|
||||
const levelPage = await api.getJobExecutionLevel(client, jobId, {
|
||||
parentId: parentExecutionId,
|
||||
page,
|
||||
pageSize,
|
||||
});
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
jobId,
|
||||
parentId: parentExecutionId,
|
||||
...levelPage,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = levelPage.items.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.id,
|
||||
item.name || "-",
|
||||
item.label || item.displayName || "-",
|
||||
item.type || "-",
|
||||
item.status || "-",
|
||||
item.currentLoopPath || "-",
|
||||
item.error?.message || "-",
|
||||
]);
|
||||
const extraDetails: string[] = [];
|
||||
for (const item of levelPage.items) {
|
||||
if (item.form !== undefined || item.error?.message) {
|
||||
extraDetails.push(
|
||||
`\n── 节点明细 [${item.id}] (${item.name || "-"} | loop=${item.currentLoopPath || "-"} | status=${item.status}) ──`
|
||||
);
|
||||
if (item.error?.message) {
|
||||
extraDetails.push(` 错误原因: ${item.error.message}`);
|
||||
}
|
||||
if (item.form !== undefined) {
|
||||
extraDetails.push(` 传入表单 (form): ${JSON.stringify(item.form)}`);
|
||||
}
|
||||
if (item.details !== undefined) {
|
||||
extraDetails.push(` 明细数据 (details): ${JSON.stringify(item.details)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`====== 子节点执行层级明细 (Job: ${jobId} | Parent: ${parentExecutionId} | 共 ${levelPage.totalItems} 项) ======`,
|
||||
rows.length
|
||||
? printTable(
|
||||
["#", "Execution ID", "节点标识 (name)", "节点名称", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因"],
|
||||
rows
|
||||
)
|
||||
: "暂无子节点执行记录",
|
||||
...extraDetails,
|
||||
"",
|
||||
].join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 3. --failed
|
||||
if (onlyFailed) {
|
||||
const [job, failedPage] = await Promise.all([
|
||||
api.getJob(client, jobId).catch(() => undefined),
|
||||
api.getJobFailedExecutions(client, jobId),
|
||||
]);
|
||||
const enrichedItems = await enrichFailedExecutions(client, jobId, failedPage.items);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
jobId,
|
||||
job: job ?? null,
|
||||
totalItems: failedPage.totalItems,
|
||||
items: enrichedItems,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = enrichedItems.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.id,
|
||||
item.parentId || "-",
|
||||
item.name || "-",
|
||||
item.type || "-",
|
||||
item.status || "-",
|
||||
item.currentLoopPath || "-",
|
||||
item.error?.message || "-",
|
||||
]);
|
||||
const formSummaries: string[] = [];
|
||||
for (const item of enrichedItems) {
|
||||
if (item.error?.message || item.form !== undefined) {
|
||||
formSummaries.push(
|
||||
`\n── ⚠️ 异常节点 [${item.id}] (${item.name || "-"} | status=${item.status} | loop=${item.currentLoopPath || "-"}) ──`
|
||||
);
|
||||
if (item.error?.message) {
|
||||
formSummaries.push(` 错误详情: ${item.error.message}`);
|
||||
}
|
||||
if (item.form !== undefined) {
|
||||
formSummaries.push(` 表单入参 (form): ${JSON.stringify(item.form)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`====== Job 异常/跳过执行节点明细 (Job: ${jobId}) ======`,
|
||||
job
|
||||
? printKeyValue({
|
||||
"Job ID": job.id,
|
||||
"工作流 ID": job.pipelineId,
|
||||
"Job 状态": job.state ?? job.status,
|
||||
"开始时间": job.startTime || "-",
|
||||
"耗时(ms)": String(job.durationTime ?? "-"),
|
||||
})
|
||||
: "",
|
||||
"",
|
||||
rows.length
|
||||
? printTable(
|
||||
["#", "Execution ID", "Parent ID", "节点标识 (name)", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因 (error.message)"],
|
||||
rows
|
||||
)
|
||||
: "未发现异常或报错跳过的执行节点",
|
||||
...formSummaries,
|
||||
"",
|
||||
].filter(Boolean).join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 4. Default mode: Job overview + top-level tree + failed executions
|
||||
const [job, tree, failedPage] = await Promise.all([
|
||||
api.getJob(client, jobId),
|
||||
api.getJobExecutionTree(client, jobId),
|
||||
api.getJobFailedExecutions(client, jobId).catch(() => ({
|
||||
number: 1,
|
||||
size: 100,
|
||||
totalPages: 0,
|
||||
totalItems: 0,
|
||||
items: [] as WorkflowTaskExecution[],
|
||||
})),
|
||||
]);
|
||||
const failedExecutions = await enrichFailedExecutions(client, jobId, failedPage.items);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
jobId,
|
||||
job,
|
||||
executionTree: tree,
|
||||
failedExecutions,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const treeRows = tree.map((node, idx) => [
|
||||
idx + 1,
|
||||
node.id,
|
||||
node.name || "-",
|
||||
node.label || node.displayName || "-",
|
||||
node.type || "-",
|
||||
node.status || "-",
|
||||
String((node as Record<string, unknown>).durationTime ?? node.executionTime ?? "-"),
|
||||
node.error?.message || "-",
|
||||
]);
|
||||
|
||||
const failedRows = failedExecutions.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.id,
|
||||
item.parentId || "-",
|
||||
item.name || "-",
|
||||
item.type || "-",
|
||||
item.status || "-",
|
||||
item.currentLoopPath || "-",
|
||||
item.error?.message || "-",
|
||||
]);
|
||||
|
||||
const outLines = [
|
||||
`====== 工作流 Job 执行详情 [${job.id}] ======`,
|
||||
printKeyValue({
|
||||
"Job ID": job.id,
|
||||
"工作流 ID (pipelineId)": job.pipelineId,
|
||||
"Job 状态 (state)": job.state ?? job.status,
|
||||
"开始时间": job.startTime || "-",
|
||||
"结束时间": job.endTime || "-",
|
||||
"耗时(ms)": String(job.durationTime ?? "-"),
|
||||
"顶层节点数": tree.length,
|
||||
"异常/跳过节点数": failedExecutions.length,
|
||||
}),
|
||||
"",
|
||||
"── 顶层节点执行树 ──",
|
||||
treeRows.length
|
||||
? printTable(
|
||||
["#", "Execution ID", "节点标识 (name)", "节点名称", "类型 (type)", "状态 (status)", "耗时(ms)", "错误信息"],
|
||||
treeRows
|
||||
)
|
||||
: "暂无顶层节点执行记录",
|
||||
];
|
||||
|
||||
if (failedRows.length > 0) {
|
||||
outLines.push("");
|
||||
outLines.push("── ⚠️ 失败/报错跳过节点明细 (含循环子项) ──");
|
||||
outLines.push(
|
||||
printTable(
|
||||
["#", "Execution ID", "Parent ID", "节点标识 (name)", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因 (error.message)"],
|
||||
failedRows
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleCheck(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const result = await listAllWorkflows(clients, { page: 1, pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size"]) || 100 });
|
||||
const observedAt = Date.now();
|
||||
const logResults = await Promise.all(result.workflows.map(async (workflow) => {
|
||||
try {
|
||||
const piperClient = await createPiperClientForCorp(runtime.selectedCorp!, workflow.platformId);
|
||||
const log = await api.listWorkflowLogs(piperClient, workflow.id, { page: 1, pageSize: 1 });
|
||||
return { workflow, errorCount: log.errorCount };
|
||||
} catch (error) {
|
||||
return { workflow, errorCount: workflow.errorCount, error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
}));
|
||||
const logErrors = logResults.filter((item): item is typeof item & { error: string } => Boolean(item.error)).map((item) => ({ platformId: item.workflow.platformId, platformName: item.workflow.platformName, error: item.error }));
|
||||
const activeAlerts = logResults
|
||||
.filter(({ errorCount }) => errorCount > 0)
|
||||
.map(({ workflow, errorCount }) => ({
|
||||
id: `${runtime.selectedCorp!.id}:${workflow.platformId}:${workflow.id}`,
|
||||
pipelineId: workflow.id,
|
||||
platformId: workflow.platformId,
|
||||
pipelineName: workflow.pipelineName,
|
||||
errorCount,
|
||||
state: workflow.state,
|
||||
observedAt,
|
||||
}));
|
||||
const stateFile = stringOption(parsed.options, ["state-file", "stateFile"]) || join(WORKFLOW_STATE_DIR, `workflow-alerts-${runtime.selectedCorp!.id}.json`);
|
||||
const check = new WorkflowAlertStore(stateFile).observe(activeAlerts);
|
||||
const output = { corpId: runtime.selectedCorp!.id, observedAt, stateFile, activeAlerts: check.activeAlerts, newAlerts: check.newAlerts, scanErrors: [...result.errors, ...logErrors] };
|
||||
if (runtime.jsonMode) return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: booleanOption(parsed.options, ["fail-on-alert", "failOnAlert"]) && check.newAlerts.length > 0 ? 2 : 0 };
|
||||
const rows = check.activeAlerts.map((alert) => [alert.pipelineId, alert.pipelineName || "-", alert.errorCount, alert.state === 1 ? "启用" : "停用", check.newAlerts.some((item) => item.id === alert.id) ? "🔔 新提醒" : "已记录"]);
|
||||
const warning = check.newAlerts.length ? `\n🔔 新错误管道提醒 ${check.newAlerts.length} 条` : "\n暂无新的错误管道提醒";
|
||||
const scanErrorCount = result.errors.length + logErrors.length;
|
||||
const scanWarning = scanErrorCount ? `\n⚠️ 工作流扫描失败 ${scanErrorCount} 个` : "";
|
||||
return { stdout: `====== 工作流健康检查 [${runtime.selectedCorp!.name}] ======\n${rows.length ? printTable(["工作流 ID", "名称", "错误次数", "状态", "提醒"], rows) : "未发现错误管道"}${warning}${scanWarning}\n状态文件: ${stateFile}\n`, stderr: "", exitCode: booleanOption(parsed.options, ["fail-on-alert", "failOnAlert"]) && check.newAlerts.length > 0 ? 2 : 0 };
|
||||
}
|
||||
|
||||
async function handlePublish(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow publish <pipelineId>\n", exitCode: 1 };
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"发布并启用工作流",
|
||||
`hose-use workflow publish ${pipelineId} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "发布并启用工作流", pipelineId, { state: 1 });
|
||||
}
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const result = await api.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 };
|
||||
}
|
||||
|
||||
async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||
const pageSize = numberOption(parsed.options, ["pageSize", "size"]) || 50;
|
||||
const filterPlatformId = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
||||
|
||||
const rawResult = await listAllWorkflows(clients, { page, pageSize });
|
||||
const workflows = filterPlatformId
|
||||
? rawResult.workflows.filter(
|
||||
(wf) => wf.platformId === filterPlatformId || wf.platformName === filterPlatformId
|
||||
)
|
||||
: rawResult.workflows;
|
||||
const result = filterPlatformId
|
||||
? { ...rawResult, workflows, totalWorkflows: workflows.length }
|
||||
: rawResult;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
if (result.workflows.length === 0) {
|
||||
return {
|
||||
stdout: `企业 [${runtime.selectedCorp!.name}] 下暂无工作流\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = result.workflows.map((wf, i) => [
|
||||
i + 1,
|
||||
wf.id,
|
||||
wf.pipelineName,
|
||||
wf.platformName || wf.platformId || "-",
|
||||
wf.state === 1 ? "🟢 启用" : "⚪ 停用",
|
||||
wf.tasks?.length ?? "-",
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
["#", "工作流 ID", "工作流名称", "所属自建应用", "状态", "节点数"],
|
||||
rows
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: `====== [${runtime.selectedCorp!.name}] 工作流列表 (共 ${result.workflows.length} 条) ======\n${table}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) {
|
||||
return { stdout: "", stderr: "用法: hose-use workflow get <pipelineId>\n", exitCode: 1 };
|
||||
}
|
||||
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await api.getWorkflowDetail(client, pipelineId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const summary = printKeyValue({
|
||||
"工作流 ID": detail.id,
|
||||
"工作流名称": detail.label,
|
||||
"状态": detail.state === 1 ? "🟢 启用" : "⚪ 停用",
|
||||
"版本号": detail.version || "-",
|
||||
"节点总数": detail.tasks?.length ?? 0,
|
||||
});
|
||||
|
||||
let taskList = "";
|
||||
if (detail.tasks && detail.tasks.length > 0) {
|
||||
const taskRows = detail.tasks.map((t, i) => [
|
||||
i + 1,
|
||||
t.name || "-",
|
||||
t.label || "-",
|
||||
t.type,
|
||||
t.groupName || "-",
|
||||
]);
|
||||
taskList = `\n 节点结构:\n` + printTable(["#", "节点标识", "节点名称", "类型", "分组"], taskRows);
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `====== 工作流详情 ======\n${summary}\n${taskList}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function createWorkflowDetailClient(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime,
|
||||
pipelineId: string,
|
||||
): Promise<{
|
||||
client: Awaited<ReturnType<typeof createPiperClientForCorp>>;
|
||||
clients: Awaited<ReturnType<typeof createClientsForCorp>>;
|
||||
}> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
||||
let platformId = explicit;
|
||||
if (!platformId) {
|
||||
const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 });
|
||||
platformId = all.workflows.find((workflow) => workflow.id === pipelineId)?.platformId;
|
||||
}
|
||||
return {
|
||||
client: platformId ? await createPiperClientForCorp(runtime.selectedCorp!, platformId) : clients.easoClient,
|
||||
clients,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleFind(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const taskType = stringOption(parsed.options, ["task", "taskType", "type"]) || parsed.args[0];
|
||||
if (!taskType) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use workflow find --task=<节点类型> (如 code-js2, http, condition)\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const includeDetail = booleanOption(parsed.options, ["includeDetail", "detail"]);
|
||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||
const pageSize = numberOption(parsed.options, ["pageSize", "size"]) || 50;
|
||||
|
||||
const result = await findWorkflowsByTaskType(clients, taskType, {
|
||||
page,
|
||||
pageSize,
|
||||
includeDetail,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
if (result.workflows.length === 0) {
|
||||
return {
|
||||
stdout: `未找到包含节点类型 [${taskType}] 的工作流\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = result.workflows.map((wf, i) => [
|
||||
i + 1,
|
||||
wf.id,
|
||||
wf.pipelineName,
|
||||
wf.platformName || wf.platformId || "-",
|
||||
wf.state === 1 ? "🟢 启用" : "⚪ 停用",
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
["#", "工作流 ID", "工作流名称", "所属自建应用", "状态"],
|
||||
rows
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: `====== 匹配节点类型 [${taskType}] 的工作流 (共 ${result.workflows.length} 条) ======\n${table}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleToggle(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
const stateArg = stringOption(parsed.options, ["state", "s"]);
|
||||
|
||||
if (!pipelineId || stateArg === undefined) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use workflow toggle <pipelineId> --state=<1|0> (1启用, 0停用)\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const state = (stateArg === "1" || stateArg === "true" ? 1 : 0) as 0 | 1;
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"切换工作流状态",
|
||||
`hose-use workflow toggle ${pipelineId} --state=${state} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "切换工作流状态", pipelineId, { state });
|
||||
}
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const result = await api.toggleWorkflow(client, pipelineId, state);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 工作流 ${pipelineId} 状态已更新为: ${state === 1 ? "🟢 启用" : "⚪ 停用"}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { getWorkflowDetail } from "../../../domains/platform/services.js";
|
||||
import {
|
||||
analyzeWorkflow,
|
||||
extractWorkflowSpecificationIds,
|
||||
type WorkflowFormSpecLike,
|
||||
} from "../../../domains/platform/analysis.js";
|
||||
import { getFormSpecification } from "../../../domains/bill/tools.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
|
||||
export async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow analyze <pipelineId>\n", exitCode: 1 };
|
||||
const { client, clients } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
const specIds = extractWorkflowSpecificationIds(detail);
|
||||
const specifications: Record<string, WorkflowFormSpecLike | undefined> = {};
|
||||
if (specIds.length > 0) {
|
||||
const corpId = runtime.selectedCorp!.corpId || runtime.selectedCorp!.id;
|
||||
await Promise.all(
|
||||
specIds.map(async (specId) => {
|
||||
try {
|
||||
const spec = await getFormSpecification(clients.ekbClient, corpId, specId);
|
||||
if (spec) specifications[specId] = spec;
|
||||
} catch {
|
||||
// Ignore specification fetch failure in offline or restricted environments
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
const result = analyzeWorkflow(detail, { specifications });
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const diagnosticRows = result.diagnostics.map((item) => [item.severity, item.code, item.path, item.message]);
|
||||
const dependencyRows = result.dependencies.map((item) => [item.path, item.taskType, item.references.join(", ")]);
|
||||
return { stdout: [
|
||||
`====== 工作流静态分析 (${detail.label || detail.id}) ======`,
|
||||
printKeyValue({
|
||||
"工作流 ID": detail.id,
|
||||
"状态": detail.state === 1 ? "🟢 启用 (state=1)" : "⚪ 停用/草稿 (state=0)",
|
||||
"根节点数": result.ast.length,
|
||||
"依赖节点数": result.dependencies.length,
|
||||
"诊断数": result.diagnostics.length,
|
||||
}),
|
||||
`\n依赖引用:\n${dependencyRows.length ? printTable(["节点路径", "类型", "引用"], dependencyRows) : "暂无代码引用"}`,
|
||||
`\n诊断:\n${diagnosticRows.length ? printTable(["级别", "代码", "节点路径", "说明"], diagnosticRows) : "未发现明显配置问题"}`, "",
|
||||
].join("\n"), stderr: "", exitCode: 0 };
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { listAllWorkflows, listWorkflowLogs } from "../../../domains/platform/services.js";
|
||||
import { WorkflowAlertStore } from "../../../domains/platform/workflow-alert-store.js";
|
||||
import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
||||
import { printJson, printTable } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
|
||||
export async function handleCheck(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const result = await listAllWorkflows(clients, { page: 1, pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size"]) || 100 });
|
||||
const observedAt = Date.now();
|
||||
const logResults = await Promise.all(result.workflows.map(async (workflow) => {
|
||||
try {
|
||||
const piperClient = await createPiperClientForCorp(runtime.selectedCorp!, workflow.platformId);
|
||||
const log = await listWorkflowLogs(piperClient, workflow.id, { page: 1, pageSize: 1 });
|
||||
return { workflow, errorCount: log.errorCount };
|
||||
} catch (error) {
|
||||
return { workflow, errorCount: workflow.errorCount, error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
}));
|
||||
const logErrors = logResults.filter((item): item is typeof item & { error: string } => Boolean(item.error)).map((item) => ({ platformId: item.workflow.platformId, platformName: item.workflow.platformName, error: item.error }));
|
||||
const activeAlerts = logResults
|
||||
.filter(({ errorCount }) => errorCount > 0)
|
||||
.map(({ workflow, errorCount }) => ({
|
||||
id: `${runtime.selectedCorp!.id}:${workflow.platformId}:${workflow.id}`,
|
||||
pipelineId: workflow.id,
|
||||
platformId: workflow.platformId,
|
||||
pipelineName: workflow.pipelineName,
|
||||
errorCount,
|
||||
state: workflow.state,
|
||||
observedAt,
|
||||
}));
|
||||
const explicitStateFile = stringOption(parsed.options, ["state-file", "stateFile"]);
|
||||
const stateFile = explicitStateFile || `sqlite:workflow_error_alerts:${runtime.selectedCorp!.id}`;
|
||||
const check = new WorkflowAlertStore(explicitStateFile || `corp:${runtime.selectedCorp!.id}`).observe(activeAlerts);
|
||||
const output = { corpId: runtime.selectedCorp!.id, observedAt, stateFile, activeAlerts: check.activeAlerts, newAlerts: check.newAlerts, scanErrors: [...result.errors, ...logErrors] };
|
||||
if (runtime.jsonMode) return { stdout: printJson(output, runtime.outputOptions), stderr: "", exitCode: booleanOption(parsed.options, ["fail-on-alert", "failOnAlert"]) && check.newAlerts.length > 0 ? 2 : 0 };
|
||||
const rows = check.activeAlerts.map((alert) => [alert.pipelineId, alert.pipelineName || "-", alert.errorCount, alert.state === 1 ? "启用" : "停用", check.newAlerts.some((item) => item.id === alert.id) ? "🔔 新提醒" : "已记录"]);
|
||||
const warning = check.newAlerts.length ? `\n🔔 新错误管道提醒 ${check.newAlerts.length} 条` : "\n暂无新的错误管道提醒";
|
||||
const scanErrorCount = result.errors.length + logErrors.length;
|
||||
const scanWarning = scanErrorCount ? `\n⚠️ 工作流扫描失败 ${scanErrorCount} 个` : "";
|
||||
return { stdout: `====== 工作流健康检查 [${runtime.selectedCorp!.name}] ======\n${rows.length ? printTable(["工作流 ID", "名称", "错误次数", "状态", "提醒"], rows) : "未发现错误管道"}${warning}${scanWarning}\n状态存储: ${stateFile}\n`, stderr: "", exitCode: booleanOption(parsed.options, ["fail-on-alert", "failOnAlert"]) && check.newAlerts.length > 0 ? 2 : 0 };
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { getWorkflowDetail, listAllWorkflows, updateWorkflow } from "../../../domains/platform/services.js";
|
||||
import { WorkflowDetailSchema } from "../../../domains/platform/types.js";
|
||||
import {
|
||||
applyWorkflowPathPatch,
|
||||
beginWorkflowSave,
|
||||
commitWorkflowSave,
|
||||
createWorkflowDraft,
|
||||
failWorkflowSave,
|
||||
hasWorkflowVersionConflict,
|
||||
} from "../../../domains/platform/workflow-state.js";
|
||||
import { stringOption, booleanOption } from "../../parser.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { PLATFORM_ID_OPTION_KEYS } from "./shared.js";
|
||||
|
||||
export async function handlePatch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
const file = stringOption(parsed.options, ["file", "input", "from"]);
|
||||
const path = stringOption(parsed.options, ["path", "field"]);
|
||||
const rawValue = parsed.options.value;
|
||||
const output = stringOption(parsed.options, ["output", "output-file", "outputFile"]);
|
||||
const inPlace = booleanOption(parsed.options, ["in-place", "inPlace"]);
|
||||
if (!pipelineId || !file || !path || typeof rawValue !== "string" || (!output && !inPlace)) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use workflow patch <pipelineId> --file=<workflow.json> --path=<tasks.0.code> --value=<值> (--output=<patched.json>|--in-place) [--value-json]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
let source: unknown;
|
||||
try {
|
||||
source = JSON.parse(readFileSync(file, "utf8"));
|
||||
} catch (error) {
|
||||
throw new Error(`无法读取工作流 JSON 文件 [${file}]: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
const sourceWorkflow = WorkflowDetailSchema.parse(source);
|
||||
if (sourceWorkflow.id !== pipelineId) {
|
||||
throw new Error(`工作流 ID 不匹配:参数为 [${pipelineId}],文件中为 [${sourceWorkflow.id}]`);
|
||||
}
|
||||
|
||||
let value: unknown = rawValue;
|
||||
if (booleanOption(parsed.options, ["value-json", "valueJson"])) {
|
||||
try {
|
||||
value = JSON.parse(rawValue);
|
||||
} catch (error) {
|
||||
throw new Error(`--value-json 不是合法 JSON: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
const patched = applyWorkflowPathPatch(sourceWorkflow, path, value);
|
||||
const target = inPlace ? file : output!;
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"写入工作流草稿文件",
|
||||
`hose-use workflow patch ${pipelineId} --file=${file} --path=${path} --value='${rawValue}' ${inPlace ? "--in-place" : `--output=${target}`} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "写入工作流草稿文件", target, {
|
||||
pipelineId,
|
||||
path,
|
||||
value,
|
||||
tasksVersion: patched.tasksVersion,
|
||||
});
|
||||
}
|
||||
writeFileSync(target, `${JSON.stringify(patched, null, 2)}\n`, "utf8");
|
||||
const result = { success: true, pipelineId, path, output: target, tasksVersion: patched.tasksVersion };
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `✅ 已生成工作流草稿 [${target}],修改路径: ${path}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
const file = stringOption(parsed.options, ["file", "input", "from"]);
|
||||
if (!pipelineId || !file) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use workflow save <pipelineId> --file=<workflow.json> [--force-write]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
let draftWorkflow: unknown;
|
||||
try {
|
||||
draftWorkflow = JSON.parse(readFileSync(file, "utf8"));
|
||||
} catch (error) {
|
||||
throw new Error(`无法读取工作流 JSON 文件 [${file}]: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
|
||||
const parsedWorkflow = WorkflowDetailSchema.parse(draftWorkflow);
|
||||
if (parsedWorkflow.id !== pipelineId) {
|
||||
throw new Error(`工作流 ID 不匹配:参数为 [${pipelineId}],文件中为 [${parsedWorkflow.id}]`);
|
||||
}
|
||||
|
||||
const forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]);
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"保存工作流草稿到远端",
|
||||
`hose-use workflow save ${pipelineId} --file=${file} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "保存工作流草稿到远端", pipelineId, {
|
||||
file,
|
||||
tasksVersion: parsedWorkflow.tasksVersion,
|
||||
forceWrite,
|
||||
});
|
||||
}
|
||||
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const platformId = await resolveWorkflowPlatformId(parsed, clients, pipelineId);
|
||||
const piperClient = await createPiperClientForCorp(runtime.selectedCorp!, platformId);
|
||||
const remote = await getWorkflowDetail(piperClient, pipelineId);
|
||||
let state = createWorkflowDraft(parsedWorkflow);
|
||||
state = {
|
||||
...state,
|
||||
revision: 1,
|
||||
status: "dirty",
|
||||
dirtyPaths: ["*"],
|
||||
};
|
||||
|
||||
if (!forceWrite && hasWorkflowVersionConflict(state, remote)) {
|
||||
throw new Error(
|
||||
`工作流版本已变化,拒绝覆盖:远端 tasksVersion=${remote.tasksVersion}, 文件 tasksVersion=${parsedWorkflow.tasksVersion}。确认来源后使用 --force-write。`
|
||||
);
|
||||
}
|
||||
|
||||
state = beginWorkflowSave(state);
|
||||
try {
|
||||
const payload = state.workflow.inputs?.length
|
||||
? state.workflow
|
||||
: { ...state.workflow, inputs: [{ key: "$platformId", value: platformId }] };
|
||||
const saved = await updateWorkflow(piperClient, payload);
|
||||
state = commitWorkflowSave(state, saved);
|
||||
const result = {
|
||||
success: true,
|
||||
pipelineId,
|
||||
status: state.status,
|
||||
tasksVersion: saved.tasksVersion,
|
||||
updateTime: saved.updateTime,
|
||||
};
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: `✅ 工作流 [${pipelineId}] 草稿保存成功,tasksVersion=${saved.tasksVersion}。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} catch (error) {
|
||||
state = failWorkflowSave(state, error);
|
||||
throw new Error(`工作流保存失败(${state.status}): ${state.error}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveWorkflowPlatformId(
|
||||
parsed: CliParsedArgs,
|
||||
clients: Awaited<ReturnType<typeof createClientsForCorp>>,
|
||||
pipelineId: string
|
||||
): Promise<string> {
|
||||
const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
||||
if (explicit) return explicit;
|
||||
const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 });
|
||||
const match = all.workflows.find((workflow) => workflow.id === pipelineId);
|
||||
if (!match?.platformId) {
|
||||
throw new Error(`无法确定工作流 [${pipelineId}] 所属自建应用,请使用 --platform-id=<platformId> 或 --app-id=<appId>`);
|
||||
}
|
||||
return match.platformId;
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { listWorkflowLogs, listWorkflowSnapshots } from "../../../domains/platform/services.js";
|
||||
import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
|
||||
export async function handleHistory(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow history <pipelineId> [--page=1] [--page-size=10]\n", exitCode: 1 };
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize", "size"]) || 10;
|
||||
const result = await listWorkflowSnapshots(client, pipelineId, page, pageSize);
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = result.items.map((snapshot, index) => [
|
||||
(page - 1) * pageSize + index + 1,
|
||||
snapshot.version,
|
||||
snapshot.id,
|
||||
snapshot.updateTime,
|
||||
snapshot.staffName || snapshot.staffId || "-",
|
||||
]);
|
||||
return {
|
||||
stdout: `====== 工作流版本历史 [${pipelineId}](共 ${result.totalItems} 个) ======\n${printTable(["#", "版本", "快照 ID", "更新时间", "操作者"], rows)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs <pipelineId> [--state=FAILED] [--has-error] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 };
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const rawResult = await listWorkflowLogs(client, pipelineId, {
|
||||
state: stringOption(parsed.options, ["state"]),
|
||||
page: numberOption(parsed.options, ["page"]),
|
||||
pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size"]),
|
||||
startTime: stringOption(parsed.options, ["start-time", "startTime"]),
|
||||
endTime: stringOption(parsed.options, ["end-time", "endTime"]),
|
||||
});
|
||||
const hasErrorFilter = booleanOption(parsed.options, ["has-error", "hasError", "errors"]);
|
||||
const filteredJobList = hasErrorFilter
|
||||
? rawResult.jobList.filter(
|
||||
(job) => job.hasError === true || job.errorTaskCount > 0 || job.state === "FAILED"
|
||||
)
|
||||
: rawResult.jobList;
|
||||
const result = hasErrorFilter
|
||||
? { ...rawResult, jobList: filteredJobList }
|
||||
: rawResult;
|
||||
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
|
||||
const rows = result.jobList.map((job, idx) => [
|
||||
idx + 1,
|
||||
job.id,
|
||||
job.state,
|
||||
job.successTaskCount,
|
||||
job.errorTaskCount,
|
||||
job.hasError || job.errorTaskCount > 0 ? "⚠️ 是 (true)" : "否 (false)",
|
||||
job.durationTime ?? "-",
|
||||
job.startTime || "-",
|
||||
]);
|
||||
const tableStr = rows.length
|
||||
? printTable(
|
||||
["#", "Job ID", "状态 (state)", "成功节点 (successTaskCount)", "失败节点 (errorTaskCount)", "有错误 (hasError)", "耗时(ms)", "开始时间"],
|
||||
rows
|
||||
)
|
||||
: "暂无匹配的运行记录";
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`====== 工作流运行日志 [${pipelineId}] ======`,
|
||||
printKeyValue({
|
||||
"执行次数": result.executeCount,
|
||||
"成功次数": result.successCount,
|
||||
"错误次数": result.errorCount,
|
||||
"日志条数": result.totalItems,
|
||||
"当前返回记录": result.jobList.length,
|
||||
}),
|
||||
"",
|
||||
tableStr,
|
||||
"\n提示: 运行 hose-use workflow job <jobId> [--failed] 下钻查看单次 Job 节点级报错与入参明细\n",
|
||||
].join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { handleList, handleGet, handleFind } from "./list.js";
|
||||
import { handleToggle, handlePublish } from "./lifecycle.js";
|
||||
import { handlePatch, handleSave } from "./draft.js";
|
||||
import { handleHistory, handleLogs } from "./history.js";
|
||||
import { handleJob } from "./job.js";
|
||||
import { handleCheck } from "./check.js";
|
||||
import { handleAnalyze } from "./analyze.js";
|
||||
|
||||
export async function handleWorkflowCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<CliResult> {
|
||||
const currentCorp = runtime.selectedCorp;
|
||||
if (!currentCorp) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const action = parsed.action || "list";
|
||||
|
||||
switch (action) {
|
||||
case "list":
|
||||
case "list-all":
|
||||
case "ls":
|
||||
return handleList(parsed, runtime);
|
||||
case "get":
|
||||
case "detail":
|
||||
case "info":
|
||||
return handleGet(parsed, runtime);
|
||||
case "find":
|
||||
case "search":
|
||||
return handleFind(parsed, runtime);
|
||||
case "toggle":
|
||||
return handleToggle(parsed, runtime);
|
||||
case "publish":
|
||||
case "enable":
|
||||
return handlePublish(parsed, runtime);
|
||||
case "save":
|
||||
case "update":
|
||||
return handleSave(parsed, runtime);
|
||||
case "patch":
|
||||
return handlePatch(parsed, runtime);
|
||||
case "history":
|
||||
case "snapshots":
|
||||
return handleHistory(parsed, runtime);
|
||||
case "logs":
|
||||
case "log":
|
||||
return handleLogs(parsed, runtime);
|
||||
case "job":
|
||||
case "execution":
|
||||
return handleJob(parsed, runtime);
|
||||
case "check":
|
||||
case "health":
|
||||
return handleCheck(parsed, runtime);
|
||||
case "analyze":
|
||||
case "analyse":
|
||||
return handleAnalyze(parsed, runtime);
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, check\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
import {
|
||||
getExecutionLogs,
|
||||
getJob,
|
||||
getJobExecutionLevel,
|
||||
getJobExecutionTree,
|
||||
getJobFailedExecutions,
|
||||
listPlatforms,
|
||||
} from "../../../domains/platform/services.js";
|
||||
import type { WorkflowTaskExecution } from "../../../domains/platform/types.js";
|
||||
import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { PLATFORM_ID_OPTION_KEYS } from "./shared.js";
|
||||
|
||||
async function createJobPiperClient(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
): Promise<Awaited<ReturnType<typeof createPiperClientForCorp>>> {
|
||||
const corp = runtime.selectedCorp!;
|
||||
const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
||||
if (explicit) {
|
||||
return createPiperClientForCorp(corp, explicit);
|
||||
}
|
||||
const clients = await createClientsForCorp(corp);
|
||||
try {
|
||||
const corpId = corp.corpId || corp.id;
|
||||
const platforms = await listPlatforms(clients.ekbClient, corpId);
|
||||
const firstActive = platforms.find((p) => p.active) ?? platforms[0];
|
||||
if (firstActive?.id) {
|
||||
return await createPiperClientForCorp(corp, firstActive.id);
|
||||
}
|
||||
} catch {
|
||||
// Fall back to default easoClient
|
||||
}
|
||||
return clients.easoClient;
|
||||
}
|
||||
|
||||
async function enrichFailedExecutions(
|
||||
client: Awaited<ReturnType<typeof createPiperClientForCorp>>,
|
||||
jobId: string,
|
||||
items: WorkflowTaskExecution[]
|
||||
): Promise<WorkflowTaskExecution[]> {
|
||||
const parentCache = new Map<string, WorkflowTaskExecution[]>();
|
||||
const enriched: WorkflowTaskExecution[] = [];
|
||||
|
||||
for (const item of items) {
|
||||
if (item.parentId && (!item.currentLoopPath || !item.name || !item.form)) {
|
||||
let siblings = parentCache.get(item.parentId);
|
||||
if (!siblings) {
|
||||
try {
|
||||
const level = await getJobExecutionLevel(client, jobId, {
|
||||
parentId: item.parentId,
|
||||
page: 1,
|
||||
pageSize: 100,
|
||||
});
|
||||
siblings = level.items;
|
||||
} catch {
|
||||
siblings = [];
|
||||
}
|
||||
parentCache.set(item.parentId, siblings);
|
||||
}
|
||||
const matched = siblings.find((s) => s.id === item.id);
|
||||
if (matched) {
|
||||
const itemInputs = item.inputs;
|
||||
const matchedInputs = matched.inputs;
|
||||
const hasItemInputs = Array.isArray(itemInputs)
|
||||
? itemInputs.length > 0
|
||||
: Boolean(itemInputs && typeof itemInputs === "object" && Object.keys(itemInputs as Record<string, unknown>).length > 0);
|
||||
const itemOutputs = item.outputs;
|
||||
const matchedOutputs = matched.outputs;
|
||||
const hasItemOutputs = Boolean(
|
||||
itemOutputs && typeof itemOutputs === "object" && Object.keys(itemOutputs as Record<string, unknown>).length > 0
|
||||
);
|
||||
enriched.push({
|
||||
...matched,
|
||||
...item,
|
||||
name: item.name || matched.name,
|
||||
label: item.label || matched.label,
|
||||
displayName: item.displayName || matched.displayName,
|
||||
type: item.type || matched.type,
|
||||
status: item.status || matched.status,
|
||||
currentLoopPath: item.currentLoopPath || matched.currentLoopPath,
|
||||
levelIndex: item.levelIndex?.length ? item.levelIndex : matched.levelIndex,
|
||||
form: item.form ?? matched.form,
|
||||
details: item.details ?? matched.details,
|
||||
inputs: hasItemInputs ? itemInputs : matchedInputs,
|
||||
outputs: hasItemOutputs ? itemOutputs : matchedOutputs,
|
||||
error: item.error ?? matched.error,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
}
|
||||
enriched.push(item);
|
||||
}
|
||||
return enriched;
|
||||
}
|
||||
|
||||
export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const jobId = parsed.args[0] || stringOption(parsed.options, ["id", "job-id", "jobId"]);
|
||||
if (!jobId) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use workflow job <jobId> [--failed] [--parent=<executionId>] [--logs=<executionId>]\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const client = await createJobPiperClient(parsed, runtime);
|
||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||
const pageSize = numberOption(parsed.options, ["page-size", "pageSize", "size"]) || 100;
|
||||
const logsExecutionId = stringOption(parsed.options, ["logs", "log", "execution-logs"]);
|
||||
const parentExecutionId = stringOption(parsed.options, ["parent", "parent-id", "parentId"]);
|
||||
const onlyFailed = booleanOption(parsed.options, ["failed", "fail", "errors"]);
|
||||
|
||||
// 1. --logs=<executionId>
|
||||
if (logsExecutionId) {
|
||||
const logs = await getExecutionLogs(client, logsExecutionId);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ jobId, executionId: logsExecutionId, logs }, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
const rows = logs.map((log, i) => [
|
||||
i + 1,
|
||||
String(log.id ?? "-"),
|
||||
String(log.createAt ?? (log as Record<string, unknown>).createTime ?? (log as Record<string, unknown>).timestamp ?? "-"),
|
||||
String(log.level || "INFO"),
|
||||
String(log.message || JSON.stringify(log)),
|
||||
]);
|
||||
return {
|
||||
stdout: [
|
||||
`====== 节点执行日志 (Job: ${jobId} | Execution: ${logsExecutionId}) ======`,
|
||||
rows.length ? printTable(["#", "日志 ID", "时间", "级别", "内容"], rows) : "该节点暂无输出日志",
|
||||
"",
|
||||
].join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. --parent=<executionId>
|
||||
if (parentExecutionId) {
|
||||
const levelPage = await getJobExecutionLevel(client, jobId, {
|
||||
parentId: parentExecutionId,
|
||||
page,
|
||||
pageSize,
|
||||
});
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
jobId,
|
||||
parentId: parentExecutionId,
|
||||
...levelPage,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = levelPage.items.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.id,
|
||||
item.name || "-",
|
||||
item.label || item.displayName || "-",
|
||||
item.type || "-",
|
||||
item.status || "-",
|
||||
item.currentLoopPath || "-",
|
||||
item.error?.message || "-",
|
||||
]);
|
||||
const extraDetails: string[] = [];
|
||||
for (const item of levelPage.items) {
|
||||
if (item.form !== undefined || item.error?.message) {
|
||||
extraDetails.push(
|
||||
`\n── 节点明细 [${item.id}] (${item.name || "-"} | loop=${item.currentLoopPath || "-"} | status=${item.status}) ──`
|
||||
);
|
||||
if (item.error?.message) {
|
||||
extraDetails.push(` 错误原因: ${item.error.message}`);
|
||||
}
|
||||
if (item.form !== undefined) {
|
||||
extraDetails.push(` 传入表单 (form): ${JSON.stringify(item.form)}`);
|
||||
}
|
||||
if (item.details !== undefined) {
|
||||
extraDetails.push(` 明细数据 (details): ${JSON.stringify(item.details)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`====== 子节点执行层级明细 (Job: ${jobId} | Parent: ${parentExecutionId} | 共 ${levelPage.totalItems} 项) ======`,
|
||||
rows.length
|
||||
? printTable(
|
||||
["#", "Execution ID", "节点标识 (name)", "节点名称", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因"],
|
||||
rows
|
||||
)
|
||||
: "暂无子节点执行记录",
|
||||
...extraDetails,
|
||||
"",
|
||||
].join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 3. --failed
|
||||
if (onlyFailed) {
|
||||
const [job, failedPage] = await Promise.all([
|
||||
getJob(client, jobId).catch(() => undefined),
|
||||
getJobFailedExecutions(client, jobId),
|
||||
]);
|
||||
const enrichedItems = await enrichFailedExecutions(client, jobId, failedPage.items);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
jobId,
|
||||
job: job ?? null,
|
||||
totalItems: failedPage.totalItems,
|
||||
items: enrichedItems,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = enrichedItems.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.id,
|
||||
item.parentId || "-",
|
||||
item.name || "-",
|
||||
item.type || "-",
|
||||
item.status || "-",
|
||||
item.currentLoopPath || "-",
|
||||
item.error?.message || "-",
|
||||
]);
|
||||
const formSummaries: string[] = [];
|
||||
for (const item of enrichedItems) {
|
||||
if (item.error?.message || item.form !== undefined) {
|
||||
formSummaries.push(
|
||||
`\n── ⚠️ 异常节点 [${item.id}] (${item.name || "-"} | status=${item.status} | loop=${item.currentLoopPath || "-"}) ──`
|
||||
);
|
||||
if (item.error?.message) {
|
||||
formSummaries.push(` 错误详情: ${item.error.message}`);
|
||||
}
|
||||
if (item.form !== undefined) {
|
||||
formSummaries.push(` 表单入参 (form): ${JSON.stringify(item.form)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: [
|
||||
`====== Job 异常/跳过执行节点明细 (Job: ${jobId}) ======`,
|
||||
job
|
||||
? printKeyValue({
|
||||
"Job ID": job.id,
|
||||
"工作流 ID": job.pipelineId,
|
||||
"Job 状态": job.state ?? job.status,
|
||||
"开始时间": job.startTime || "-",
|
||||
"耗时(ms)": String(job.durationTime ?? "-"),
|
||||
})
|
||||
: "",
|
||||
"",
|
||||
rows.length
|
||||
? printTable(
|
||||
["#", "Execution ID", "Parent ID", "节点标识 (name)", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因 (error.message)"],
|
||||
rows
|
||||
)
|
||||
: "未发现异常或报错跳过的执行节点",
|
||||
...formSummaries,
|
||||
"",
|
||||
].filter(Boolean).join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 4. Default mode: Job overview + top-level tree + failed executions
|
||||
const [job, tree, failedPage] = await Promise.all([
|
||||
getJob(client, jobId),
|
||||
getJobExecutionTree(client, jobId),
|
||||
getJobFailedExecutions(client, jobId).catch(() => ({
|
||||
number: 1,
|
||||
size: 100,
|
||||
totalPages: 0,
|
||||
totalItems: 0,
|
||||
items: [] as WorkflowTaskExecution[],
|
||||
})),
|
||||
]);
|
||||
const failedExecutions = await enrichFailedExecutions(client, jobId, failedPage.items);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
jobId,
|
||||
job,
|
||||
executionTree: tree,
|
||||
failedExecutions,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const treeRows = tree.map((node, idx) => [
|
||||
idx + 1,
|
||||
node.id,
|
||||
node.name || "-",
|
||||
node.label || node.displayName || "-",
|
||||
node.type || "-",
|
||||
node.status || "-",
|
||||
String((node as Record<string, unknown>).durationTime ?? node.executionTime ?? "-"),
|
||||
node.error?.message || "-",
|
||||
]);
|
||||
|
||||
const failedRows = failedExecutions.map((item, idx) => [
|
||||
idx + 1,
|
||||
item.id,
|
||||
item.parentId || "-",
|
||||
item.name || "-",
|
||||
item.type || "-",
|
||||
item.status || "-",
|
||||
item.currentLoopPath || "-",
|
||||
item.error?.message || "-",
|
||||
]);
|
||||
|
||||
const outLines = [
|
||||
`====== 工作流 Job 执行详情 [${job.id}] ======`,
|
||||
printKeyValue({
|
||||
"Job ID": job.id,
|
||||
"工作流 ID (pipelineId)": job.pipelineId,
|
||||
"Job 状态 (state)": job.state ?? job.status,
|
||||
"开始时间": job.startTime || "-",
|
||||
"结束时间": job.endTime || "-",
|
||||
"耗时(ms)": String(job.durationTime ?? "-"),
|
||||
"顶层节点数": tree.length,
|
||||
"异常/跳过节点数": failedExecutions.length,
|
||||
}),
|
||||
"",
|
||||
"── 顶层节点执行树 ──",
|
||||
treeRows.length
|
||||
? printTable(
|
||||
["#", "Execution ID", "节点标识 (name)", "节点名称", "类型 (type)", "状态 (status)", "耗时(ms)", "错误信息"],
|
||||
treeRows
|
||||
)
|
||||
: "暂无顶层节点执行记录",
|
||||
];
|
||||
|
||||
if (failedRows.length > 0) {
|
||||
outLines.push("");
|
||||
outLines.push("── ⚠️ 失败/报错跳过节点明细 (含循环子项) ──");
|
||||
outLines.push(
|
||||
printTable(
|
||||
["#", "Execution ID", "Parent ID", "节点标识 (name)", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因 (error.message)"],
|
||||
failedRows
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `${outLines.join("\n")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { toggleWorkflow } from "../../../domains/platform/services.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { createWorkflowDetailClient } from "./shared.js";
|
||||
|
||||
export async function handleToggle(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
const stateArg = stringOption(parsed.options, ["state", "s"]);
|
||||
|
||||
if (!pipelineId || stateArg === undefined) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use workflow toggle <pipelineId> --state=<1|0> (1启用, 0停用)\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const state = (stateArg === "1" || stateArg === "true" ? 1 : 0) as 0 | 1;
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"切换工作流状态",
|
||||
`hose-use workflow toggle ${pipelineId} --state=${state} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "切换工作流状态", pipelineId, { state });
|
||||
}
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const result = await toggleWorkflow(client, pipelineId, state);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 工作流 ${pipelineId} 状态已更新为: ${state === 1 ? "🟢 启用" : "⚪ 停用"}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handlePublish(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow publish <pipelineId>\n", exitCode: 1 };
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"发布并启用工作流",
|
||||
`hose-use workflow publish ${pipelineId} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "发布并启用工作流", pipelineId, { state: 1 });
|
||||
}
|
||||
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 };
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import {
|
||||
findWorkflowsByTaskType,
|
||||
getWorkflowDetail,
|
||||
listAllWorkflows,
|
||||
} from "../../../domains/platform/services.js";
|
||||
import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
||||
import { createClientsForCorp } from "../../helpers.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
import { PLATFORM_ID_OPTION_KEYS, createWorkflowDetailClient } from "./shared.js";
|
||||
|
||||
export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||
const pageSize = numberOption(parsed.options, ["pageSize", "size"]) || 50;
|
||||
const filterPlatformId = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
||||
|
||||
const rawResult = await listAllWorkflows(clients, { page, pageSize });
|
||||
const workflows = filterPlatformId
|
||||
? rawResult.workflows.filter(
|
||||
(wf) => wf.platformId === filterPlatformId || wf.platformName === filterPlatformId
|
||||
)
|
||||
: rawResult.workflows;
|
||||
const result = filterPlatformId
|
||||
? { ...rawResult, workflows, totalWorkflows: workflows.length }
|
||||
: rawResult;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
if (result.workflows.length === 0) {
|
||||
return {
|
||||
stdout: `企业 [${runtime.selectedCorp!.name}] 下暂无工作流\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = result.workflows.map((wf, i) => [
|
||||
i + 1,
|
||||
wf.id,
|
||||
wf.pipelineName,
|
||||
wf.platformName || wf.platformId || "-",
|
||||
wf.state === 1 ? "🟢 启用" : "⚪ 停用",
|
||||
wf.tasks?.length ?? "-",
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
["#", "工作流 ID", "工作流名称", "所属自建应用", "状态", "节点数"],
|
||||
rows
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: `====== [${runtime.selectedCorp!.name}] 工作流列表 (共 ${result.workflows.length} 条) ======\n${table}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) {
|
||||
return { stdout: "", stderr: "用法: hose-use workflow get <pipelineId>\n", exitCode: 1 };
|
||||
}
|
||||
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
const detail = await getWorkflowDetail(client, pipelineId);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const summary = printKeyValue({
|
||||
"工作流 ID": detail.id,
|
||||
"工作流名称": detail.label,
|
||||
"状态": detail.state === 1 ? "🟢 启用" : "⚪ 停用",
|
||||
"版本号": detail.version || "-",
|
||||
"节点总数": detail.tasks?.length ?? 0,
|
||||
});
|
||||
|
||||
let taskList = "";
|
||||
if (detail.tasks && detail.tasks.length > 0) {
|
||||
const taskRows = detail.tasks.map((t, i) => [
|
||||
i + 1,
|
||||
t.name || "-",
|
||||
t.label || "-",
|
||||
t.type,
|
||||
t.groupName || "-",
|
||||
]);
|
||||
taskList = `\n 节点结构:\n` + printTable(["#", "节点标识", "节点名称", "类型", "分组"], taskRows);
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `====== 工作流详情 ======\n${summary}\n${taskList}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleFind(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const taskType = stringOption(parsed.options, ["task", "taskType", "type"]) || parsed.args[0];
|
||||
if (!taskType) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "用法: hose-use workflow find --task=<节点类型> (如 code-js2, http, condition)\n",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const includeDetail = booleanOption(parsed.options, ["includeDetail", "detail"]);
|
||||
const page = numberOption(parsed.options, ["page"]) || 1;
|
||||
const pageSize = numberOption(parsed.options, ["pageSize", "size"]) || 50;
|
||||
|
||||
const result = await findWorkflowsByTaskType(clients, taskType, {
|
||||
page,
|
||||
pageSize,
|
||||
includeDetail,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
if (result.workflows.length === 0) {
|
||||
return {
|
||||
stdout: `未找到包含节点类型 [${taskType}] 的工作流\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = result.workflows.map((wf, i) => [
|
||||
i + 1,
|
||||
wf.id,
|
||||
wf.pipelineName,
|
||||
wf.platformName || wf.platformId || "-",
|
||||
wf.state === 1 ? "🟢 启用" : "⚪ 停用",
|
||||
]);
|
||||
|
||||
const table = printTable(
|
||||
["#", "工作流 ID", "工作流名称", "所属自建应用", "状态"],
|
||||
rows
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: `====== 匹配节点类型 [${taskType}] 的工作流 (共 ${result.workflows.length} 条) ======\n${table}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { listAllWorkflows } from "../../../domains/platform/services.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||
|
||||
export const PLATFORM_ID_OPTION_KEYS = ["platform-id", "platformId", "app-id", "appId"];
|
||||
|
||||
export async function createWorkflowDetailClient(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime,
|
||||
pipelineId: string,
|
||||
): Promise<{
|
||||
client: Awaited<ReturnType<typeof createPiperClientForCorp>>;
|
||||
clients: Awaited<ReturnType<typeof createClientsForCorp>>;
|
||||
}> {
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
|
||||
let platformId = explicit;
|
||||
if (!platformId) {
|
||||
const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 });
|
||||
platformId = all.workflows.find((workflow) => workflow.id === pipelineId)?.platformId;
|
||||
}
|
||||
return {
|
||||
client: platformId ? await createPiperClientForCorp(runtime.selectedCorp!, platformId) : clients.easoClient,
|
||||
clients,
|
||||
};
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { EkbError } from "../core/errors.js";
|
||||
|
||||
export type CliExitCode = 1 | 2 | 10 | 11 | 12;
|
||||
|
||||
export class CliError extends Error {
|
||||
@@ -35,6 +37,15 @@ export function classifyCliError(error: unknown): {
|
||||
return { exitCode: error.exitCode, nextAction: error.nextAction };
|
||||
}
|
||||
|
||||
if (error instanceof EkbError) {
|
||||
if (error.code === "NOT_LOGGED_IN" || error.code === "AUTH_FAILED" || error.status === 401) {
|
||||
return { exitCode: 11, nextAction: "hose-use auth login" };
|
||||
}
|
||||
if (error.code === "VALIDATION_ERROR") {
|
||||
return { exitCode: 2 };
|
||||
}
|
||||
}
|
||||
|
||||
const value = error instanceof Error ? error.message : String(error);
|
||||
const status = responseStatus(error);
|
||||
if (status === 401 || status === 403 || /(?:^|\s)(?:token|bearer|session) (?:expired|missing|invalid)/i.test(value)) {
|
||||
@@ -56,3 +67,4 @@ function responseStatus(error: unknown): number | undefined {
|
||||
const status = (response as { status?: unknown }).status;
|
||||
return typeof status === "number" ? status : undefined;
|
||||
}
|
||||
|
||||
@@ -90,6 +90,23 @@ export async function createScriptEngineClientForCorp(corp: CorpConfig, platform
|
||||
|
||||
export const createPiperClientForCorp = createScriptEngineClientForCorp;
|
||||
|
||||
export function requireSelectedCorp(
|
||||
runtime: CliRuntime,
|
||||
message = "未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。"
|
||||
): CorpConfig {
|
||||
if (!runtime.selectedCorp) {
|
||||
throw new Error(message);
|
||||
}
|
||||
return runtime.selectedCorp;
|
||||
}
|
||||
|
||||
export async function getSessionClientForRuntime(runtime: CliRuntime) {
|
||||
const corp = requireSelectedCorp(runtime);
|
||||
const corpId = corp.credentials?.corpId || corp.corpId || corp.id;
|
||||
const client = await createSessionClient(corp);
|
||||
return { corp, corpId, client };
|
||||
}
|
||||
|
||||
export function prompt(question: string): Promise<string> {
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { handleAuthCommand } from "./commands/auth.js";
|
||||
import { handleConfigCommand } from "./commands/config.js";
|
||||
import { handleCorpsCommand } from "./commands/corps.js";
|
||||
import { handleCorpsCommand } from "./commands/corps/index.js";
|
||||
import { handleMessageCommand } from "./commands/message.js";
|
||||
import { handleSkillCommand } from "./commands/skill.js";
|
||||
import type { CliRuntime } from "./types.js";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { handleBillCommand } from "./commands/bill.js";
|
||||
import { handleBillCommand } from "./commands/bill/index.js";
|
||||
import type { CliRuntime } from "./types.js";
|
||||
|
||||
const runtime: CliRuntime = {
|
||||
|
||||
+99
-4
@@ -17,6 +17,7 @@ const KNOWN_BOOLEAN_FLAGS = new Set([
|
||||
"check-only",
|
||||
"changelog",
|
||||
"log",
|
||||
"l",
|
||||
"local",
|
||||
"workspace",
|
||||
"external",
|
||||
@@ -25,13 +26,87 @@ const KNOWN_BOOLEAN_FLAGS = new Set([
|
||||
"allowFull",
|
||||
"summary",
|
||||
"yes",
|
||||
"y",
|
||||
"confirm",
|
||||
"force-write",
|
||||
"forceWrite",
|
||||
"dry-run",
|
||||
"dryRun",
|
||||
"dryrun",
|
||||
"all",
|
||||
"a",
|
||||
"include-disabled",
|
||||
"flat",
|
||||
"flatten",
|
||||
"table",
|
||||
"specs",
|
||||
"spec",
|
||||
"fields",
|
||||
"recursive",
|
||||
"in-place",
|
||||
"inPlace",
|
||||
"value-json",
|
||||
"valueJson",
|
||||
"has-error",
|
||||
"hasError",
|
||||
"errors",
|
||||
"failed",
|
||||
"fail",
|
||||
"fail-on-alert",
|
||||
"failOnAlert",
|
||||
"includeDetail",
|
||||
"detail",
|
||||
"apply",
|
||||
"execute",
|
||||
"do",
|
||||
"refresh",
|
||||
"overwrite",
|
||||
"elevate",
|
||||
"elevate-hose",
|
||||
"as-hose",
|
||||
"no-elevate",
|
||||
"reveal",
|
||||
"plain",
|
||||
"save",
|
||||
"persist",
|
||||
"verify",
|
||||
"workbench",
|
||||
"w",
|
||||
"active-only",
|
||||
"activeOnly",
|
||||
"active",
|
||||
"read",
|
||||
"unread",
|
||||
"clear",
|
||||
"sms",
|
||||
"sync",
|
||||
"interactive",
|
||||
"i",
|
||||
"reminder",
|
||||
"remind",
|
||||
"keep-it-secret",
|
||||
"secret",
|
||||
"private",
|
||||
"mine",
|
||||
"my",
|
||||
"self",
|
||||
"distinct",
|
||||
"risk",
|
||||
"with-risk",
|
||||
"audit",
|
||||
"github",
|
||||
"gh",
|
||||
"gitea",
|
||||
"yingqing",
|
||||
"mirror",
|
||||
]);
|
||||
|
||||
function isExplicitBooleanLiteral(val: string | undefined): boolean {
|
||||
if (!val) return false;
|
||||
const lower = val.toLowerCase();
|
||||
return lower === "true" || lower === "false";
|
||||
}
|
||||
|
||||
export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||
const options: Record<string, string | boolean | number> = {};
|
||||
const positional: string[] = [];
|
||||
@@ -53,11 +128,18 @@ export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||
} else {
|
||||
const key = arg.slice(2);
|
||||
const keyLower = key.toLowerCase();
|
||||
const next = rawArgs[i + 1];
|
||||
if (KNOWN_BOOLEAN_FLAGS.has(key) || KNOWN_BOOLEAN_FLAGS.has(keyLower)) {
|
||||
options[key] = true;
|
||||
if (key !== keyLower) options[keyLower] = true;
|
||||
if (isExplicitBooleanLiteral(next)) {
|
||||
const boolVal = next!.toLowerCase() === "true";
|
||||
options[key] = boolVal;
|
||||
if (key !== keyLower) options[keyLower] = boolVal;
|
||||
i++;
|
||||
} else {
|
||||
options[key] = true;
|
||||
if (key !== keyLower) options[keyLower] = true;
|
||||
}
|
||||
} else {
|
||||
const next = rawArgs[i + 1];
|
||||
if (next && !next.startsWith("-")) {
|
||||
options[key] = next;
|
||||
i++;
|
||||
@@ -86,6 +168,14 @@ export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||
} else {
|
||||
options.o = true;
|
||||
}
|
||||
} else if (flag === "c") {
|
||||
const next = rawArgs[i + 1];
|
||||
if (next && !next.startsWith("-")) {
|
||||
options.c = next;
|
||||
i++;
|
||||
} else {
|
||||
options.c = true;
|
||||
}
|
||||
} else {
|
||||
options[flag] = true;
|
||||
}
|
||||
@@ -103,6 +193,7 @@ export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||
area,
|
||||
action,
|
||||
args,
|
||||
positional,
|
||||
options,
|
||||
raw: rawArgs,
|
||||
};
|
||||
@@ -128,7 +219,11 @@ export function booleanOption(
|
||||
for (const k of keys) {
|
||||
const val = options[k];
|
||||
if (typeof val === "boolean") return val;
|
||||
if (typeof val === "string") return val === "true" || val === "1";
|
||||
if (typeof val === "string") {
|
||||
const lower = val.toLowerCase();
|
||||
if (lower === "true" || lower === "1") return true;
|
||||
if (lower === "false" || lower === "0") return false;
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
import { handleAuthCommand } from "./commands/auth.js";
|
||||
import { handleCorpsCommand } from "./commands/corps/index.js";
|
||||
import { handleConfigCommand } from "./commands/config.js";
|
||||
import { handleWorkflowCommand } from "./commands/workflow/index.js";
|
||||
import { handlePlatformCommand } from "./commands/platform/index.js";
|
||||
import { handleAppCommand } from "./commands/app.js";
|
||||
import { handleMenuCommand } from "./commands/menu.js";
|
||||
import { handleSkillCommand } from "./commands/skill.js";
|
||||
import { handleProbeCommand } from "./commands/probe.js";
|
||||
import { handleMcpCommand } from "./commands/mcp.js";
|
||||
import { handleUpdateCommand } from "./commands/update/index.js";
|
||||
import { handleOpenApiCommand } from "./commands/openapi.js";
|
||||
import { handleBillCommand } from "./commands/bill/index.js";
|
||||
import { handleContactCommand } from "./commands/contact.js";
|
||||
import { handleServiceCommand } from "./commands/service.js";
|
||||
import { handleHttpCommand } from "./commands/http.js";
|
||||
import { handleTaskCommand } from "./commands/task.js";
|
||||
import { handleMessageCommand } from "./commands/message.js";
|
||||
import { handleDimensionCommand } from "./commands/dimension.js";
|
||||
import { handleRoleCommand } from "./commands/role.js";
|
||||
import { handlePermissionCommand } from "./commands/permission.js";
|
||||
import { handleRuleCommand } from "./commands/rule.js";
|
||||
import { handleApprovalCommand } from "./commands/approval.js";
|
||||
import { handleContextCommand } from "./commands/context.js";
|
||||
import { handleKeysCommand } from "./commands/keys.js";
|
||||
import { handleStoreCommand } from "./commands/store.js";
|
||||
import { handleFeeTypeCommand } from "./commands/feetype.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "./types.js";
|
||||
|
||||
export type CliCommandHandler = (
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime,
|
||||
options: CliRunOptions
|
||||
) => Promise<CliResult>;
|
||||
|
||||
export interface CliCommandDefinition {
|
||||
area: string;
|
||||
aliases: string[];
|
||||
standing?: boolean | ((args: string[]) => boolean);
|
||||
handler: CliCommandHandler;
|
||||
}
|
||||
|
||||
export const CLI_COMMAND_REGISTRY: readonly CliCommandDefinition[] = [
|
||||
{
|
||||
area: "context",
|
||||
aliases: ["status", "whoami", "env"],
|
||||
handler: (parsed, runtime) => handleContextCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "aipro",
|
||||
aliases: [],
|
||||
handler: async (parsed) => {
|
||||
const { runAiProCli } = await import("../aipro-cli.js");
|
||||
const aiproIdx = parsed.raw.findIndex((a) => a.toLowerCase() === "aipro");
|
||||
const subArgs = aiproIdx !== -1 ? parsed.raw.slice(aiproIdx + 1) : parsed.raw.slice(1);
|
||||
return runAiProCli(subArgs);
|
||||
},
|
||||
},
|
||||
{
|
||||
area: "auth",
|
||||
aliases: ["login"],
|
||||
handler: (parsed, runtime) => handleAuthCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "corps",
|
||||
aliases: ["corp"],
|
||||
handler: (parsed, runtime) => handleCorpsCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "config",
|
||||
aliases: ["mode"],
|
||||
handler: (parsed, runtime) => handleConfigCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "workflow",
|
||||
aliases: ["workflows", "wf"],
|
||||
handler: (parsed, runtime) => handleWorkflowCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "bill",
|
||||
aliases: ["bills", "fee", "fees", "invoice", "invoices"],
|
||||
handler: (parsed, runtime) => handleBillCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "contact",
|
||||
aliases: ["contacts", "staff", "staffs"],
|
||||
handler: (parsed, runtime) => handleContactCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "task",
|
||||
aliases: ["tasks", "todo"],
|
||||
handler: (parsed, runtime) => handleTaskCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "dimension",
|
||||
aliases: ["dimensions", "archive", "archives"],
|
||||
handler: (parsed, runtime) => handleDimensionCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "feetype",
|
||||
aliases: ["feetypes", "fee-type", "fee-types", "expense-type", "expense-types", "costtype"],
|
||||
handler: (parsed, runtime) => handleFeeTypeCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "role",
|
||||
aliases: ["roles"],
|
||||
handler: (parsed, runtime) => handleRoleCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "permission",
|
||||
aliases: ["permissions"],
|
||||
handler: (parsed, runtime) => handlePermissionCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "rule",
|
||||
aliases: ["rules"],
|
||||
handler: (parsed, runtime) => handleRuleCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "approval",
|
||||
aliases: ["approvals", "audit"],
|
||||
handler: (parsed, runtime) => handleApprovalCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "message",
|
||||
aliases: ["messages", "notify", "notifications"],
|
||||
handler: (parsed, runtime) => handleMessageCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "platform",
|
||||
aliases: ["platforms", "datalink", "data-link"],
|
||||
handler: (parsed, runtime) => handlePlatformCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "app",
|
||||
aliases: ["apps", "workbench"],
|
||||
handler: (parsed, runtime) => handleAppCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "menu",
|
||||
aliases: ["menus"],
|
||||
handler: (parsed, runtime) => handleMenuCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "skill",
|
||||
aliases: ["skills"],
|
||||
handler: (parsed, runtime) => handleSkillCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "probe",
|
||||
aliases: ["diagnose"],
|
||||
handler: (parsed, runtime) => handleProbeCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "update",
|
||||
aliases: ["upgrade", "self-update", "changelog"],
|
||||
handler: (parsed, runtime, options) => handleUpdateCommand(parsed, runtime, options),
|
||||
},
|
||||
{
|
||||
area: "openapi",
|
||||
aliases: ["schema", "spec"],
|
||||
handler: (parsed, runtime) => handleOpenApiCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "keys",
|
||||
aliases: ["key", "secret", "secrets"],
|
||||
handler: (parsed, runtime) => handleKeysCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "store",
|
||||
aliases: ["market"],
|
||||
handler: (parsed, runtime) => handleStoreCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "http",
|
||||
aliases: ["server", "web"],
|
||||
standing: true,
|
||||
handler: (parsed, runtime) => handleHttpCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "service",
|
||||
aliases: ["daemon"],
|
||||
standing: (args) => args[1]?.toLowerCase() === "run",
|
||||
handler: (parsed, runtime) => handleServiceCommand(parsed, runtime),
|
||||
},
|
||||
{
|
||||
area: "mcp",
|
||||
aliases: [],
|
||||
standing: true,
|
||||
handler: (parsed, _runtime, options) => handleMcpCommand(parsed, options),
|
||||
},
|
||||
];
|
||||
|
||||
const COMMAND_LOOKUP = new Map<string, CliCommandDefinition>();
|
||||
for (const def of CLI_COMMAND_REGISTRY) {
|
||||
COMMAND_LOOKUP.set(def.area.toLowerCase(), def);
|
||||
for (const alias of def.aliases) {
|
||||
COMMAND_LOOKUP.set(alias.toLowerCase(), def);
|
||||
}
|
||||
}
|
||||
|
||||
export function findCommandByArea(area?: string): CliCommandDefinition | undefined {
|
||||
if (!area) return undefined;
|
||||
return COMMAND_LOOKUP.get(area.toLowerCase());
|
||||
}
|
||||
|
||||
export function isStandingCommand(args: string[]): boolean {
|
||||
if (!args.length) return false;
|
||||
const def = findCommandByArea(args[0]);
|
||||
if (!def?.standing) return false;
|
||||
return typeof def.standing === "function" ? def.standing(args) : def.standing;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { runCli } from "./runner.js";
|
||||
import { parseArgs, booleanOption } from "./parser.js";
|
||||
import { VERSION_INFO, formatVersionLabel } from "../version.js";
|
||||
|
||||
describe("CLI runner - version and help aliases", () => {
|
||||
@@ -98,4 +99,19 @@ describe("CLI runner - version and help aliases", () => {
|
||||
expect(help.stderr).toBe("");
|
||||
expect(version.stderr).toBe("");
|
||||
});
|
||||
|
||||
it("does not swallow positional arguments after subcommand boolean flags", () => {
|
||||
const parsed1 = parseArgs(["feetype", "get", "--all", "FT001"]);
|
||||
expect(booleanOption(parsed1.options, ["all"])).toBe(true);
|
||||
expect(parsed1.args).toEqual(["FT001"]);
|
||||
|
||||
const parsed2 = parseArgs(["workflow", "patch", "--in-place", "--value-json", "PIPE_123"]);
|
||||
expect(booleanOption(parsed2.options, ["in-place"])).toBe(true);
|
||||
expect(booleanOption(parsed2.options, ["value-json"])).toBe(true);
|
||||
expect(parsed2.args).toEqual(["PIPE_123"]);
|
||||
|
||||
const parsed3 = parseArgs(["platform", "record", "toggle", "--active", "false", "REC_01"]);
|
||||
expect(booleanOption(parsed3.options, ["active"], true)).toBe(false);
|
||||
expect(parsed3.args).toEqual(["toggle", "REC_01"]);
|
||||
});
|
||||
});
|
||||
+12
-162
@@ -3,46 +3,9 @@ import { parseArgs, stringOption, booleanOption, outputOptions } from "./parser.
|
||||
import { printHelp, printJson, redactSensitiveText } from "./printer.js";
|
||||
import { classifyCliError } from "./errors.js";
|
||||
import { initCorpRuntime } from "./helpers.js";
|
||||
import { handleAuthCommand } from "./commands/auth.js";
|
||||
import { handleCorpsCommand } from "./commands/corps.js";
|
||||
import { handleConfigCommand } from "./commands/config.js";
|
||||
import { handleWorkflowCommand } from "./commands/workflow.js";
|
||||
import { handlePlatformCommand } from "./commands/platform.js";
|
||||
import { handleAppCommand } from "./commands/app.js";
|
||||
import { handleMenuCommand } from "./commands/menu.js";
|
||||
import { handleSkillCommand } from "./commands/skill.js";
|
||||
import { handleProbeCommand } from "./commands/probe.js";
|
||||
import { handleMcpCommand } from "./commands/mcp.js";
|
||||
import { handleUpdateCommand } from "./commands/update.js";
|
||||
import { handleOpenApiCommand } from "./commands/openapi.js";
|
||||
import { handleBillCommand } from "./commands/bill.js";
|
||||
import { handleContactCommand } from "./commands/contact.js";
|
||||
import { handleServiceCommand } from "./commands/service.js";
|
||||
import { handleHttpCommand } from "./commands/http.js";
|
||||
import { handleTaskCommand } from "./commands/task.js";
|
||||
import { handleMessageCommand } from "./commands/message.js";
|
||||
import { handleDimensionCommand } from "./commands/dimension.js";
|
||||
import { handleRoleCommand } from "./commands/role.js";
|
||||
import { handlePermissionCommand } from "./commands/permission.js";
|
||||
import { handleRuleCommand } from "./commands/rule.js";
|
||||
import { handleApprovalCommand } from "./commands/approval.js";
|
||||
import { handleContextCommand } from "./commands/context.js";
|
||||
import { handleKeysCommand } from "./commands/keys.js";
|
||||
import { handleStoreCommand } from "./commands/store.js";
|
||||
import { handleFeeTypeCommand } from "./commands/feetype.js";
|
||||
import { findCommandByArea, isStandingCommand } from "./registry.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions } from "./types.js";
|
||||
|
||||
const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]);
|
||||
|
||||
function isStandingCommand(args: string[]): boolean {
|
||||
if (!args.length) return false;
|
||||
const first = args[0]?.toLowerCase();
|
||||
const second = args[1]?.toLowerCase();
|
||||
if (STANDING_COMMANDS.has(first)) return true;
|
||||
if ((first === "service" || first === "daemon") && second === "run") return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
let runQueue = Promise.resolve<any>(undefined);
|
||||
|
||||
export function runCli(
|
||||
@@ -175,131 +138,18 @@ async function dispatchCli(
|
||||
});
|
||||
|
||||
try {
|
||||
switch (parsed.area) {
|
||||
case "context":
|
||||
case "status":
|
||||
case "whoami":
|
||||
case "env":
|
||||
return await handleContextCommand(parsed, runtime);
|
||||
case "aipro": {
|
||||
const { runAiProCli } = await import("../aipro-cli.js");
|
||||
const aiproIdx = parsed.raw.findIndex((a) => a.toLowerCase() === "aipro");
|
||||
const subArgs = aiproIdx !== -1 ? parsed.raw.slice(aiproIdx + 1) : parsed.raw.slice(1);
|
||||
return await runAiProCli(subArgs);
|
||||
}
|
||||
case "auth":
|
||||
case "login":
|
||||
return await handleAuthCommand(parsed, runtime);
|
||||
case "corps":
|
||||
case "corp":
|
||||
return await handleCorpsCommand(parsed, runtime);
|
||||
case "config":
|
||||
case "mode":
|
||||
return await handleConfigCommand(parsed, runtime);
|
||||
case "workflow":
|
||||
case "workflows":
|
||||
case "wf":
|
||||
return await handleWorkflowCommand(parsed, runtime);
|
||||
case "bill":
|
||||
case "bills":
|
||||
case "fee":
|
||||
case "fees":
|
||||
case "invoice":
|
||||
case "invoices":
|
||||
return await handleBillCommand(parsed, runtime);
|
||||
case "contact":
|
||||
case "contacts":
|
||||
case "staff":
|
||||
case "staffs":
|
||||
return await handleContactCommand(parsed, runtime);
|
||||
case "task":
|
||||
case "tasks":
|
||||
case "todo":
|
||||
return await handleTaskCommand(parsed, runtime);
|
||||
case "dimension":
|
||||
case "dimensions":
|
||||
case "archive":
|
||||
case "archives":
|
||||
return await handleDimensionCommand(parsed, runtime);
|
||||
case "feetype":
|
||||
case "feetypes":
|
||||
case "fee-type":
|
||||
case "fee-types":
|
||||
case "expense-type":
|
||||
case "expense-types":
|
||||
case "costtype":
|
||||
return await handleFeeTypeCommand(parsed, runtime);
|
||||
case "role":
|
||||
case "roles":
|
||||
return await handleRoleCommand(parsed, runtime);
|
||||
case "permission":
|
||||
case "permissions":
|
||||
return await handlePermissionCommand(parsed, runtime);
|
||||
case "rule":
|
||||
case "rules":
|
||||
return await handleRuleCommand(parsed, runtime);
|
||||
case "approval":
|
||||
case "approvals":
|
||||
case "audit":
|
||||
return await handleApprovalCommand(parsed, runtime);
|
||||
case "message":
|
||||
case "messages":
|
||||
case "notify":
|
||||
case "notifications":
|
||||
return await handleMessageCommand(parsed, runtime);
|
||||
case "platform":
|
||||
case "platforms":
|
||||
case "datalink":
|
||||
case "data-link":
|
||||
return await handlePlatformCommand(parsed, runtime);
|
||||
case "app":
|
||||
case "apps":
|
||||
case "workbench":
|
||||
return await handleAppCommand(parsed, runtime);
|
||||
case "menu":
|
||||
case "menus":
|
||||
return await handleMenuCommand(parsed, runtime);
|
||||
case "skill":
|
||||
case "skills":
|
||||
return await handleSkillCommand(parsed, runtime);
|
||||
case "probe":
|
||||
case "diagnose":
|
||||
return await handleProbeCommand(parsed, runtime);
|
||||
case "update":
|
||||
case "upgrade":
|
||||
case "self-update":
|
||||
case "changelog":
|
||||
return await handleUpdateCommand(parsed, runtime, options);
|
||||
case "openapi":
|
||||
case "schema":
|
||||
case "spec":
|
||||
return await handleOpenApiCommand(parsed, runtime);
|
||||
case "keys":
|
||||
case "key":
|
||||
case "secret":
|
||||
case "secrets":
|
||||
return await handleKeysCommand(parsed, runtime);
|
||||
case "store":
|
||||
case "market":
|
||||
return await handleStoreCommand(parsed, runtime);
|
||||
case "http":
|
||||
case "server":
|
||||
case "web":
|
||||
return await handleHttpCommand(parsed, runtime);
|
||||
case "service":
|
||||
case "daemon":
|
||||
return await handleServiceCommand(parsed, runtime);
|
||||
case "mcp":
|
||||
return await handleMcpCommand(parsed, options);
|
||||
case undefined:
|
||||
return { stdout: printHelp(resolveHelpTarget(parsed)) + "\n", stderr: "", exitCode: 0 };
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知命令域: ${parsed.area}。运行 hose-use --help 查看帮助\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
if (!parsed.area) {
|
||||
return { stdout: printHelp(resolveHelpTarget(parsed)) + "\n", stderr: "", exitCode: 0 };
|
||||
}
|
||||
const commandDef = findCommandByArea(parsed.area);
|
||||
if (!commandDef) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知命令域: ${parsed.area}。运行 hose-use --help 查看帮助\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return await commandDef.handler(parsed, runtime, options);
|
||||
} catch (error) {
|
||||
const errorMsg = redactSensitiveText(error instanceof Error ? error.message : String(error));
|
||||
const classification = classifyCliError(error);
|
||||
|
||||
@@ -5,6 +5,7 @@ export interface CliParsedArgs {
|
||||
area?: string;
|
||||
action?: string;
|
||||
args: string[];
|
||||
positional?: string[];
|
||||
options: Record<string, string | boolean | number>;
|
||||
raw: string[];
|
||||
}
|
||||
|
||||
+18
-15
@@ -1,45 +1,48 @@
|
||||
# Core 层说明
|
||||
|
||||
Core 层负责基础设施:企业配置管理、认证 Token 获取与缓存、统一数据库与版本迁移、多级协同缓存、HTTP 客户端工厂、统一异常语义。
|
||||
Core 层负责基础设施:企业配置管理、认证 Token 获取与持久化缓存、统一数据库与版本迁移、多级协同缓存、HTTP 客户端工厂、统一异常语义。
|
||||
|
||||
## 代码结构
|
||||
|
||||
```text
|
||||
src/core/
|
||||
├── auth/ # 登录认证协议与凭证存储(纯凭据层:用户级主账号 + 企业级 OpenAPI 持久化双通道)
|
||||
│ ├── login.ts # 登录与换票矩阵(RSA账密、短信、F12/协助链接导入、浏览器同步、OpenAPI 密钥持久化与 getProvisionalAuth 续期)
|
||||
│ ├── account-store.ts # 多账号持久化存储 (~/.config/hose-use/accounts.json)
|
||||
│ ├── tools.ts # MCP Auth Tools 注册与调度
|
||||
│ ├── token-store.ts # 动态 Token 缓存 (~/.config/hose-use/tokens.json)
|
||||
│ ├── login.ts # IDP 账密/短信/浏览器登录、企业切换换票与双通道自动续期入口
|
||||
│ ├── openapi-v1.ts # OpenAPI v1 换票、Provisional 免密鉴权、密钥提取与标准域名探测
|
||||
│ ├── link-import.ts # 协助链接 (thirdparty.html)、F12 Headers / cURL 凭证解析与导入
|
||||
│ ├── openapi-onboard.ts # OpenAPI 持久化一键建档、seal-use 同步、企业提权与免密直达链接签发
|
||||
│ ├── account-store.ts # 多账号持久化存储 (~/.config/hose-use/accounts.json, 0o600 权限保护)
|
||||
│ ├── token-store.ts # 子域动态 Token 跨进程 L2 持久化缓存 (~/.config/hose-use/tokens.json, 0o600)
|
||||
│ └── types.ts
|
||||
├── http/ # 统一 HTTP 客户端装配与网络传输(语义化客户端)
|
||||
│ ├── factory.ts # Ky 底层客户端工厂(超时、重试、错误钩子)
|
||||
│ ├── fingerprint.ts # 统一浏览器指纹、User-Agent、Cookie 与 WAF 策略头
|
||||
│ ├── session-client.ts # 闭合用户会话客户端(三 Header + 指纹 + 账号/OpenAPI 双通道自动续杯)
|
||||
│ ├── openapi-client.ts # 开放平台应用客户端(appKey 换票与签名机制)
|
||||
│ ├── unity-client.ts # 应用中心与动态集群寻址客户端(支持账号/OpenAPI 双通道预续期)
|
||||
│ ├── script-engine-client.ts # 工作流 MVEL/Python 脚本调试引擎客户端
|
||||
│ ├── unity-client.ts # 应用中心与动态集群寻址客户端(L1 内存 + L2 token-store 跨进程复用)
|
||||
│ ├── script-engine-client.ts # 工作流 MVEL/Python 脚本调试引擎客户端(L1 + L2 token-store 缓存)
|
||||
│ └── index.ts # 统一导出入口
|
||||
├── cache/ # 统一多级协同缓存
|
||||
│ ├── memory.ts # L1 内存缓存(TTL、容量限制、按命名空间清理)
|
||||
│ ├── memory.ts # L1 内存缓存(严格 LRU、TTL、容量限制、按命名空间清理)
|
||||
│ ├── sqlite.ts # L2 SQLite 持久化缓存(跨 CLI 进程复用)
|
||||
│ ├── multi-level.ts # 多级联动门面与 withCache 透明包装器
|
||||
│ ├── multi-level.ts # 多级联动门面与 in-flight 并发防击穿包装器
|
||||
│ └── types.ts
|
||||
├── db/ # 统一 SQLite 数据库与结构化版本迁移
|
||||
│ ├── connection.ts # SQLite 单例、WAL 模式、文件权限 0o600 保护
|
||||
│ ├── migrations.ts # 结构化增量迁移运行器(_schema_migrations)
|
||||
│ └── types.ts
|
||||
├── config/ # 企业配置管理
|
||||
│ ├── loader.ts
|
||||
│ ├── manager.ts
|
||||
│ └── types.ts
|
||||
└── errors.ts # 统一异常语义(EkbError 子类)
|
||||
│ ├── loader.ts # 全局与多企业配置读写(强制 0o600 权限与字段归一化)
|
||||
│ ├── manager.ts # CorpContext 多企业上下文与身份解析
|
||||
│ └── types.ts # CorpConfig / GlobalConfig Schema 与统一字段访问器
|
||||
└── errors.ts # 统一异常语义(EkbError / NotLoggedInError / AuthenticationError / PermissionError / NotFoundError / ValidationError / BusinessError / EkbApiError)
|
||||
```
|
||||
|
||||
## 分层约束
|
||||
|
||||
- `domains/*` 优先通过 `core/http/` 获取语义化客户端(`createSessionClient`, `createOpenApiClient`, `getUnityClient`, `getScriptEngineClient`),保持底层网络与指纹统一
|
||||
- `domains/*` 层只抛 `EkbError` 子类
|
||||
- `server.ts` 负责把 `EkbError` 映射为 MCP error
|
||||
- `domains/*` 层只抛 `EkbError` 子类(由 `cli/errors.ts` 统一按结构化 `code` / `status` 映射退出码)
|
||||
- `server.ts` 作为极简 MCP 单工具网关(`hose_cli`)直接委托 `cli/runner.ts` 执行
|
||||
- 业务域如果需要缓存,统一使用 `core/cache/` 提供的多级缓存门面
|
||||
- 业务域如果需要持久化数据,统一接入 `core/db/` 并注册版本迁移
|
||||
|
||||
@@ -10,6 +10,14 @@ export const ACCOUNT_CACHE_PATH = join(
|
||||
"accounts.json"
|
||||
);
|
||||
|
||||
export function resolveAccountCachePath(): string {
|
||||
const envFile = process.env.HOSE_ACCOUNTS_FILE?.trim();
|
||||
if (envFile) return envFile;
|
||||
const stateDir = process.env.HOSE_STATE_DIR?.trim();
|
||||
if (stateDir) return join(stateDir, "accounts.json");
|
||||
return ACCOUNT_CACHE_PATH;
|
||||
}
|
||||
|
||||
export const AccountCorporationMetaSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
@@ -48,8 +56,9 @@ function ensureDir(path: string): void {
|
||||
}
|
||||
|
||||
export function loadAccountStore(): AccountStore {
|
||||
const filePath = resolveAccountCachePath();
|
||||
try {
|
||||
const content = readFileSync(ACCOUNT_CACHE_PATH, "utf-8");
|
||||
const content = readFileSync(filePath, "utf-8");
|
||||
return AccountStoreSchema.parse(JSON.parse(content));
|
||||
} catch {
|
||||
return { accounts: {} };
|
||||
@@ -57,8 +66,15 @@ export function loadAccountStore(): AccountStore {
|
||||
}
|
||||
|
||||
export function saveAccountStore(store: AccountStore): void {
|
||||
ensureDir(ACCOUNT_CACHE_PATH);
|
||||
writeFileSync(ACCOUNT_CACHE_PATH, JSON.stringify(store, null, 2), "utf-8");
|
||||
const filePath = resolveAccountCachePath();
|
||||
ensureDir(filePath);
|
||||
writeFileSync(filePath, JSON.stringify(store, null, 2), {
|
||||
encoding: "utf-8",
|
||||
mode: 0o600,
|
||||
});
|
||||
try {
|
||||
chmodSync(filePath, 0o600);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function saveAccount(entry: AccountEntry): void {
|
||||
|
||||
@@ -0,0 +1,612 @@
|
||||
import ky from "ky";
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
import { CorpConfig, CredentialSource } from "../config/types.js";
|
||||
import { saveCorpConfig, resolveWritableEnterprisesDir } from "../config/loader.js";
|
||||
import { resolveCorpCluster, clearUnityClientCache } from "../http/unity-client.js";
|
||||
import { clearScriptEngineClientCache } from "../http/script-engine-client.js";
|
||||
import { clearCorpTokens } from "./token-store.js";
|
||||
import {
|
||||
DEFAULT_EKB_BASE_URL,
|
||||
HoseOpenApiKeyItem,
|
||||
fetchOpenApiKeysBySession,
|
||||
selectOpenApiKey,
|
||||
} from "./openapi-v1.js";
|
||||
|
||||
// ── 模式 4:F12 / cURL / 手动直接导入单企业凭证 ───────────────────────────────
|
||||
|
||||
export interface F12ImportParams {
|
||||
accessToken: string;
|
||||
corpId: string;
|
||||
staffId?: string;
|
||||
name?: string;
|
||||
baseUrl?: string;
|
||||
cluster?: string;
|
||||
source?: CredentialSource;
|
||||
enterprisesDir?: string;
|
||||
overwrite?: boolean;
|
||||
ttl?: string | number;
|
||||
expires?: string | number;
|
||||
appKey?: string;
|
||||
appSecurity?: string;
|
||||
keyId?: string;
|
||||
elevate?: boolean;
|
||||
autoElevate?: boolean;
|
||||
force?: boolean;
|
||||
}
|
||||
|
||||
export interface ImportFromLinkOptions {
|
||||
name?: string;
|
||||
baseUrl?: string;
|
||||
enterprisesDir?: string;
|
||||
overwrite?: boolean;
|
||||
ttl?: string | number;
|
||||
expires?: string | number;
|
||||
appKey?: string;
|
||||
appSecurity?: string;
|
||||
keyId?: string;
|
||||
elevate?: boolean;
|
||||
autoElevate?: boolean;
|
||||
force?: boolean;
|
||||
}
|
||||
|
||||
function parseDurationMs(value: string | number, defaultUnit: "hours" | "days"): number {
|
||||
const raw = String(value).trim().toLowerCase();
|
||||
const match = raw.match(/^(\d+(?:\.\d+)?)\s*(h|hr|hrs|hour|hours|d|day|days)?$/);
|
||||
if (!match) throw new AuthenticationError(`无效的有效期参数: ${value}(示例:3d、72h)`);
|
||||
const amount = Number(match[1]);
|
||||
if (!Number.isFinite(amount) || amount <= 0) {
|
||||
throw new AuthenticationError(`有效期必须是大于 0 的数字: ${value}`);
|
||||
}
|
||||
const unit = match[2];
|
||||
const isDays = unit ? ["d", "day", "days"].includes(unit) : defaultUnit === "days";
|
||||
return amount * (isDays ? 24 : 1) * 60 * 60 * 1000;
|
||||
}
|
||||
|
||||
export function resolveLinkExpiresAt(
|
||||
options: { ttl?: string | number; expires?: string | number },
|
||||
baseTime = Date.now()
|
||||
): number | undefined {
|
||||
if (options.ttl !== undefined) return baseTime + parseDurationMs(options.ttl, "hours");
|
||||
if (options.expires !== undefined) return baseTime + parseDurationMs(options.expires, "days");
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function parseExpiresInSeconds(
|
||||
value?: string | number,
|
||||
fallbackSeconds = 7200
|
||||
): number {
|
||||
if (value === undefined || value === null || String(value).trim() === "") {
|
||||
return fallbackSeconds;
|
||||
}
|
||||
if (typeof value === "number") {
|
||||
if (!Number.isFinite(value) || value <= 0) {
|
||||
throw new AuthenticationError(`有效期秒数必须是大于 0 的数字: ${value}`);
|
||||
}
|
||||
return Math.round(value);
|
||||
}
|
||||
const raw = String(value).trim().toLowerCase();
|
||||
const match = raw.match(
|
||||
/^(\d+(?:\.\d+)?)\s*(s|sec|secs|second|seconds|m|min|mins|minute|minutes|h|hr|hrs|hour|hours|d|day|days)?$/
|
||||
);
|
||||
if (!match) {
|
||||
throw new AuthenticationError(
|
||||
`无效的有效期参数: ${value}(支持秒数如 86400,或带单位如 30m、24h、3d)`
|
||||
);
|
||||
}
|
||||
const amount = Number(match[1]);
|
||||
if (!Number.isFinite(amount) || amount <= 0) {
|
||||
throw new AuthenticationError(`有效期必须是大于 0 的数字: ${value}`);
|
||||
}
|
||||
const unit = match[2] || "s";
|
||||
if (["s", "sec", "secs", "second", "seconds"].includes(unit)) {
|
||||
return Math.round(amount);
|
||||
}
|
||||
if (["m", "min", "mins", "minute", "minutes"].includes(unit)) {
|
||||
return Math.round(amount * 60);
|
||||
}
|
||||
if (["h", "hr", "hrs", "hour", "hours"].includes(unit)) {
|
||||
return Math.round(amount * 3600);
|
||||
}
|
||||
return Math.round(amount * 86400);
|
||||
}
|
||||
|
||||
export function invalidateCorpSubdomainTokenCaches(corp: CorpConfig): void {
|
||||
try {
|
||||
const keys = new Set<string>(
|
||||
[corp.id, corp.corpId, corp.credentials?.corpId].filter((v): v is string => Boolean(v))
|
||||
);
|
||||
for (const key of keys) {
|
||||
clearCorpTokens(key);
|
||||
clearUnityClientCache(key);
|
||||
clearScriptEngineClientCache(key);
|
||||
}
|
||||
} catch {
|
||||
// Ignore cache cleanup errors in restricted environments
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析从 F12 抓包复制出来的 Request Headers、cURL 命令或 URL 字符串
|
||||
*/
|
||||
export function parseHeadersOrCurl(rawInput: string): Partial<F12ImportParams> {
|
||||
const result: Partial<F12ImportParams> = {};
|
||||
if (!rawInput) return result;
|
||||
|
||||
// 0. 尝试匹配完整 URL(包含 http:// 或 https://)
|
||||
const urlMatch = /(https?:\/\/[^\s"'<>]+)/i.exec(rawInput);
|
||||
if (urlMatch) {
|
||||
try {
|
||||
const parsedUrl = new URL(urlMatch[1]);
|
||||
result.baseUrl = `${parsedUrl.protocol}//${parsedUrl.host}`;
|
||||
const tokenParam =
|
||||
parsedUrl.searchParams.get("accessToken") ||
|
||||
parsedUrl.searchParams.get("token");
|
||||
if (tokenParam) result.accessToken = tokenParam;
|
||||
const corpParam =
|
||||
parsedUrl.searchParams.get("ekbCorpId") ||
|
||||
parsedUrl.searchParams.get("corpId") ||
|
||||
parsedUrl.searchParams.get("corporationId");
|
||||
if (corpParam) result.corpId = corpParam;
|
||||
const staffParam = parsedUrl.searchParams.get("staffId");
|
||||
if (staffParam) result.staffId = staffParam;
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// 1. 尝试匹配各种 -H / --header 参数:-H 'header: value' 或 -H "header: value"
|
||||
const headerRegex = /(?:-H|--header)\s+['"]([^'"]+)['"]/gi;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = headerRegex.exec(rawInput)) !== null) {
|
||||
const headerStr = match[1];
|
||||
const colonIdx = headerStr.indexOf(":");
|
||||
if (colonIdx !== -1) {
|
||||
const key = headerStr.slice(0, colonIdx).trim().toLowerCase().replace(/[^a-z]/g, "");
|
||||
const val = headerStr.slice(colonIdx + 1).trim();
|
||||
if (key === "accesstoken") result.accessToken = val;
|
||||
if (key === "corpid" || key === "corporationid") result.corpId = val;
|
||||
if (key === "staffid") result.staffId = val;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 逐行匹配标准 HTTP Headers (如 accesstoken: xxx)
|
||||
const lines = rawInput.split("\n");
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
const colonIdx = trimmed.indexOf(":");
|
||||
if (colonIdx !== -1) {
|
||||
const key = trimmed.slice(0, colonIdx).trim().toLowerCase().replace(/[^a-z]/g, "");
|
||||
const val = trimmed.slice(colonIdx + 1).trim().replace(/^['"]|['"]$/g, "");
|
||||
if (key === "accesstoken" && !result.accessToken) result.accessToken = val;
|
||||
if ((key === "corpid" || key === "corporationid") && !result.corpId) result.corpId = val;
|
||||
if (key === "staffid" && !result.staffId) result.staffId = val;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 从 URL/Query 中提取 query 参数(例如 ?corpId=xxx 或 &corpId=xxx 或 ekbCorpId=xxx)
|
||||
if (!result.corpId) {
|
||||
const urlCorpMatch = /(?:[?&](?:ekbCorpId|corpId|corporationId)=)([^&'"\s]+)/i.exec(rawInput);
|
||||
if (urlCorpMatch) {
|
||||
result.corpId = decodeURIComponent(urlCorpMatch[1]);
|
||||
}
|
||||
}
|
||||
if (!result.accessToken) {
|
||||
const urlTokenMatch = /(?:[?&](?:accessToken|token)=)([^&'"\s]+)/i.exec(rawInput);
|
||||
if (urlTokenMatch) {
|
||||
result.accessToken = decodeURIComponent(urlTokenMatch[1]);
|
||||
}
|
||||
}
|
||||
if (!result.staffId) {
|
||||
const urlStaffMatch = /(?:[?&]staffId=)([^&'"\s]+)/i.exec(rawInput);
|
||||
if (urlStaffMatch) {
|
||||
result.staffId = decodeURIComponent(urlStaffMatch[1]);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 从 Cookie (-b / Cookie header) 中提取 ekb-access-token 或 corpId
|
||||
if (!result.accessToken) {
|
||||
const cookieTokenMatch = /ekb-access-token=([^;'"\s]+)/i.exec(rawInput);
|
||||
if (cookieTokenMatch) {
|
||||
result.accessToken = decodeURIComponent(cookieTokenMatch[1]);
|
||||
}
|
||||
}
|
||||
if (!result.corpId) {
|
||||
const cookieCorpMatch = /(?:^|;\s*)corpId=([^;'"\s]+)/i.exec(rawInput);
|
||||
if (cookieCorpMatch) {
|
||||
result.corpId = decodeURIComponent(cookieCorpMatch[1]);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并导入单个抓包/手动凭证,自动探测官方 Session 平台类型并保存到企业配置
|
||||
*/
|
||||
export async function importCredentials(
|
||||
params: F12ImportParams
|
||||
): Promise<CorpConfig> {
|
||||
const { accessToken, corpId } = params;
|
||||
let staffId = params.staffId;
|
||||
const baseUrl = params.baseUrl || DEFAULT_EKB_BASE_URL;
|
||||
|
||||
if (!accessToken || !corpId) {
|
||||
throw new AuthenticationError("导入凭证失败:accessToken 与 corpId 均为必填项");
|
||||
}
|
||||
|
||||
// 检查已存在保护:当明确要求不覆盖 (overwrite === false) 且文件已存在时拦截
|
||||
const targetDir = params.enterprisesDir || resolveWritableEnterprisesDir();
|
||||
const targetFile = join(targetDir, `${corpId}.json`);
|
||||
if (params.overwrite === false && existsSync(targetFile)) {
|
||||
throw new AuthenticationError(`企业 [${corpId}] 配置文件已存在。若要更新覆盖,请附加 --overwrite 参数。`);
|
||||
}
|
||||
|
||||
// 1. 若 staffId 缺失,优先通过 $UNITY JWT 自动探测 staffId、企业名与身份
|
||||
let corpName = params.name;
|
||||
let staffName: string | undefined;
|
||||
let cellphone: string | undefined;
|
||||
let isAdmin: boolean | undefined;
|
||||
let sourceChannel: string | undefined;
|
||||
let jwtExpMs: number | undefined;
|
||||
const requestedExpiresAt = resolveLinkExpiresAt(params);
|
||||
|
||||
try {
|
||||
const jwtHeaders: Record<string, string> = {
|
||||
accesstoken: accessToken,
|
||||
corpid: corpId,
|
||||
};
|
||||
if (staffId) {
|
||||
jwtHeaders.staffid = staffId;
|
||||
}
|
||||
const jwtRes = await ky
|
||||
.get(`${baseUrl}/api/engine/realm/$UNITY/actions/jwt`, {
|
||||
searchParams: { corpId },
|
||||
headers: jwtHeaders,
|
||||
})
|
||||
.json<{ id?: string; value?: string }>();
|
||||
const token = jwtRes.id || jwtRes.value;
|
||||
if (token) {
|
||||
const parts = token.split(".");
|
||||
if (parts.length >= 2) {
|
||||
const payload = JSON.parse(Buffer.from(parts[1], "base64").toString("utf-8"));
|
||||
if (!staffId && payload.staffId) {
|
||||
staffId = payload.staffId;
|
||||
}
|
||||
if (!corpName && payload.corporationName) {
|
||||
corpName = payload.corporationName;
|
||||
}
|
||||
if (payload.staffName) {
|
||||
staffName = payload.staffName;
|
||||
}
|
||||
if (payload.cellphone) {
|
||||
cellphone = payload.cellphone;
|
||||
}
|
||||
if (payload.isAdmin !== undefined) {
|
||||
isAdmin = payload.isAdmin === "true" || payload.isAdmin === true;
|
||||
}
|
||||
if (payload.sourceChannel) {
|
||||
sourceChannel = payload.sourceChannel;
|
||||
}
|
||||
if (payload.exp) {
|
||||
jwtExpMs = Number(payload.exp) * 1000;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 探测失败则继续后续降级流程
|
||||
}
|
||||
|
||||
// 2. 验证凭证有效性并提取官方服务端 Session 元数据
|
||||
let sessionData: {
|
||||
id?: string;
|
||||
userId?: string;
|
||||
loginStaffId?: string;
|
||||
corporationId?: string;
|
||||
platform?: string;
|
||||
isAssistPlatform?: boolean;
|
||||
isShortTermToken?: boolean;
|
||||
assistId?: string;
|
||||
operationUserId?: string;
|
||||
operationUserName?: string;
|
||||
privilege?: string;
|
||||
deviceType?: string;
|
||||
loginAccountType?: string;
|
||||
loginTime?: number;
|
||||
expTime?: number;
|
||||
} | undefined;
|
||||
|
||||
try {
|
||||
const sessionHeaders: Record<string, string> = {
|
||||
accesstoken: accessToken,
|
||||
corpid: corpId,
|
||||
};
|
||||
if (staffId) {
|
||||
sessionHeaders.staffid = staffId;
|
||||
}
|
||||
const res = await ky
|
||||
.get(`${baseUrl}/api/account/v2/session`, {
|
||||
headers: sessionHeaders,
|
||||
})
|
||||
.json<{
|
||||
value?: {
|
||||
id?: string;
|
||||
userId?: string;
|
||||
loginStaffId?: string;
|
||||
corporationId?: string;
|
||||
platform?: string;
|
||||
isAssistPlatform?: boolean;
|
||||
isShortTermToken?: boolean;
|
||||
assistId?: string;
|
||||
operationUserId?: string;
|
||||
operationUserName?: string;
|
||||
privilege?: string;
|
||||
deviceType?: string;
|
||||
loginAccountType?: string;
|
||||
loginTime?: number;
|
||||
expTime?: number;
|
||||
};
|
||||
}>();
|
||||
|
||||
sessionData = res.value;
|
||||
if (!sessionData || (!sessionData.corporationId && !sessionData.id && !sessionData.userId)) {
|
||||
throw new Error("服务端未返回有效 Session");
|
||||
}
|
||||
|
||||
if (!staffId && sessionData.loginStaffId) {
|
||||
staffId = sessionData.loginStaffId;
|
||||
}
|
||||
if (!staffName && sessionData.privilege) {
|
||||
staffName = sessionData.privilege;
|
||||
}
|
||||
} catch (err) {
|
||||
throw new AuthenticationError(`凭证校验失败,请检查 token 是否已过期: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
|
||||
// 兜底 staffId:若依然为空,退化为 corpId:admin
|
||||
if (!staffId) {
|
||||
staffId = `${corpId}:admin`;
|
||||
}
|
||||
|
||||
// 3. 自动或显式提取 OpenAPI 密钥实现持久化提权 (appKey + appSecurity)
|
||||
let resolvedAppKey = params.appKey;
|
||||
let resolvedAppSecurity = params.appSecurity;
|
||||
|
||||
if ((!resolvedAppKey || !resolvedAppSecurity) && params.elevate !== false && params.autoElevate !== false) {
|
||||
if (params.elevate === true || params.keyId || (params.appKey && !params.appSecurity)) {
|
||||
const keys = await fetchOpenApiKeysBySession({
|
||||
baseUrl,
|
||||
corpId,
|
||||
staffId,
|
||||
accessToken,
|
||||
});
|
||||
const selected = selectOpenApiKey(keys, corpId, {
|
||||
appKey: params.appKey,
|
||||
keyId: params.keyId,
|
||||
force: params.force,
|
||||
});
|
||||
resolvedAppKey = selected.appKey;
|
||||
resolvedAppSecurity = selected.appSecurity;
|
||||
} else {
|
||||
// 默认最佳努力自动提权:若当前身份可读取 OpenAPI 密钥则自动挂载持久化
|
||||
try {
|
||||
const keys = await fetchOpenApiKeysBySession({
|
||||
baseUrl,
|
||||
corpId,
|
||||
staffId,
|
||||
accessToken,
|
||||
});
|
||||
if (keys.length > 0) {
|
||||
const picked = keys.find((k) => k.active !== false) ?? keys[0];
|
||||
if (picked) {
|
||||
resolvedAppKey = picked.appKey;
|
||||
resolvedAppSecurity = picked.appSecurity;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 无权限或未开通开放平台时静默降级为普通会话
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 智能判断语义化凭证来源与集群环境
|
||||
let source: CredentialSource = params.source || "curl";
|
||||
if (!params.source) {
|
||||
if (sessionData?.isAssistPlatform || sessionData?.platform === "ASSIST") {
|
||||
source = "assist";
|
||||
}
|
||||
}
|
||||
|
||||
const cluster = params.cluster || resolveCorpCluster({ cluster: params.cluster, baseUrl });
|
||||
|
||||
// 5. 计算 Token 过期时间戳 (ms)
|
||||
let expiresAt: number | undefined;
|
||||
if (sessionData?.expTime && sessionData.expTime > 0) {
|
||||
expiresAt = sessionData.expTime;
|
||||
} else if (jwtExpMs && jwtExpMs > 0) {
|
||||
expiresAt = jwtExpMs;
|
||||
} else if (requestedExpiresAt) {
|
||||
expiresAt = requestedExpiresAt;
|
||||
}
|
||||
|
||||
const corpConfig: CorpConfig = {
|
||||
id: corpId,
|
||||
name: corpName || `企业-${corpId}`,
|
||||
baseUrl,
|
||||
cluster,
|
||||
source,
|
||||
staffName,
|
||||
credentials: {
|
||||
accessToken,
|
||||
corpId,
|
||||
staffId,
|
||||
...(resolvedAppKey && resolvedAppSecurity
|
||||
? {
|
||||
appKey: resolvedAppKey,
|
||||
appSecurity: resolvedAppSecurity,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
auth: {
|
||||
refreshTtl: 300,
|
||||
expiresAt,
|
||||
},
|
||||
session: {
|
||||
platform: sessionData?.platform,
|
||||
isAssistPlatform: sessionData?.isAssistPlatform,
|
||||
isShortTermToken: sessionData?.isShortTermToken,
|
||||
assistId: sessionData?.assistId,
|
||||
operationUserId: sessionData?.operationUserId,
|
||||
operationUserName: sessionData?.operationUserName,
|
||||
staffName,
|
||||
cellphone,
|
||||
isAdmin,
|
||||
deviceType: sessionData?.deviceType,
|
||||
loginAccountType: sessionData?.loginAccountType,
|
||||
loginTime: sessionData?.loginTime,
|
||||
expTime: expiresAt || sessionData?.expTime,
|
||||
sourceChannel,
|
||||
},
|
||||
};
|
||||
|
||||
saveCorpConfig(corpConfig, params.enterprisesDir);
|
||||
return corpConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接通过第三方协助/免密链接 (thirdparty.html / assistance link) 一键导入企业
|
||||
*/
|
||||
export async function importFromLink(
|
||||
linkUrl: string,
|
||||
options: ImportFromLinkOptions = {}
|
||||
): Promise<CorpConfig> {
|
||||
const parsed = parseHeadersOrCurl(linkUrl);
|
||||
const accessToken = parsed.accessToken;
|
||||
const corpId = parsed.corpId;
|
||||
const baseUrl = options.baseUrl || parsed.baseUrl || DEFAULT_EKB_BASE_URL;
|
||||
|
||||
if (!accessToken) {
|
||||
throw new AuthenticationError("未能从提供的链接中提取到 accessToken 参数");
|
||||
}
|
||||
if (!corpId) {
|
||||
throw new AuthenticationError("未能从提供的链接中提取到 ekbCorpId 或 corpId 参数");
|
||||
}
|
||||
|
||||
return await importCredentials({
|
||||
accessToken,
|
||||
corpId,
|
||||
staffId: parsed.staffId,
|
||||
name: options.name,
|
||||
baseUrl,
|
||||
enterprisesDir: options.enterprisesDir,
|
||||
overwrite: options.overwrite,
|
||||
source: "link",
|
||||
ttl: options.ttl,
|
||||
expires: options.expires,
|
||||
appKey: options.appKey,
|
||||
appSecurity: options.appSecurity,
|
||||
keyId: options.keyId,
|
||||
elevate: options.elevate,
|
||||
autoElevate: options.autoElevate,
|
||||
force: options.force,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 从协助链接提取 OpenAPI 密钥列表(可选保存为持久化企业配置)
|
||||
*/
|
||||
export async function extractOpenApiKeysFromLink(
|
||||
linkUrl: string,
|
||||
options: {
|
||||
save?: boolean;
|
||||
name?: string;
|
||||
overwrite?: boolean;
|
||||
force?: boolean;
|
||||
appKey?: string;
|
||||
keyId?: string;
|
||||
enterprisesDir?: string;
|
||||
} = {}
|
||||
): Promise<{
|
||||
corpId: string;
|
||||
corpName?: string;
|
||||
baseUrl: string;
|
||||
staffId: string;
|
||||
keys: HoseOpenApiKeyItem[];
|
||||
selectedKey?: HoseOpenApiKeyItem;
|
||||
savedCorp?: CorpConfig;
|
||||
}> {
|
||||
const parsed = parseHeadersOrCurl(linkUrl);
|
||||
const accessToken = parsed.accessToken;
|
||||
const corpId = parsed.corpId;
|
||||
const baseUrl = parsed.baseUrl || DEFAULT_EKB_BASE_URL;
|
||||
|
||||
if (!accessToken || !corpId) {
|
||||
throw new AuthenticationError("无效的合思协助链接:缺少 accessToken 或 ekbCorpId 参数");
|
||||
}
|
||||
|
||||
let staffId = parsed.staffId;
|
||||
let corpName = options.name;
|
||||
|
||||
try {
|
||||
const jwtRes = await ky
|
||||
.get(`${baseUrl}/api/engine/realm/$UNITY/actions/jwt`, {
|
||||
searchParams: { corpId },
|
||||
headers: { accesstoken: accessToken, corpid: corpId },
|
||||
})
|
||||
.json<{ id?: string; value?: string }>();
|
||||
const token = jwtRes.id || jwtRes.value;
|
||||
if (token) {
|
||||
const parts = token.split(".");
|
||||
if (parts.length >= 2) {
|
||||
const payload = JSON.parse(Buffer.from(parts[1]!, "base64").toString("utf-8"));
|
||||
if (!staffId && payload.staffId) staffId = payload.staffId;
|
||||
if (!corpName && payload.corporationName) corpName = payload.corporationName;
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
|
||||
if (!staffId) staffId = `${corpId}:admin`;
|
||||
|
||||
const keys = await fetchOpenApiKeysBySession({
|
||||
baseUrl,
|
||||
corpId,
|
||||
staffId,
|
||||
accessToken,
|
||||
});
|
||||
|
||||
if (!options.save) {
|
||||
return { corpId, corpName, baseUrl, staffId, keys };
|
||||
}
|
||||
|
||||
const selectedKey = selectOpenApiKey(keys, corpId, {
|
||||
appKey: options.appKey,
|
||||
keyId: options.keyId,
|
||||
force: options.force,
|
||||
});
|
||||
|
||||
const savedCorp = await importCredentials({
|
||||
accessToken,
|
||||
corpId,
|
||||
staffId,
|
||||
name: corpName,
|
||||
baseUrl,
|
||||
overwrite: options.overwrite ?? true,
|
||||
source: "link",
|
||||
enterprisesDir: options.enterprisesDir,
|
||||
appKey: selectedKey.appKey,
|
||||
appSecurity: selectedKey.appSecurity,
|
||||
autoElevate: false,
|
||||
});
|
||||
|
||||
return {
|
||||
corpId,
|
||||
corpName: savedCorp.name,
|
||||
baseUrl,
|
||||
staffId: savedCorp.credentials.staffId,
|
||||
keys,
|
||||
selectedKey,
|
||||
savedCorp,
|
||||
};
|
||||
}
|
||||
|
||||
// 保持历史命名兼容
|
||||
export const importF12Credentials = importCredentials;
|
||||
+18
-1648
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,523 @@
|
||||
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
import { CorpConfig, CorpConfigSchema } from "../config/types.js";
|
||||
import { saveCorpConfig, resolveWritableEnterprisesDir } from "../config/loader.js";
|
||||
import { resolveCorpCluster } from "../http/unity-client.js";
|
||||
import {
|
||||
DEFAULT_EKB_BASE_URL,
|
||||
HoseOpenApiKeyItem,
|
||||
canRefreshCorpAccessToken,
|
||||
fetchHoseOpenApiAccessToken,
|
||||
fetchHoseProvisionalAuth,
|
||||
fetchHoseRoleDefGroups,
|
||||
fetchHoseRoleStaffs,
|
||||
fetchHoseStaffDetails,
|
||||
fetchOpenApiKeysBySession,
|
||||
formatBeijingIso,
|
||||
getCorpOpenApiCredentials,
|
||||
hasOpenApiPersistentCredentials,
|
||||
normalizeBaseUrl,
|
||||
probeHoseDomain,
|
||||
selectOpenApiKey,
|
||||
} from "./openapi-v1.js";
|
||||
import {
|
||||
importCredentials,
|
||||
invalidateCorpSubdomainTokenCaches,
|
||||
parseExpiresInSeconds,
|
||||
} from "./link-import.js";
|
||||
import { refreshSingleCorpAccessToken } from "./login.js";
|
||||
|
||||
export interface OnboardHosePersistentParams {
|
||||
id?: string;
|
||||
name?: string;
|
||||
appKey: string;
|
||||
appSecurity: string;
|
||||
domain?: string;
|
||||
baseUrl?: string;
|
||||
corpId?: string;
|
||||
staffId?: string;
|
||||
staffName?: string;
|
||||
staffPhone?: string;
|
||||
role?: string;
|
||||
force?: boolean;
|
||||
overwrite?: boolean;
|
||||
enterprisesDir?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过开放平台持久化密钥 (appKey + appSecurity) 自动探测域名、管理员并导入企业配置
|
||||
*/
|
||||
export async function onboardHosePersistent(
|
||||
input: OnboardHosePersistentParams
|
||||
): Promise<CorpConfig> {
|
||||
const explicitDomain = input.domain || input.baseUrl;
|
||||
const probe = await probeHoseDomain(input.appKey, input.appSecurity, explicitDomain);
|
||||
const domain = probe.domain;
|
||||
const corpId = input.corpId || probe.corpId;
|
||||
let corpName = input.name || probe.corpName;
|
||||
let staffId = input.staffId;
|
||||
let staffName = input.staffName;
|
||||
|
||||
const targetDir = input.enterprisesDir || resolveWritableEnterprisesDir();
|
||||
const targetFile = join(targetDir, `${input.id || corpId}.json`);
|
||||
if (input.overwrite === false && existsSync(targetFile)) {
|
||||
throw new AuthenticationError(`企业 [${input.id || corpId}] 配置文件已存在。若要更新覆盖,请附加 --overwrite 参数。`);
|
||||
}
|
||||
|
||||
if (!staffId) {
|
||||
const roleQuery = input.role ?? "admin";
|
||||
const roleGroups = await fetchHoseRoleDefGroups(domain, probe.openapiToken).catch(() => []);
|
||||
let targetRoleId: string | undefined;
|
||||
for (const group of roleGroups) {
|
||||
for (const role of group.roleDefs) {
|
||||
if (role.id.endsWith(`:${roleQuery}`) || role.name === roleQuery || role.id === roleQuery) {
|
||||
targetRoleId = role.id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (targetRoleId) break;
|
||||
}
|
||||
if (!targetRoleId) {
|
||||
targetRoleId = roleGroups
|
||||
.find((group) => group.roleDefs.some((role) => role.id.endsWith(":admin")))
|
||||
?.roleDefs.find((role) => role.id.endsWith(":admin"))?.id;
|
||||
}
|
||||
|
||||
if (targetRoleId) {
|
||||
const roleStaffs = await fetchHoseRoleStaffs(domain, probe.openapiToken, targetRoleId).catch(() => ({ staffs: [] }));
|
||||
const staffDetails = await fetchHoseStaffDetails(domain, probe.openapiToken, roleStaffs.staffs).catch(() => []);
|
||||
if (input.staffName || input.staffPhone) {
|
||||
const matches = staffDetails.filter((staff) => {
|
||||
if (input.staffName && staff.name !== input.staffName && !staff.name.includes(input.staffName)) return false;
|
||||
if (input.staffPhone && (!staff.cellphone || !staff.cellphone.includes(input.staffPhone))) return false;
|
||||
return true;
|
||||
});
|
||||
if (matches.length === 1 && matches[0]) {
|
||||
staffId = matches[0].id;
|
||||
staffName = matches[0].name;
|
||||
} else if (matches.length > 1) {
|
||||
throw new AuthenticationError(
|
||||
`匹配到多位管理员候选人 (${matches.map((s) => `${s.name}[${s.id}]`).join(", ")}),请通过 --staff-id 精确指定。`
|
||||
);
|
||||
} else {
|
||||
throw new AuthenticationError(
|
||||
`未找到匹配 '${input.staffName ?? input.staffPhone}' 的管理员,请检查姓名/手机号或显式指定 --staff-id。`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
const activeStaffs = staffDetails.filter((s) => s.active);
|
||||
if (staffDetails.length === 1 && staffDetails[0]) {
|
||||
staffId = staffDetails[0].id;
|
||||
staffName = staffDetails[0].name;
|
||||
} else if (activeStaffs.length === 1 && activeStaffs[0]) {
|
||||
staffId = activeStaffs[0].id;
|
||||
staffName = activeStaffs[0].name;
|
||||
} else if (input.force && (activeStaffs[0] || staffDetails[0])) {
|
||||
const picked = activeStaffs[0] ?? staffDetails[0]!;
|
||||
staffId = picked.id;
|
||||
staffName = picked.name;
|
||||
} else if (staffDetails.length > 1) {
|
||||
const candidates = staffDetails.map((s) => ({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
cellphone: s.cellphone ? s.cellphone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2") : undefined,
|
||||
active: s.active,
|
||||
}));
|
||||
throw new AuthenticationError(
|
||||
`检测到多位主管理员候选人,请通过 --staff-id、--staff-name 指定,或追加 --force 自动选择第一位在职管理员: ${JSON.stringify(candidates)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!staffId) {
|
||||
throw new AuthenticationError(
|
||||
"缺少员工工号 (staffId),且未能从主管理员角色自动发现,请通过 --staff-id 显式指定。"
|
||||
);
|
||||
}
|
||||
|
||||
const normalizedStaffId = staffId.includes(":") ? staffId : `${corpId}:${staffId}`;
|
||||
|
||||
// 使用 getProvisionalAuth 签发初始会话并走 importCredentials 完整探测企业全称与 Session 元数据
|
||||
const provisional = await fetchHoseProvisionalAuth({
|
||||
baseUrl: domain,
|
||||
openapiToken: probe.openapiToken,
|
||||
corpId,
|
||||
staffId: normalizedStaffId,
|
||||
expiresIn: 7200,
|
||||
});
|
||||
|
||||
const imported = await importCredentials({
|
||||
accessToken: provisional.token,
|
||||
corpId,
|
||||
staffId: normalizedStaffId,
|
||||
name: corpName,
|
||||
baseUrl: domain,
|
||||
source: "openapi",
|
||||
enterprisesDir: input.enterprisesDir,
|
||||
overwrite: true,
|
||||
appKey: input.appKey,
|
||||
appSecurity: input.appSecurity,
|
||||
autoElevate: false,
|
||||
});
|
||||
|
||||
if (staffName && !imported.staffName) {
|
||||
imported.staffName = staffName;
|
||||
saveCorpConfig(imported, input.enterprisesDir);
|
||||
}
|
||||
|
||||
return imported;
|
||||
}
|
||||
|
||||
export interface SyncFromSealUseOptions {
|
||||
filter?: string;
|
||||
sealEnterprisesDir?: string;
|
||||
enterprisesDir?: string;
|
||||
verify?: boolean;
|
||||
overwrite?: boolean;
|
||||
}
|
||||
|
||||
export interface SyncFromSealUseItemResult {
|
||||
corpId: string;
|
||||
name: string;
|
||||
appKey: string;
|
||||
domain: string;
|
||||
staffId: string;
|
||||
action: "merged" | "created" | "skipped";
|
||||
}
|
||||
|
||||
export async function syncOpenApiFromSealUse(
|
||||
options: SyncFromSealUseOptions = {}
|
||||
): Promise<{
|
||||
sealDir: string;
|
||||
targetDir: string;
|
||||
items: SyncFromSealUseItemResult[];
|
||||
}> {
|
||||
const sealDir =
|
||||
options.sealEnterprisesDir ||
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR?.trim() ||
|
||||
join(homedir(), ".config", "seal-use", "enterprises");
|
||||
const targetDir = options.enterprisesDir || resolveWritableEnterprisesDir();
|
||||
|
||||
if (!existsSync(sealDir)) {
|
||||
throw new AuthenticationError(`未找到 seal-use 企业配置目录: ${sealDir}`);
|
||||
}
|
||||
|
||||
const files = readdirSync(sealDir).filter((f) => f.endsWith(".json") && !f.startsWith("example."));
|
||||
const kw = options.filter?.trim().toLowerCase();
|
||||
const items: SyncFromSealUseItemResult[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
try {
|
||||
const raw = JSON.parse(readFileSync(join(sealDir, file), "utf-8"));
|
||||
const sourceObj = raw?.source?.hose || raw?.source || raw?.hose;
|
||||
const appKey = sourceObj?.appKey;
|
||||
const appSecurity = sourceObj?.appSecurity;
|
||||
if (!appKey || !appSecurity) continue;
|
||||
|
||||
const corpId: string = sourceObj.corpId || raw.id;
|
||||
const sealName: string = raw.name || corpId;
|
||||
const domain = normalizeBaseUrl(sourceObj.domain || DEFAULT_EKB_BASE_URL);
|
||||
const rawStaffId: string = sourceObj.staffId || `${corpId}:admin`;
|
||||
const staffId = rawStaffId.includes(":") ? rawStaffId : `${corpId}:${rawStaffId}`;
|
||||
|
||||
if (kw) {
|
||||
const matched =
|
||||
corpId.toLowerCase().includes(kw) ||
|
||||
sealName.toLowerCase().includes(kw) ||
|
||||
String(raw.id || "").toLowerCase().includes(kw);
|
||||
if (!matched) continue;
|
||||
}
|
||||
|
||||
const targetPath = join(targetDir, `${corpId}.json`);
|
||||
if (existsSync(targetPath)) {
|
||||
const existing = CorpConfigSchema.parse(JSON.parse(readFileSync(targetPath, "utf-8")));
|
||||
if (hasOpenApiPersistentCredentials(existing) && options.overwrite === false) {
|
||||
items.push({
|
||||
corpId,
|
||||
name: existing.name,
|
||||
appKey: existing.credentials.appKey || appKey,
|
||||
domain: existing.baseUrl || domain,
|
||||
staffId: existing.credentials.staffId,
|
||||
action: "skipped",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
existing.credentials.appKey = appKey;
|
||||
existing.credentials.appSecurity = appSecurity;
|
||||
if (!existing.baseUrl) existing.baseUrl = domain;
|
||||
if (!existing.credentials.staffId) existing.credentials.staffId = staffId;
|
||||
if (options.verify) {
|
||||
await refreshSingleCorpAccessToken(existing);
|
||||
} else {
|
||||
saveCorpConfig(existing, targetDir);
|
||||
}
|
||||
items.push({
|
||||
corpId,
|
||||
name: existing.name,
|
||||
appKey,
|
||||
domain: existing.baseUrl || domain,
|
||||
staffId: existing.credentials.staffId,
|
||||
action: "merged",
|
||||
});
|
||||
} else {
|
||||
let createdConfig: CorpConfig | null = null;
|
||||
if (options.verify) {
|
||||
try {
|
||||
createdConfig = await onboardHosePersistent({
|
||||
id: corpId,
|
||||
name: sealName,
|
||||
appKey,
|
||||
appSecurity,
|
||||
domain,
|
||||
corpId,
|
||||
staffId,
|
||||
overwrite: true,
|
||||
enterprisesDir: targetDir,
|
||||
});
|
||||
} catch {
|
||||
// fallback to saving raw OpenAPI credentials below
|
||||
}
|
||||
}
|
||||
if (!createdConfig) {
|
||||
createdConfig = {
|
||||
id: corpId,
|
||||
name: sealName,
|
||||
corpId,
|
||||
staffId,
|
||||
source: "openapi",
|
||||
baseUrl: domain,
|
||||
cluster: resolveCorpCluster({ baseUrl: domain }),
|
||||
credentials: {
|
||||
accessToken: "",
|
||||
corpId,
|
||||
staffId,
|
||||
appKey,
|
||||
appSecurity,
|
||||
},
|
||||
auth: {
|
||||
refreshTtl: 300,
|
||||
},
|
||||
};
|
||||
saveCorpConfig(createdConfig, targetDir);
|
||||
}
|
||||
items.push({
|
||||
corpId,
|
||||
name: createdConfig.name,
|
||||
appKey,
|
||||
domain: createdConfig.baseUrl || domain,
|
||||
staffId: createdConfig.credentials.staffId,
|
||||
action: "created",
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// ignore invalid file
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
sealDir,
|
||||
targetDir,
|
||||
items,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 为已配置企业提取并持久化 OpenAPI 密钥
|
||||
*/
|
||||
export async function elevateCorpWithOpenApiKey(
|
||||
corp: CorpConfig,
|
||||
options: {
|
||||
appKey?: string;
|
||||
keyId?: string;
|
||||
force?: boolean;
|
||||
silent?: boolean;
|
||||
enterprisesDir?: string;
|
||||
} = {}
|
||||
): Promise<HoseOpenApiKeyItem | undefined> {
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const staffId = corp.staffId || corp.credentials.staffId;
|
||||
const baseUrl = corp.baseUrl || DEFAULT_EKB_BASE_URL;
|
||||
|
||||
try {
|
||||
const ttlMs = (corp.auth?.refreshTtl || 300) * 1000;
|
||||
const expMs = corp.auth?.expiresAt || corp.session?.expTime;
|
||||
if (canRefreshCorpAccessToken(corp) && (!corp.credentials.accessToken || (expMs && Date.now() >= expMs - ttlMs))) {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
}
|
||||
|
||||
const keys = await fetchOpenApiKeysBySession({
|
||||
baseUrl,
|
||||
corpId,
|
||||
staffId,
|
||||
accessToken: corp.credentials.accessToken,
|
||||
}).catch(async (err) => {
|
||||
if (canRefreshCorpAccessToken(corp)) {
|
||||
const refreshed = await refreshSingleCorpAccessToken(corp);
|
||||
if (refreshed) {
|
||||
return fetchOpenApiKeysBySession({
|
||||
baseUrl,
|
||||
corpId,
|
||||
staffId,
|
||||
accessToken: corp.credentials.accessToken,
|
||||
});
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
|
||||
if (keys.length === 0) {
|
||||
if (options.silent) return undefined;
|
||||
throw new AuthenticationError(`企业 [${corp.name}] 暂未创建 OpenAPI 密钥`);
|
||||
}
|
||||
const selected = selectOpenApiKey(keys, corpId, {
|
||||
appKey: options.appKey,
|
||||
keyId: options.keyId,
|
||||
force: options.force ?? options.silent,
|
||||
});
|
||||
corp.credentials.appKey = selected.appKey;
|
||||
corp.credentials.appSecurity = selected.appSecurity;
|
||||
saveCorpConfig(corp, options.enterprisesDir);
|
||||
return selected;
|
||||
} catch (err) {
|
||||
if (options.silent) return undefined;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成指定企业的合思 Web 免密登录直达链接 (thirdparty.html)
|
||||
* 优先走 OpenAPI getProvisionalAuth 签发独立授权链接;若无 OpenAPI 密钥则尝试自动提权,最后回退当前有效会话 Token。
|
||||
*/
|
||||
export async function getCorpProvisionalAuthLink(
|
||||
corp: CorpConfig,
|
||||
options: {
|
||||
expiresIn?: number | string;
|
||||
ttl?: number | string;
|
||||
pageType?: string;
|
||||
force?: boolean;
|
||||
syncLocalSession?: boolean;
|
||||
enterprisesDir?: string;
|
||||
} = {}
|
||||
): Promise<{
|
||||
corpId: string;
|
||||
corpName: string;
|
||||
staffId: string;
|
||||
staffName?: string;
|
||||
url: string;
|
||||
token: string;
|
||||
expiresIn: number;
|
||||
expiresAt: string;
|
||||
persistent: boolean;
|
||||
method: "provisional-openapi" | "session-token";
|
||||
}> {
|
||||
const explicitDuration = options.expiresIn ?? options.ttl;
|
||||
const expiresIn = parseExpiresInSeconds(explicitDuration, 7200);
|
||||
const pageType = options.pageType || "home";
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const staffId = corp.staffId || corp.credentials.staffId;
|
||||
const baseUrl = normalizeBaseUrl(corp.baseUrl || DEFAULT_EKB_BASE_URL);
|
||||
|
||||
// 1. 若尚未配置 appKey/appSecurity,先确保会话有效并尝试自动提权提取密钥
|
||||
if (!hasOpenApiPersistentCredentials(corp)) {
|
||||
const ttlMs = (corp.auth?.refreshTtl || 300) * 1000;
|
||||
const expMs = corp.auth?.expiresAt || corp.session?.expTime;
|
||||
if (canRefreshCorpAccessToken(corp) && (!corp.credentials.accessToken || (expMs && Date.now() >= expMs - ttlMs))) {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
}
|
||||
if (corp.credentials.accessToken) {
|
||||
await elevateCorpWithOpenApiKey(corp, { silent: true, force: true, enterprisesDir: options.enterprisesDir });
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 若具备 OpenAPI 持久化密钥,直接走 getProvisionalAuth 签发标准免密链接
|
||||
const openApiCreds = getCorpOpenApiCredentials(corp);
|
||||
if (openApiCreds) {
|
||||
const openapiToken = await fetchHoseOpenApiAccessToken({
|
||||
appKey: openApiCreds.appKey,
|
||||
appSecurity: openApiCreds.appSecurity,
|
||||
baseUrl,
|
||||
forceRefresh: options.force,
|
||||
});
|
||||
const provisional = await fetchHoseProvisionalAuth({
|
||||
baseUrl,
|
||||
openapiToken,
|
||||
corpId,
|
||||
staffId,
|
||||
expiresIn,
|
||||
pageType,
|
||||
});
|
||||
|
||||
if (options.syncLocalSession !== false) {
|
||||
corp.credentials.accessToken = provisional.token;
|
||||
if (!corp.auth) corp.auth = { refreshTtl: 300 };
|
||||
corp.auth.expiresAt = provisional.expiresAt;
|
||||
if (corp.session) {
|
||||
corp.session.expTime = provisional.expiresAt;
|
||||
}
|
||||
saveCorpConfig(corp, options.enterprisesDir);
|
||||
invalidateCorpSubdomainTokenCaches(corp);
|
||||
}
|
||||
|
||||
return {
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
staffId: provisional.uid,
|
||||
staffName: corp.staffName || corp.session?.staffName || undefined,
|
||||
url: provisional.url,
|
||||
token: provisional.token,
|
||||
expiresIn: provisional.expiresIn,
|
||||
expiresAt: formatBeijingIso(provisional.expiresAt),
|
||||
persistent: true,
|
||||
method: "provisional-openapi",
|
||||
};
|
||||
}
|
||||
|
||||
// 3. 回退路径:无 OpenAPI 密钥时,使用主账号或现有有效 Session Token 拼装免密链接
|
||||
if (!corp.credentials.accessToken) {
|
||||
throw new AuthenticationError(
|
||||
`企业 [${corp.name}] 缺少可用访问令牌且未配置 OpenAPI 持久化密钥,请重新登录或导入链接。`
|
||||
);
|
||||
}
|
||||
|
||||
const expMs =
|
||||
explicitDuration !== undefined
|
||||
? Date.now() + expiresIn * 1000
|
||||
: corp.auth?.expiresAt || corp.session?.expTime || Date.now() + expiresIn * 1000;
|
||||
if (expMs <= Date.now() && !canRefreshCorpAccessToken(corp)) {
|
||||
throw new AuthenticationError(
|
||||
`企业 [${corp.name}] 临时凭证已过期且未配置持久化密钥,请使用 hose-use corps add-link 重新导入。`
|
||||
);
|
||||
}
|
||||
|
||||
if (explicitDuration !== undefined && options.syncLocalSession !== false) {
|
||||
if (!corp.auth) corp.auth = { refreshTtl: 300 };
|
||||
corp.auth.expiresAt = expMs;
|
||||
if (corp.session) {
|
||||
corp.session.expTime = expMs;
|
||||
}
|
||||
saveCorpConfig(corp, options.enterprisesDir);
|
||||
}
|
||||
|
||||
const url = `${baseUrl}/web/thirdparty.html?accessToken=${encodeURIComponent(
|
||||
corp.credentials.accessToken
|
||||
)}&ekbCorpId=${encodeURIComponent(corpId)}&pageType=${encodeURIComponent(
|
||||
pageType
|
||||
)}&overdueTokenRedirect=&noPathCache=true`;
|
||||
|
||||
return {
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
staffId,
|
||||
staffName: corp.staffName || corp.session?.staffName || undefined,
|
||||
url,
|
||||
token: corp.credentials.accessToken,
|
||||
expiresIn: Math.max(1, Math.round((expMs - Date.now()) / 1000)),
|
||||
expiresAt: formatBeijingIso(expMs),
|
||||
persistent: canRefreshCorpAccessToken(corp),
|
||||
method: "session-token",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
import ky from "ky";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
import { CorpConfig } from "../config/types.js";
|
||||
|
||||
export const DEFAULT_EKB_BASE_URL = "https://app.ekuaibao.com";
|
||||
|
||||
export const HOSE_STANDARD_DOMAINS = [
|
||||
"https://app.ekuaibao.com",
|
||||
"https://dd2.hosecloud.com",
|
||||
"https://wx2.ekuaibao.com",
|
||||
"https://kdcloud2.ekuaibao.com",
|
||||
"https://ddenterprise.ekuaibao.com",
|
||||
"https://feishu.ekuaibao.com",
|
||||
] as const;
|
||||
|
||||
export function normalizeBaseUrl(url: string): string {
|
||||
return url.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
export function formatBeijingIso(timestampMs: number): string {
|
||||
const shanghaiMs = timestampMs + 8 * 60 * 60 * 1000;
|
||||
const iso = new Date(shanghaiMs).toISOString();
|
||||
return `${iso.slice(0, 19)}+08:00`;
|
||||
}
|
||||
|
||||
export function maskOpenApiSecurity(secret: string): string {
|
||||
if (!secret) return "-";
|
||||
if (secret.length <= 12) return "******";
|
||||
return `${secret.slice(0, 8)}...${secret.slice(-4)}`;
|
||||
}
|
||||
|
||||
export function getCorpOpenApiCredentials(
|
||||
corp?: CorpConfig | null
|
||||
): { appKey: string; appSecurity: string } | undefined {
|
||||
if (!corp) return undefined;
|
||||
const appKey = corp.credentials?.appKey || corp.auth?.appKey;
|
||||
const appSecurity = corp.credentials?.appSecurity || corp.auth?.appSecurity;
|
||||
if (appKey && appSecurity) {
|
||||
return { appKey, appSecurity };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function hasOpenApiPersistentCredentials(corp?: CorpConfig | null): boolean {
|
||||
return Boolean(getCorpOpenApiCredentials(corp));
|
||||
}
|
||||
|
||||
export function canRefreshCorpAccessToken(corp?: CorpConfig | null): boolean {
|
||||
if (!corp) return false;
|
||||
if (hasOpenApiPersistentCredentials(corp)) {
|
||||
return true;
|
||||
}
|
||||
return corp.source === "account" && !corp.session?.isShortTermToken && Boolean(corp.accountId);
|
||||
}
|
||||
|
||||
// ── OpenAPI v1 持久凭据换票、免密链接签发与提权 ──────────────────────────────
|
||||
|
||||
export interface HoseOpenApiKeyItem {
|
||||
id: string;
|
||||
name?: string;
|
||||
appKey: string;
|
||||
appSecurity: string;
|
||||
active: boolean;
|
||||
corporationId?: string;
|
||||
createTime?: number;
|
||||
updateTime?: number;
|
||||
}
|
||||
|
||||
export interface HoseProbeDomainResult {
|
||||
domain: string;
|
||||
corpId: string;
|
||||
corpName?: string;
|
||||
openapiToken: string;
|
||||
expireTime?: number;
|
||||
}
|
||||
|
||||
export interface HoseRoleDef {
|
||||
id: string;
|
||||
name: string;
|
||||
enName?: string | null;
|
||||
sourceType?: string;
|
||||
sourceTypeValue?: string | null;
|
||||
groupId?: string;
|
||||
groupName?: string;
|
||||
}
|
||||
|
||||
export interface HoseRoleDefGroup {
|
||||
id: string;
|
||||
name: string;
|
||||
enName?: string | null;
|
||||
roleDefs: HoseRoleDef[];
|
||||
}
|
||||
|
||||
export interface HoseStaffDetail {
|
||||
id: string;
|
||||
name: string;
|
||||
nickName?: string | null;
|
||||
code?: string;
|
||||
departments?: string[];
|
||||
defaultDepartment?: string;
|
||||
cellphone?: string;
|
||||
active: boolean;
|
||||
userId?: string;
|
||||
email?: string | null;
|
||||
showEmail?: string | null;
|
||||
external?: boolean;
|
||||
authState?: boolean;
|
||||
}
|
||||
|
||||
const openapiV1TokenCache = new Map<string, { token: string; expiresAt: number }>();
|
||||
const openapiV1TokenInflight = new Map<string, Promise<string>>();
|
||||
|
||||
export async function fetchHoseOpenApiAccessToken(params: {
|
||||
appKey: string;
|
||||
appSecurity: string;
|
||||
baseUrl?: string;
|
||||
forceRefresh?: boolean;
|
||||
}): Promise<string> {
|
||||
const baseUrl = normalizeBaseUrl(params.baseUrl || DEFAULT_EKB_BASE_URL);
|
||||
const cacheKey = `${params.appKey}@${baseUrl}`;
|
||||
|
||||
if (!params.forceRefresh) {
|
||||
const cached = openapiV1TokenCache.get(cacheKey);
|
||||
if (cached && Date.now() < cached.expiresAt - 60_000) {
|
||||
return cached.token;
|
||||
}
|
||||
const inflight = openapiV1TokenInflight.get(cacheKey);
|
||||
if (inflight) return inflight;
|
||||
}
|
||||
|
||||
const req = (async () => {
|
||||
const res = await ky
|
||||
.post(`${baseUrl}/api/openapi/v1/auth/getAccessToken`, {
|
||||
json: {
|
||||
appKey: params.appKey,
|
||||
appSecurity: params.appSecurity,
|
||||
},
|
||||
timeout: 15000,
|
||||
})
|
||||
.json<{
|
||||
value?: {
|
||||
accessToken?: string;
|
||||
corporationId?: string;
|
||||
expireTime?: number;
|
||||
errorCode?: number;
|
||||
errorMessage?: string;
|
||||
};
|
||||
accessToken?: string;
|
||||
token?: string;
|
||||
}>();
|
||||
|
||||
if (res.value?.errorCode) {
|
||||
throw new AuthenticationError(
|
||||
res.value.errorMessage || `OpenAPI 换票失败 (errorCode: ${res.value.errorCode})`
|
||||
);
|
||||
}
|
||||
|
||||
const token = res.value?.accessToken ?? res.accessToken ?? res.token;
|
||||
if (!token) {
|
||||
throw new AuthenticationError("合思 OpenAPI getAccessToken 未返回有效 accessToken");
|
||||
}
|
||||
|
||||
openapiV1TokenCache.set(cacheKey, {
|
||||
token,
|
||||
expiresAt: Date.now() + 3600 * 1000,
|
||||
});
|
||||
return token;
|
||||
})().finally(() => {
|
||||
openapiV1TokenInflight.delete(cacheKey);
|
||||
});
|
||||
|
||||
openapiV1TokenInflight.set(cacheKey, req);
|
||||
return req;
|
||||
}
|
||||
|
||||
export async function fetchHoseProvisionalAuth(params: {
|
||||
baseUrl?: string;
|
||||
openapiToken: string;
|
||||
corpId: string;
|
||||
staffId: string;
|
||||
expiresIn?: number;
|
||||
pageType?: string;
|
||||
}): Promise<{
|
||||
url: string;
|
||||
token: string;
|
||||
uid: string;
|
||||
expiresIn: number;
|
||||
expiresAt: number;
|
||||
}> {
|
||||
const baseUrl = normalizeBaseUrl(params.baseUrl || DEFAULT_EKB_BASE_URL);
|
||||
const expiresIn = params.expiresIn && params.expiresIn > 0 ? params.expiresIn : 7200;
|
||||
const pageType = params.pageType || "home";
|
||||
const uid = params.staffId.includes(":")
|
||||
? params.staffId
|
||||
: `${params.corpId}:${params.staffId}`;
|
||||
|
||||
const response = await ky
|
||||
.post(`${baseUrl}/api/openapi/v1.1/provisional/getProvisionalAuth`, {
|
||||
searchParams: {
|
||||
accessToken: params.openapiToken,
|
||||
},
|
||||
json: {
|
||||
uid,
|
||||
pageType,
|
||||
expireDate: expiresIn,
|
||||
},
|
||||
timeout: 15000,
|
||||
})
|
||||
.json<{ value?: { message?: string } }>();
|
||||
|
||||
const url = response.value?.message;
|
||||
if (!url) {
|
||||
throw new AuthenticationError("合思 getProvisionalAuth 未返回免密授权链接");
|
||||
}
|
||||
|
||||
const token = new URL(url).searchParams.get("accessToken");
|
||||
if (!token) {
|
||||
throw new AuthenticationError("合思免密授权链接缺少 accessToken 参数");
|
||||
}
|
||||
|
||||
return {
|
||||
url,
|
||||
token,
|
||||
uid,
|
||||
expiresIn,
|
||||
expiresAt: Date.now() + expiresIn * 1000,
|
||||
};
|
||||
}
|
||||
|
||||
export async function fetchOpenApiKeysBySession(params: {
|
||||
baseUrl?: string;
|
||||
corpId: string;
|
||||
staffId?: string;
|
||||
accessToken: string;
|
||||
}): Promise<HoseOpenApiKeyItem[]> {
|
||||
const baseUrl = normalizeBaseUrl(params.baseUrl || DEFAULT_EKB_BASE_URL);
|
||||
const staffId = params.staffId || `${params.corpId}:admin`;
|
||||
const response = await ky
|
||||
.get(`${baseUrl}/api/innerapi/v1/key`, {
|
||||
searchParams: { corpId: params.corpId },
|
||||
headers: {
|
||||
accesstoken: params.accessToken,
|
||||
corpid: params.corpId,
|
||||
staffid: staffId,
|
||||
},
|
||||
timeout: 15000,
|
||||
})
|
||||
.json<{ items?: unknown[] }>();
|
||||
|
||||
const rawItems = response.items ?? [];
|
||||
const keys: HoseOpenApiKeyItem[] = [];
|
||||
for (const raw of rawItems) {
|
||||
if (typeof raw === "object" && raw !== null) {
|
||||
const item = raw as Record<string, unknown>;
|
||||
if (typeof item.appKey === "string" && typeof item.appSecurity === "string") {
|
||||
keys.push({
|
||||
id: String(item.id ?? item.appKey),
|
||||
name: typeof item.name === "string" ? item.name : undefined,
|
||||
appKey: item.appKey,
|
||||
appSecurity: item.appSecurity,
|
||||
active: typeof item.active === "boolean" ? item.active : true,
|
||||
corporationId: typeof item.corporationId === "string" ? item.corporationId : params.corpId,
|
||||
createTime: typeof item.createTime === "number" ? item.createTime : undefined,
|
||||
updateTime: typeof item.updateTime === "number" ? item.updateTime : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
export function selectOpenApiKey(
|
||||
keys: HoseOpenApiKeyItem[],
|
||||
corpId: string,
|
||||
selection: { appKey?: string; keyId?: string; force?: boolean } = {}
|
||||
): HoseOpenApiKeyItem {
|
||||
if (keys.length === 0) {
|
||||
throw new AuthenticationError(
|
||||
`未能从企业 [${corpId}] 中提取到 OpenAPI 密钥凭据。请确认该企业在合思开放平台已创建应用密钥,且当前员工具有管理员权限。`
|
||||
);
|
||||
}
|
||||
if (selection.keyId || selection.appKey) {
|
||||
const matched = keys.find(
|
||||
(k) =>
|
||||
(selection.keyId && k.id === selection.keyId) ||
|
||||
(selection.appKey && k.appKey === selection.appKey)
|
||||
);
|
||||
if (!matched) {
|
||||
const candidates = keys
|
||||
.map((k) => ` • "${k.name || "未命名应用"}" (appKey: ${k.appKey}, keyId: ${k.id}, 状态: ${k.active ? "🟢 启用" : "⚪ 停用"})`)
|
||||
.join("\n");
|
||||
throw new AuthenticationError(
|
||||
`指定的合思密钥不存在,请从候选列表中选择正确的 --app-key 或 --key-id:\n${candidates}`
|
||||
);
|
||||
}
|
||||
return matched;
|
||||
}
|
||||
const activeKeys = keys.filter((k) => k.active !== false);
|
||||
if (keys.length === 1) return keys[0]!;
|
||||
if (activeKeys.length === 1) return activeKeys[0]!;
|
||||
if (selection.force) {
|
||||
return activeKeys[0] ?? keys[0]!;
|
||||
}
|
||||
const candidates = keys
|
||||
.map(
|
||||
(k, idx) =>
|
||||
` [${idx + 1}] "${k.name || "未命名应用"}" (appKey: ${k.appKey}, keyId: ${k.id}, 状态: ${k.active ? "🟢 启用" : "⚪ 停用"})`
|
||||
)
|
||||
.join("\n");
|
||||
throw new AuthenticationError(
|
||||
`企业 [${corpId}] 存在多套 (${keys.length} 套) OpenAPI 应用密钥凭据:\n${candidates}\n请通过 --app-key <key> 或 --key-id <id> 显式指定,或追加 --force 自动选用第一套启用密钥。`
|
||||
);
|
||||
}
|
||||
|
||||
export async function probeHoseDomain(
|
||||
appKey: string,
|
||||
appSecurity: string,
|
||||
explicitDomain?: string
|
||||
): Promise<HoseProbeDomainResult> {
|
||||
if (explicitDomain) {
|
||||
const normalized = normalizeBaseUrl(explicitDomain);
|
||||
const result = await testSingleHoseDomain(normalized, appKey, appSecurity);
|
||||
if (!result) {
|
||||
throw new AuthenticationError(
|
||||
`在指定域名 ${normalized} 上校验 OpenAPI 凭据失败,请检查 appKey/appSecurity 与域名连通性。`
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const results = await Promise.all(
|
||||
HOSE_STANDARD_DOMAINS.map((domain) =>
|
||||
testSingleHoseDomain(domain, appKey, appSecurity).catch(() => undefined)
|
||||
)
|
||||
);
|
||||
const matched = results.find((item): item is HoseProbeDomainResult => Boolean(item));
|
||||
if (matched) return matched;
|
||||
|
||||
throw new AuthenticationError(
|
||||
`在全部 6 个标准合思域名 (${HOSE_STANDARD_DOMAINS.join(", ")}) 上均未能通过 appKey/appSecurity 鉴权。若为私有化或独立域名,请通过 --domain 显式指定。`
|
||||
);
|
||||
}
|
||||
|
||||
async function testSingleHoseDomain(
|
||||
domain: string,
|
||||
appKey: string,
|
||||
appSecurity: string
|
||||
): Promise<HoseProbeDomainResult | undefined> {
|
||||
try {
|
||||
const response = await fetch(`${domain}/api/openapi/v1/auth/getAccessToken`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ appKey, appSecurity }),
|
||||
signal: AbortSignal.timeout(8000),
|
||||
});
|
||||
if (!response.ok) return undefined;
|
||||
const data = (await response.json()) as {
|
||||
value?: {
|
||||
accessToken?: string;
|
||||
corporationId?: string;
|
||||
corporation?: { id?: string; name?: string };
|
||||
expireTime?: number;
|
||||
errorCode?: number;
|
||||
};
|
||||
accessToken?: string;
|
||||
};
|
||||
if (data.value?.errorCode) return undefined;
|
||||
const openapiToken = data.value?.accessToken ?? data.accessToken;
|
||||
const corpId = data.value?.corporationId ?? data.value?.corporation?.id;
|
||||
if (!openapiToken || !corpId) return undefined;
|
||||
return {
|
||||
domain,
|
||||
corpId,
|
||||
corpName: data.value?.corporation?.name,
|
||||
openapiToken,
|
||||
expireTime: data.value?.expireTime,
|
||||
};
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchHoseRoleDefGroups(
|
||||
domain: string,
|
||||
openapiToken: string
|
||||
): Promise<HoseRoleDefGroup[]> {
|
||||
const url = `${normalizeBaseUrl(domain)}/api/openapi/v1/roleDefGroups?accessToken=${encodeURIComponent(openapiToken)}`;
|
||||
const response = await fetch(url, {
|
||||
headers: { "content-type": "application/json", Accept: "application/json" },
|
||||
signal: AbortSignal.timeout(10000),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const text = await response.text().catch(() => "");
|
||||
throw new AuthenticationError(`获取合思角色定义组失败: ${response.status} ${text}`);
|
||||
}
|
||||
const json = (await response.json()) as {
|
||||
items?: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
enName?: string | null;
|
||||
roleDefs?: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
enName?: string | null;
|
||||
sourceType?: string;
|
||||
sourceTypeValue?: string | null;
|
||||
}>;
|
||||
}>;
|
||||
};
|
||||
return (json.items ?? []).map((g) => ({
|
||||
id: g.id,
|
||||
name: g.name,
|
||||
enName: g.enName,
|
||||
roleDefs: (g.roleDefs ?? []).map((r) => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
enName: r.enName,
|
||||
sourceType: r.sourceType,
|
||||
sourceTypeValue: r.sourceTypeValue,
|
||||
groupId: g.id,
|
||||
groupName: g.name,
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function fetchHoseRoleStaffs(
|
||||
domain: string,
|
||||
openapiToken: string,
|
||||
roledefId: string,
|
||||
staffBy = "id"
|
||||
): Promise<{ id: string; name: string; count: number; staffs: string[] }> {
|
||||
const cleanId = roledefId.startsWith("$") ? roledefId.slice(1) : roledefId;
|
||||
const url = `${normalizeBaseUrl(domain)}/api/openapi/v1/roledefs/$${cleanId}?accessToken=${encodeURIComponent(openapiToken)}&staffBy=${encodeURIComponent(staffBy)}&pathType=name`;
|
||||
const response = await fetch(url, {
|
||||
headers: { "content-type": "application/json", Accept: "application/json" },
|
||||
signal: AbortSignal.timeout(10000),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const text = await response.text().catch(() => "");
|
||||
throw new AuthenticationError(`获取角色成员失败 (${cleanId}): ${response.status} ${text}`);
|
||||
}
|
||||
const json = (await response.json()) as {
|
||||
value?: {
|
||||
id: string;
|
||||
name: string;
|
||||
count?: number;
|
||||
contents?: Array<{ staffs?: string[] }>;
|
||||
};
|
||||
};
|
||||
const val = json.value;
|
||||
if (!val) throw new AuthenticationError(`角色成员查询返回为空 (${cleanId})`);
|
||||
const allStaffs: string[] = [];
|
||||
for (const c of val.contents ?? []) {
|
||||
for (const s of c.staffs ?? []) {
|
||||
if (s && !allStaffs.includes(s)) allStaffs.push(s);
|
||||
}
|
||||
}
|
||||
return {
|
||||
id: val.id ?? cleanId,
|
||||
name: val.name ?? "",
|
||||
count: val.count ?? allStaffs.length,
|
||||
staffs: allStaffs,
|
||||
};
|
||||
}
|
||||
|
||||
export async function fetchHoseStaffDetails(
|
||||
domain: string,
|
||||
openapiToken: string,
|
||||
staffIds: string[]
|
||||
): Promise<HoseStaffDetail[]> {
|
||||
if (staffIds.length === 0) return [];
|
||||
const url = `${normalizeBaseUrl(domain)}/api/openapi/v1/staffs/getStaffIds?accessToken=${encodeURIComponent(openapiToken)}`;
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", Accept: "application/json" },
|
||||
body: JSON.stringify({
|
||||
type: "STAFFID",
|
||||
conditionIds: staffIds.slice(0, 100),
|
||||
}),
|
||||
signal: AbortSignal.timeout(10000),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const text = await response.text().catch(() => "");
|
||||
throw new AuthenticationError(`获取合思员工详情失败: ${response.status} ${text}`);
|
||||
}
|
||||
const json = (await response.json()) as { items?: HoseStaffDetail[] };
|
||||
return json.items ?? [];
|
||||
}
|
||||
|
||||
export async function listHoseStaffsByOpenApi(input: {
|
||||
appKey: string;
|
||||
appSecurity: string;
|
||||
domain?: string;
|
||||
role?: string;
|
||||
roleDefId?: string;
|
||||
}) {
|
||||
const probe = await probeHoseDomain(input.appKey, input.appSecurity, input.domain);
|
||||
const roleQuery = input.role ?? input.roleDefId ?? "admin";
|
||||
const roleGroups = await fetchHoseRoleDefGroups(probe.domain, probe.openapiToken);
|
||||
let targetRoleDefId: string | undefined;
|
||||
let targetRoleName: string | undefined;
|
||||
|
||||
for (const group of roleGroups) {
|
||||
for (const role of group.roleDefs) {
|
||||
if (role.id === roleQuery || role.id === `${probe.corpId}:${roleQuery}`) {
|
||||
targetRoleDefId = role.id;
|
||||
targetRoleName = role.name;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (targetRoleDefId) break;
|
||||
}
|
||||
|
||||
if (!targetRoleDefId && (roleQuery === "admin" || roleQuery === "主管理员")) {
|
||||
for (const group of roleGroups) {
|
||||
for (const role of group.roleDefs) {
|
||||
if (role.id.endsWith(":admin") || role.name === "主管理员") {
|
||||
targetRoleDefId = role.id;
|
||||
targetRoleName = role.name;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (targetRoleDefId) break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!targetRoleDefId) {
|
||||
for (const group of roleGroups) {
|
||||
for (const role of group.roleDefs) {
|
||||
if (role.name.toLowerCase().includes(roleQuery.toLowerCase())) {
|
||||
targetRoleDefId = role.id;
|
||||
targetRoleName = role.name;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (targetRoleDefId) break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!targetRoleDefId) {
|
||||
throw new AuthenticationError(`未找到匹配 '${roleQuery}' 的角色定义`);
|
||||
}
|
||||
|
||||
const roleStaffs = await fetchHoseRoleStaffs(probe.domain, probe.openapiToken, targetRoleDefId);
|
||||
const staffs = await fetchHoseStaffDetails(probe.domain, probe.openapiToken, roleStaffs.staffs);
|
||||
return {
|
||||
domain: probe.domain,
|
||||
corpId: probe.corpId,
|
||||
corpName: probe.corpName ?? probe.corpId,
|
||||
roleId: targetRoleDefId,
|
||||
roleName: targetRoleName,
|
||||
staffs,
|
||||
};
|
||||
}
|
||||
@@ -12,7 +12,11 @@ export const PRIMARY_TOKEN_CACHE_PATH = join(
|
||||
|
||||
export const TOKEN_CACHE_PATH = PRIMARY_TOKEN_CACHE_PATH;
|
||||
|
||||
function resolveTokenCachePath(): string {
|
||||
export function resolveTokenCachePath(): string {
|
||||
const envFile = process.env.HOSE_TOKENS_FILE?.trim();
|
||||
if (envFile) return envFile;
|
||||
const stateDir = process.env.HOSE_STATE_DIR?.trim();
|
||||
if (stateDir) return join(stateDir, "tokens.json");
|
||||
return PRIMARY_TOKEN_CACHE_PATH;
|
||||
}
|
||||
|
||||
@@ -28,9 +32,15 @@ function ensureDir(path: string): void {
|
||||
|
||||
let memoryTokenCache: TokenStore | null = null;
|
||||
let lastMtimeMs = 0;
|
||||
let lastResolvedPath = "";
|
||||
|
||||
export function loadTokenStore(): TokenStore {
|
||||
const filePath = resolveTokenCachePath();
|
||||
if (filePath !== lastResolvedPath) {
|
||||
memoryTokenCache = null;
|
||||
lastMtimeMs = 0;
|
||||
lastResolvedPath = filePath;
|
||||
}
|
||||
|
||||
if (existsSync(filePath)) {
|
||||
try {
|
||||
@@ -53,8 +63,9 @@ export function loadTokenStore(): TokenStore {
|
||||
}
|
||||
|
||||
export function saveTokenStore(store: TokenStore): void {
|
||||
const targetPath = resolveTokenCachePath();
|
||||
memoryTokenCache = store;
|
||||
const targetPath = PRIMARY_TOKEN_CACHE_PATH;
|
||||
lastResolvedPath = targetPath;
|
||||
ensureDir(targetPath);
|
||||
|
||||
// MAJ-03: 强制写入 0o600 保护敏感凭证
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
import { z } from "zod";
|
||||
import { CorpContext } from "../config/manager.js";
|
||||
import { createSessionClient } from "../http/session-client.js";
|
||||
|
||||
// ── 精简 MCP Auth Tools (其余复杂登录/刷新均由 CLI 直接提供) ───────────────────
|
||||
|
||||
export const authTools = [
|
||||
{
|
||||
name: "list_corps",
|
||||
description: "列出当前所有已配置的企业列表",
|
||||
parameters: z.object({}),
|
||||
handler: async ({ corpContext }: { corpContext: CorpContext }) => {
|
||||
return {
|
||||
activeCorp: corpContext.getCurrent()?.id,
|
||||
corporations: corpContext.listCorps(),
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "switch_corp",
|
||||
description: "切换当前活跃工作企业",
|
||||
parameters: z.object({
|
||||
corpId: z.string().describe("目标企业 ID"),
|
||||
}),
|
||||
handler: async (
|
||||
{ corpContext }: { corpContext: CorpContext },
|
||||
params: { corpId: string }
|
||||
) => {
|
||||
const success = corpContext.switchCorp(params.corpId);
|
||||
if (!success) {
|
||||
throw new Error(`企业 ${params.corpId} 不存在或未配置`);
|
||||
}
|
||||
const current = corpContext.getCurrent();
|
||||
return {
|
||||
success: true,
|
||||
message: `已切换到企业: ${current?.name} (${current?.id})`,
|
||||
corp: current,
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "whoami",
|
||||
description: "查看当前操作员身份、当前活跃企业与账号状态",
|
||||
parameters: z.object({}),
|
||||
handler: async ({ corpContext }: { corpContext: CorpContext }) => {
|
||||
const current = corpContext.getCurrent();
|
||||
if (!current) {
|
||||
return {
|
||||
authenticated: false,
|
||||
message: "未配置任何企业,请先运行 hose-use auth login",
|
||||
};
|
||||
}
|
||||
|
||||
let sessionValid = false;
|
||||
let sessionData: unknown = null;
|
||||
try {
|
||||
const client = await createSessionClient(current);
|
||||
const res = await client.get("api/account/v2/session").json<{ value?: unknown }>();
|
||||
sessionData = res.value;
|
||||
sessionValid = !!res.value;
|
||||
} catch {
|
||||
sessionValid = false;
|
||||
}
|
||||
|
||||
return {
|
||||
authenticated: sessionValid,
|
||||
currentCorp: {
|
||||
id: current.id,
|
||||
name: current.name,
|
||||
staffId: current.credentials.staffId,
|
||||
source: current.source,
|
||||
accountId: current.accountId,
|
||||
baseUrl: current.baseUrl,
|
||||
},
|
||||
session: sessionData,
|
||||
};
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -11,11 +11,18 @@ export const CorpTokensSchema = z.object({
|
||||
unityJwt: z.string(),
|
||||
easToken: z.string(),
|
||||
expiresAt: z.number(),
|
||||
sourceAccessToken: z.string().optional(),
|
||||
}).optional(),
|
||||
unity: z.object({
|
||||
unityJwt: z.string(),
|
||||
expiresAt: z.number(),
|
||||
sourceAccessToken: z.string().optional(),
|
||||
}).optional(),
|
||||
piper: z.object({
|
||||
hoseToken: z.string(),
|
||||
easJwt: z.string(),
|
||||
expiresAt: z.number(),
|
||||
sourceAccessToken: z.string().optional(),
|
||||
}).optional(),
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync, utimesSync } from "node:fs";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync, statSync, utimesSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
syncLegacyEnterprisesDir,
|
||||
syncLegacyGlobalConfig,
|
||||
} from "./loader.js";
|
||||
import { saveAccount, loadAccountStore, resolveAccountCachePath } from "../auth/account-store.js";
|
||||
import type { CorpConfig } from "./types.js";
|
||||
|
||||
describe("core/config/loader", () => {
|
||||
@@ -213,4 +214,30 @@ describe("core/config/loader", () => {
|
||||
expect(JSON.parse(readFileSync(primary, "utf8")).stateful).toBe(false);
|
||||
expect(existsSync(legacy)).toBe(false);
|
||||
});
|
||||
|
||||
test("saveCorpConfig and saveAccount enforce 0o600 file permissions and respect HOSE_ACCOUNTS_FILE", () => {
|
||||
const targetDir = join(tempDir, "secure-corps");
|
||||
const corpFile = saveCorpConfig(createMockCorp("sec-1", "安全测试企业"), targetDir);
|
||||
if (process.platform !== "win32") {
|
||||
expect(statSync(corpFile).mode & 0o777).toBe(0o600);
|
||||
}
|
||||
|
||||
const customAccountsFile = join(tempDir, "secure-accounts", "accounts.json");
|
||||
process.env.HOSE_ACCOUNTS_FILE = customAccountsFile;
|
||||
expect(resolveAccountCachePath()).toBe(customAccountsFile);
|
||||
|
||||
saveAccount({
|
||||
accountId: "86-13800138000",
|
||||
cloudAuthToken: "secret-cloud-token",
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
corporations: [],
|
||||
});
|
||||
|
||||
expect(existsSync(customAccountsFile)).toBe(true);
|
||||
if (process.platform !== "win32") {
|
||||
expect(statSync(customAccountsFile).mode & 0o777).toBe(0o600);
|
||||
}
|
||||
expect(loadAccountStore().accounts["86-13800138000"]?.cloudAuthToken).toBe("secret-cloud-token");
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
|
||||
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema, normalizeCorpConfig } from "./types.js";
|
||||
|
||||
const CONFIG_ENV = "HOSE_ENTERPRISES_DIR";
|
||||
const USER_DIR_ENV = "HOSE_USER_ENTERPRISES_DIR";
|
||||
@@ -17,7 +17,18 @@ export const LEGACY_GLOBAL_CONFIG_FILE = join(homedir(), ".cache", "ekb-mcp", "c
|
||||
const LEGACY_CLEANUP_GRACE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
function ensureDir(dir: string): void {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
try {
|
||||
chmodSync(dir, 0o700);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function writeSecureFile(filePath: string, content: string): void {
|
||||
ensureDir(dirname(filePath));
|
||||
writeFileSync(filePath, content, { encoding: "utf-8", mode: 0o600 });
|
||||
try {
|
||||
chmodSync(filePath, 0o600);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function resolveEnterprisesDirs(): string[] {
|
||||
@@ -165,8 +176,7 @@ export function saveGlobalConfig(config: Partial<GlobalConfig>): GlobalConfig {
|
||||
|
||||
const configured = process.env[GLOBAL_CONFIG_ENV]?.trim();
|
||||
const targetFile = configured || PRIMARY_GLOBAL_CONFIG_FILE;
|
||||
ensureDir(dirname(targetFile));
|
||||
writeFileSync(targetFile, JSON.stringify(updated, null, 2), "utf-8");
|
||||
writeSecureFile(targetFile, JSON.stringify(updated, null, 2));
|
||||
return updated;
|
||||
}
|
||||
|
||||
@@ -184,7 +194,7 @@ export function loadCorpConfigs(overrideDirs?: string[]): CorpConfig[] {
|
||||
try {
|
||||
const content = readFileSync(join(dir, file), "utf-8");
|
||||
const parsed = JSON.parse(content);
|
||||
const corp = CorpConfigSchema.parse(parsed);
|
||||
const corp = normalizeCorpConfig(CorpConfigSchema.parse(parsed));
|
||||
// 相同企业 ID 以先出现的为准(工作区优先于全局,全局优先于历史)
|
||||
if (!byId.has(corp.id)) {
|
||||
byId.set(corp.id, corp);
|
||||
@@ -228,9 +238,9 @@ export function saveCorpConfig(config: CorpConfig, dir?: string): string {
|
||||
// ignore malformed existing file
|
||||
}
|
||||
}
|
||||
const validated = CorpConfigSchema.parse(config);
|
||||
const validated = normalizeCorpConfig(CorpConfigSchema.parse(config));
|
||||
const filePath = join(targetDir, `${validated.id}.json`);
|
||||
writeFileSync(filePath, JSON.stringify(validated, null, 2), "utf-8");
|
||||
writeSecureFile(filePath, JSON.stringify(validated, null, 2));
|
||||
return filePath;
|
||||
}
|
||||
|
||||
|
||||
+16
-13
@@ -1,4 +1,11 @@
|
||||
import { CorpConfig, GlobalConfig } from "./types.js";
|
||||
import {
|
||||
CorpConfig,
|
||||
getCorpExpiresAt,
|
||||
getCorpPhysicalId,
|
||||
getCorpStaffId,
|
||||
getCorpStaffName,
|
||||
} from "./types.js";
|
||||
import { NotFoundError, NotLoggedInError, ValidationError } from "../errors.js";
|
||||
import { saveGlobalConfig } from "./loader.js";
|
||||
|
||||
export interface CorpSummary {
|
||||
@@ -35,18 +42,14 @@ export function resolveCorpConfig(
|
||||
let corp = corps.find((item) => item.id === selectedCorpId);
|
||||
// 2. 其次按企业物理 ID 匹配 (如 uzU7pcWfScck00)
|
||||
if (!corp) {
|
||||
corp = corps.find(
|
||||
(item) =>
|
||||
item.corpId === selectedCorpId ||
|
||||
item.credentials.corpId === selectedCorpId
|
||||
);
|
||||
corp = corps.find((item) => getCorpPhysicalId(item) === selectedCorpId);
|
||||
}
|
||||
if (corp) return corp;
|
||||
throw new Error(`未找到企业或身份标识为 [${selectedCorpId}] 的企业配置`);
|
||||
throw new NotFoundError(`未找到企业或身份标识为 [${selectedCorpId}] 的企业配置`);
|
||||
}
|
||||
|
||||
if (!options.stateful) {
|
||||
throw new Error(
|
||||
throw new ValidationError(
|
||||
"当前处于无状态模式 (Stateless Mode)。执行企业级操作必须显式指定 --corp <corpId>。\n" +
|
||||
"如需设置默认企业,可执行 `hose-use config mode stateful` 切换为有状态模式。"
|
||||
);
|
||||
@@ -56,7 +59,7 @@ export function resolveCorpConfig(
|
||||
if (firstCorp) return firstCorp;
|
||||
|
||||
const hintDirs = candidateDirs?.length ? ` (已检索路径: ${candidateDirs.join(", ")})` : "";
|
||||
throw new Error(`未找到任何企业配置。请先运行 'hose-use auth login' 登录或添加企业配置${hintDirs}。`);
|
||||
throw new NotLoggedInError(`未找到任何企业配置。请先运行 'hose-use auth login' 登录或添加企业配置${hintDirs}。`);
|
||||
}
|
||||
|
||||
export class CorpContext {
|
||||
@@ -160,14 +163,14 @@ export class CorpContext {
|
||||
return {
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
corpId: corp.corpId || corp.credentials.corpId,
|
||||
staffId: corp.credentials.staffId,
|
||||
staffName: corp.staffName || corp.session?.staffName || undefined,
|
||||
corpId: getCorpPhysicalId(corp),
|
||||
staffId: getCorpStaffId(corp),
|
||||
staffName: getCorpStaffName(corp),
|
||||
source: corp.source || "manual",
|
||||
accountId: corp.accountId,
|
||||
baseUrl: corp.baseUrl,
|
||||
current: corp.id === this.current?.id,
|
||||
expiresAt: corp.auth?.expiresAt || (corp.session?.expTime ?? undefined),
|
||||
expiresAt: getCorpExpiresAt(corp),
|
||||
persistent: hasOpenApiKeys || hasAccountBinding,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -66,6 +66,69 @@ export type CorpCredentials = z.infer<typeof CorpCredentialsSchema>;
|
||||
export type CorpAuthConfig = z.infer<typeof CorpAuthConfigSchema>;
|
||||
export type CorpConfig = z.infer<typeof CorpConfigSchema>;
|
||||
|
||||
/**
|
||||
* 获取企业真实物理 corpId(统一收敛 corp.corpId / corp.credentials.corpId / corp.id)
|
||||
*/
|
||||
export function getCorpPhysicalId(corp: CorpConfig): string {
|
||||
return corp.corpId || corp.credentials.corpId || corp.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取企业内当前员工工号 staffId(统一收敛 corp.credentials.staffId / corp.staffId)
|
||||
*/
|
||||
export function getCorpStaffId(corp: CorpConfig): string {
|
||||
return corp.credentials.staffId || corp.staffId || "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取企业内当前员工姓名(统一收敛 corp.staffName / corp.session?.staffName)
|
||||
*/
|
||||
export function getCorpStaffName(corp: CorpConfig): string | undefined {
|
||||
return corp.staffName || corp.session?.staffName || undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取凭证过期时间戳 ms(统一收敛 corp.auth?.expiresAt / corp.session?.expTime)
|
||||
*/
|
||||
export function getCorpExpiresAt(corp: CorpConfig): number | undefined {
|
||||
return corp.auth?.expiresAt || (corp.session?.expTime ?? undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化 CorpConfig 冗余字段,确保顶层与嵌套凭证/会话字段保持一致
|
||||
*/
|
||||
export function normalizeCorpConfig(corp: CorpConfig): CorpConfig {
|
||||
const physicalCorpId = getCorpPhysicalId(corp);
|
||||
const staffId = getCorpStaffId(corp);
|
||||
const staffName = getCorpStaffName(corp);
|
||||
const expiresAt = getCorpExpiresAt(corp);
|
||||
const appKey = corp.credentials?.appKey || corp.auth?.appKey;
|
||||
const appSecurity = corp.credentials?.appSecurity || corp.auth?.appSecurity;
|
||||
|
||||
return {
|
||||
...corp,
|
||||
corpId: physicalCorpId,
|
||||
...(staffId ? { staffId } : {}),
|
||||
...(staffName ? { staffName } : {}),
|
||||
credentials: {
|
||||
...corp.credentials,
|
||||
corpId: corp.credentials.corpId || physicalCorpId,
|
||||
staffId,
|
||||
...(appKey ? { appKey } : {}),
|
||||
...(appSecurity ? { appSecurity } : {}),
|
||||
},
|
||||
...(corp.auth || expiresAt
|
||||
? {
|
||||
auth: {
|
||||
refreshTtl: corp.auth?.refreshTtl ?? 300,
|
||||
...corp.auth,
|
||||
...(expiresAt ? { expiresAt } : {}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
// ── 全局运行配置(有状态/无状态模式)─────────────────────────────────────────
|
||||
|
||||
export const GlobalConfigSchema = z.object({
|
||||
@@ -79,3 +142,4 @@ export const GlobalConfigSchema = z.object({
|
||||
|
||||
export type GlobalConfig = z.infer<typeof GlobalConfigSchema>;
|
||||
|
||||
|
||||
@@ -37,6 +37,8 @@ describe("Core DB - 数据库连接与结构化迁移机制 (加固测试)", ()
|
||||
expect(tableNames.has("approval_findings")).toBe(true);
|
||||
expect(tableNames.has("aipro_logs")).toBe(true);
|
||||
expect(tableNames.has("cache_entries")).toBe(true);
|
||||
expect(tableNames.has("observed_events")).toBe(true);
|
||||
expect(tableNames.has("workflow_error_alerts")).toBe(true);
|
||||
|
||||
// 检查加固索引:UPPER(short_id)、findings(rule_id)
|
||||
const indices = db
|
||||
@@ -51,6 +53,8 @@ describe("Core DB - 数据库连接与结构化迁移机制 (加固测试)", ()
|
||||
expect(indexNames.has("idx_findings_rule_id")).toBe(true);
|
||||
expect(indexNames.has("idx_cache_namespace")).toBe(true);
|
||||
expect(indexNames.has("idx_cache_expires_at")).toBe(true);
|
||||
expect(indexNames.has("idx_observed_events_scope")).toBe(true);
|
||||
expect(indexNames.has("idx_workflow_alerts_scope")).toBe(true);
|
||||
});
|
||||
|
||||
test("cache_entries 具备复合主键 (namespace, key) 约束", () => {
|
||||
|
||||
@@ -184,6 +184,38 @@ export const migrations: DatabaseMigration[] = [
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
version: 3,
|
||||
name: "003_events_and_workflow_alerts_tables",
|
||||
up(db: Database): void {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS observed_events (
|
||||
scope_key TEXT NOT NULL,
|
||||
id TEXT NOT NULL,
|
||||
corp_id TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
observed_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (scope_key, id)
|
||||
);
|
||||
`);
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_observed_events_scope ON observed_events(scope_key, observed_at);");
|
||||
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS workflow_error_alerts (
|
||||
scope_key TEXT NOT NULL,
|
||||
id TEXT NOT NULL,
|
||||
pipeline_id TEXT NOT NULL,
|
||||
platform_id TEXT NOT NULL,
|
||||
pipeline_name TEXT,
|
||||
error_count INTEGER NOT NULL,
|
||||
state INTEGER NOT NULL DEFAULT 0,
|
||||
observed_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (scope_key, id)
|
||||
);
|
||||
`);
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_workflow_alerts_scope ON workflow_error_alerts(scope_key);");
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
function seedDefaultPreference(db: Database): void {
|
||||
|
||||
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user