Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ec08033e0 | ||
|
|
96c5a3f242 | ||
|
|
1d825269f4 | ||
|
|
3573ef71aa | ||
|
|
c18ff02386 | ||
|
|
64c0fafcf6 | ||
|
|
db2b256fcd | ||
|
|
aa5ec6b6ce | ||
|
|
8c444efc85 | ||
|
|
c72f07f582 | ||
|
|
edeb2a56f8 | ||
|
|
28eab40145 | ||
|
|
bcb77feabb | ||
|
|
7e16a6a312 | ||
|
|
d0f3d2738a | ||
|
|
29ac24248e | ||
|
|
aa69b50e6e | ||
|
|
1322e2eab9 | ||
|
|
139e50395d | ||
|
|
ca713cfafc | ||
|
|
4b75132b43 | ||
|
|
240ec92931 | ||
|
|
1855815aeb | ||
|
|
dd647b65a6 | ||
|
|
43595e2410 | ||
|
|
b08b99c45e | ||
|
|
7e4f218313 | ||
|
|
05569243ec | ||
|
|
ebed61d6b4 | ||
|
|
90e7ac22bb | ||
|
|
2ed9bf0236 | ||
|
|
0554f41d12 | ||
|
|
8e4535a812 | ||
|
|
68c7541cf6 | ||
|
|
134ebf0d2e | ||
|
|
5d441d9e90 | ||
|
|
3db5907357 | ||
|
|
b6551497d7 | ||
|
|
33db72f863 | ||
|
|
f26eae7b08 | ||
|
|
1571c524c1 | ||
|
|
3e072b490e | ||
|
|
7cfb68e434 | ||
|
|
d15fa65517 | ||
|
|
34983e1c07 | ||
|
|
a5c0146c8d | ||
|
|
45eb83a609 | ||
|
|
639aaa9271 |
No files matched your search
@@ -0,0 +1,60 @@
|
||||
# Agent Customizations & Modular Rules Policy
|
||||
|
||||
This directory (`.agents/`) maintains modular configuration, skills, and guidelines for AI coding assistants working in the `hose-use` repository.
|
||||
|
||||
---
|
||||
|
||||
## 1. Directory Structure
|
||||
|
||||
```
|
||||
.agents/
|
||||
├── README.md # This document: architecture & trigger policy
|
||||
├── skills.json # Declarative skill path and exclusion filters
|
||||
└── rules/ # Modular, domain-specific rule definitions (trigger: "manual")
|
||||
├── production-safety.md # 生产环境安全红线、免读源码与写操作防护原则
|
||||
├── cli-protocol.md # CLI stdout/stderr stream contract & exit codes
|
||||
├── tenant-and-credential.md # 多租户凭据管理、协助链接与单据检索最佳实践
|
||||
├── testing-and-dev-hygiene.md # 单元测试规范、非交互环境防护与发布流程
|
||||
└── typescript-style.md # ESM, explicit .js imports, and TypeScript styles
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Trigger Strategy & Context Budget Management
|
||||
|
||||
### Why `trigger: "manual"`?
|
||||
|
||||
In Antigravity (`agy`), rule files located in `.agents/rules/*.md` support YAML frontmatter:
|
||||
|
||||
```yaml
|
||||
---
|
||||
description: "..."
|
||||
globs: "src/..."
|
||||
trigger: "manual"
|
||||
---
|
||||
```
|
||||
|
||||
1. **Token Economy**: If set to `trigger: "always_on"`, every turn of the conversation unconditionally injects all rules into the system prompt (`<user_rules>`), consuming substantial context tokens on every request regardless of task relevance.
|
||||
2. **On-Demand Activation**: Setting `trigger: "manual"` prevents automatic background injection into the prompt budget. The rules remain available on-demand when explicitly referenced or requested by the user or agent.
|
||||
3. **Cross-Agent Neutrality**: Non-agy agents (e.g. OpenAI Codex, Claude Code, Cursor, generic LLMs) do not recognize `agy`'s private frontmatter triggers. Storing modular guidelines as plain Markdown with a manual trigger ensures they function as clean, standalone reference docs that any agent can read on demand via standard file reading tools without unexpected prompt pollution.
|
||||
|
||||
---
|
||||
|
||||
## 3. Modular Rules Inventory
|
||||
|
||||
| Rule File | Domain / Scope | Key Responsibilities |
|
||||
| :--- | :--- | :--- |
|
||||
| [`rules/production-safety.md`](./rules/production-safety.md) | 全局行为 | **生产安全最高红线**、严禁私自翻阅源码配置 (Zero Source-Reading)、两阶段确认写保护。 |
|
||||
| [`rules/tenant-and-credential.md`](./rules/tenant-and-credential.md) | 凭证与单据 | 同等凭据原则、协助链接导入与 `--overwrite` 保护、个人单据 (`task submitted` / `bill list --mine`) 快速通道。 |
|
||||
| [`rules/cli-protocol.md`](./rules/cli-protocol.md) | `src/cli/**/*.ts` | 严格 `stdout` JSON vs `stderr` 诊断输出契约、200KB 大报文防爆拦截、退出码规范。 |
|
||||
| [`rules/testing-and-dev-hygiene.md`](./rules/testing-and-dev-hygiene.md) | 测试与流程 | `bun:test` 规范、测试环境禁止阻塞交互输入、`bun run check` + `bun test` 门禁与发布更新规范。 |
|
||||
| [`rules/typescript-style.md`](./rules/typescript-style.md) | `src/**/*.ts` | ES Modules、强制携带 `.js` 后缀、Zod 运行时校验与代码规范。 |
|
||||
|
||||
---
|
||||
|
||||
## 4. Usage Instructions for AI Agents
|
||||
|
||||
- **Production Operations**: Always consult [`rules/production-safety.md`](./rules/production-safety.md) and [`rules/tenant-and-credential.md`](./rules/tenant-and-credential.md) before interacting with configured enterprise tenants.
|
||||
- **CLI Development**: When adding or refactoring CLI commands under `src/cli/`, consult [`rules/cli-protocol.md`](./rules/cli-protocol.md).
|
||||
- **Writing Tests**: When creating or modifying tests, consult [`rules/testing-and-dev-hygiene.md`](./rules/testing-and-dev-hygiene.md).
|
||||
- **TypeScript & Modules**: When adding new TypeScript files or resolving local imports, refer to [`rules/typescript-style.md`](./rules/typescript-style.md).
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
description: "CLI stdout/stderr stream contract, volume explosion protection, and exit codes for hose-use commands"
|
||||
globs: "src/cli/**/*.ts"
|
||||
trigger: "manual"
|
||||
---
|
||||
|
||||
# CLI 输出流协议与退出码规范
|
||||
|
||||
在实现或重构 `src/cli/` 下的命令行交互时:
|
||||
|
||||
1. **机器解析通道 (`stdout`)**:
|
||||
- 数据类命令在 `--json` 模式下,`stdout` 必须仅输出纯净、可解析的 JSON 结构体;
|
||||
- 严禁将调试日志、进度动画、交互式提示语输出到 `stdout`,确保下游脚本和 Agent Harness 能够直接可靠解析。
|
||||
|
||||
2. **诊断与引导通道 (`stderr`)**:
|
||||
- 运行时警告、网络诊断信息以及下一步操作引导(如 `下一步: hose-use ...`)统一写入 `stderr`。
|
||||
|
||||
3. **大报文体积保护(Volume Explosion Protection)**:
|
||||
- 默认受 200KB 体积防爆限制,防止海量单据明细一次性撑爆上下文;
|
||||
- 提示并支持通过 `--limit` 分页、`--output-file / -o` 直接落盘至本地文件,或通过 `--mine` 筛选关键子集。
|
||||
|
||||
4. **退出码规范**:
|
||||
- 正常执行成功退出码为 `0`;
|
||||
- 语法错误、参数缺失、上游 API 报错退出码为非 0(如 `1`);
|
||||
- 写操作未确认拦截退出码为 `10`(`MutationConfirmationRequired`);
|
||||
- 不要在领域代码深处直接调用 `process.exit()`,应抛出带有结构化语义的错误,由外层统一捕获和分配退出码。
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
description: "生产环境安全红线、免读源码(Zero Source-Reading)与写操作防护原则"
|
||||
globs: "**/*"
|
||||
trigger: "manual"
|
||||
---
|
||||
|
||||
# 生产环境安全与行为红线
|
||||
|
||||
在操作、排错或开发 `hose-use` 时,必须严格恪守以下生产安全与操作红线:
|
||||
|
||||
1. **生产环境安全第一(Production Safety First)**:
|
||||
- 企业租户(如“转转正式”、“钰泰半导体”等)多为生产真实业务环境,**严禁**未经用户明确确认擅自执行写操作(包括但不限于单据同意、驳回、转交、前/后加签、费用类型修改/停用、数据记录编辑等)。
|
||||
- 单据检索与排障默认仅使用只读查询(如 `probe`、`task submitted`、`bill list --mine`、`bill get`、`bill flow` 等)。
|
||||
|
||||
2. **零源码翻阅自省(Zero Source-Reading)**:
|
||||
- **严禁翻阅用户的本地配置文件、凭证快照(如 `~/.config/hose-use/enterprises/*.json`、`seal_tokens.json`)、SQLite 数据库或源码目录来探查企业和员工信息**。
|
||||
- 探查配置与上下文必须统一使用标准 CLI 命令(如 `hose-use context`、`hose-use corps list`、`hose-use probe`)。
|
||||
|
||||
3. **两阶段确认与写操作防护**:
|
||||
- 所有写操作必须严格遵循两阶段确认机制:
|
||||
- 第一阶段:使用 `--dry-run` 预览操作目标与变更明细;
|
||||
- 第二阶段:经用户明确确认后,追加 `--yes`(或 `--confirm`)执行写入。
|
||||
- 导入链接若检测到目标企业已存在,必须在第一阶段提示中直接给出带有 `--overwrite` 的命令,杜绝二次报错阻断。
|
||||
|
||||
4. **敏感信息与凭证脱敏**:
|
||||
- 严禁将明文密码、`appSecurity`、完整 `accessToken`、会话 Cookie 或第三方授权直链打印到公共日志、提交到代码仓库或在回复中裸露传播。
|
||||
- CLI 默认输出必须进行严格掩码脱敏。
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
description: "多租户凭据管理、合思免密/协助链接导入与个人单据检索最佳实践"
|
||||
globs: "src/{domains,core,cli}/**/*.{ts,md}"
|
||||
trigger: "manual"
|
||||
---
|
||||
|
||||
# 租户凭据与业务操作最佳实践
|
||||
|
||||
1. **同等凭据原则(Equal Credential Scope Principle)**:
|
||||
- 合思第三方免密/协助链接 (`https://.../web/thirdparty.html?...`) 与在合思管理员后台抓取的 cURL 在凭据范围上等价,均携带完整的 Web 前台会话权限(`accessToken` / `ekbCorpId`)。
|
||||
- 面对协助链接或 cURL 时,可通过 `corps add-link <url>` 直接导入或更新租户。
|
||||
|
||||
2. **协助链接导入与覆盖(add-link)**:
|
||||
- 导入协助链接时,系统会自动预解析 `ekbCorpId` 与 JWT Session。
|
||||
- 若本地已存在该企业配置,必须显式追加 `--overwrite` 参数(如 `hose-use corps add-link <url> --overwrite --yes`)。
|
||||
|
||||
3. **单据查询的业务分流与避坑**:
|
||||
- **查“我的单据” / 当前员工发起的单据**:
|
||||
- 优先使用 `hose-use task submitted` 或 `hose-use bill list --mine`;
|
||||
- 响应速度为秒级,包含完整表单明细、提交时间、审批状态与金额。
|
||||
- **查“待办任务”**:
|
||||
- 使用 `hose-use task todo`,支持分页与节点状态查看。
|
||||
- **全局发票大盘(`bill list`)**:
|
||||
- 底层调用全量账表接口 `/api/v2/invoice/search`;在像转转这样的大企业或发票量级巨大的租户中耗时较长,避免在无过滤条件时频繁调用;遇超时应引导使用轻量化的 `task submitted` / `bill list --mine`。
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
description: "测试套件规范、非交互环境防护与版本发布更新全流程"
|
||||
globs: "{src,scripts}/**/*.test.ts"
|
||||
trigger: "manual"
|
||||
---
|
||||
|
||||
# 测试与开发发布流程规范
|
||||
|
||||
1. **测试框架与单测编写**:
|
||||
- 统一采用 `bun:test`(`describe`, `test`, `it`, `expect`);
|
||||
- 测试文件与被测模块同级存放,命名为 `*.test.ts`;
|
||||
- 测试若修改了 `process.env` 或全局状态,必须在 `afterEach()` 中完成自愈清理。
|
||||
|
||||
2. **非交互测试环境防挂起**:
|
||||
- 包含终端输入提示(`prompt()` / `readline`)的命令逻辑中,必须加入 `process.env.NODE_ENV === "test"` 或 `process.env.CI` 保护,在单测环境下直接抛出确认错误,绝对禁止阻塞等待 stdin。
|
||||
|
||||
3. **提交前双重门禁验收**:
|
||||
- 任何代码改动在提交前必须 100% 通过以下检查:
|
||||
```bash
|
||||
bun run check # tsc --noEmit 静态类型检查零错误
|
||||
bun test # 完整测试套件全部通过
|
||||
```
|
||||
|
||||
4. **版本发布与全局更新标准流程**:
|
||||
- 若涉及功能增强、Bug 修复或结构变更:
|
||||
1. 运行 `bun run bump patch`(或 minor)同步各文件版本号并重建 bundles;
|
||||
2. 运行 `bun run check:version` 确认版本严格一致;
|
||||
3. 创建特性分支并提交 PR,合入 `main` 主分支;
|
||||
4. 双远端同步:推送 `main` 分支至 GitHub (`origin`) 与内部镜像 (`home`);
|
||||
5. 打正式发布 Tag(如 `v0.8.7`)并推送到双远端;
|
||||
6. 运行 `bun run dev:override` 重新构建本机全局二进制(`/opt/homebrew/bin/hose-use`)并同步 Agent Skill(`~/.agents/skills/hose-use`)。
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
description: "TypeScript and ESM coding conventions for hose-use codebase"
|
||||
globs: "src/**/*.ts"
|
||||
trigger: "manual"
|
||||
---
|
||||
|
||||
# TypeScript & ESM Conventions
|
||||
|
||||
When modifying or adding TypeScript files in `src/`:
|
||||
|
||||
1. **Module System & Import Extensions**:
|
||||
- Use ES modules exclusively (`"type": "module"` in `package.json`).
|
||||
- Local file imports MUST include explicit `.js` extensions (e.g. `import { getGlobalDb } from "../db/connection.js"`).
|
||||
- Do NOT omit the `.js` extension, or runtime Node/Bun ESM resolution will fail.
|
||||
|
||||
2. **Validation & Typing**:
|
||||
- Validate external inputs, environment variables, and external HTTP/JSON responses using Zod schemas or strictly typed models.
|
||||
- Avoid `any`. Prefer precise domain types defined in `src/domains/*/types.ts` or `src/types.ts`.
|
||||
- Never suppress type errors with `// @ts-ignore`; resolve type discrepancies cleanly.
|
||||
|
||||
3. **Code Style & Formatting**:
|
||||
- 2-space indentation.
|
||||
- Double quotes (`"`).
|
||||
- `camelCase` for functions and variables, `PascalCase` for classes, types, and interfaces.
|
||||
- Kebab-case filenames (e.g. `query-options.ts`, `task-service.ts`).
|
||||
|
||||
4. **Architecture & Separation of Concerns**:
|
||||
- `src/core/`: Database (SQLite), HTTP client factory, encryption, global configuration, logger.
|
||||
- `src/domains/`: Domain services, models, and business logic (e.g. `bill`, `corps`, `task`, `workflow`, `key-center`).
|
||||
- `src/cli/`: Command-line definitions, option parsing, user feedback, table rendering, exit handling.
|
||||
- Keep domain services independent of CLI formatting.
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"entries": [
|
||||
{
|
||||
"path": "~/.agents/skills",
|
||||
"exclude": [
|
||||
"^\\..*",
|
||||
".*-(deprecated|draft|backup|bak|old|test|tmp)$",
|
||||
"^lark.*",
|
||||
"^dingtalk.*",
|
||||
"^dws.*",
|
||||
"^seal.*",
|
||||
"^yingqing.*"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -113,7 +113,7 @@ jobs:
|
||||
local filename
|
||||
filename=$(basename "$file")
|
||||
echo " [start] Uploading ${filename} to Gitea..."
|
||||
RESP=$(curl -s -m 120 -w "\nHTTP_STATUS:%{http_code}" -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets?name=${filename}" \
|
||||
RESP=$(curl -s -m 600 -w "\nHTTP_STATUS:%{http_code}" -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/${RELEASE_ID}/assets?name=${filename}" \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-F "attachment=@${file}")
|
||||
STATUS=$(echo "$RESP" | tail -n 1)
|
||||
|
||||
@@ -46,5 +46,3 @@ data/
|
||||
|
||||
# Local roadmaps & scratch notes
|
||||
*.local.md
|
||||
.agents/
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.4",
|
||||
"version": "0.8.10",
|
||||
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
|
||||
"author": {
|
||||
"name": "yingqing"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# hose-use (v0.8.5)
|
||||
# hose-use (v0.8.10)
|
||||
|
||||
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
|
||||
|
||||
@@ -17,6 +17,19 @@ bun install
|
||||
bun run cli <command>
|
||||
```
|
||||
|
||||
### 方式三:将当前工作区安装为全局开发版
|
||||
|
||||
开发过程中需要让 PATH 中的 `hose-use` 立即使用当前源码时:
|
||||
|
||||
```bash
|
||||
bun run dev:override
|
||||
hose-use version
|
||||
```
|
||||
|
||||
该命令会构建本机二进制、原子替换全局 `hose-use`,同步 `~/.agents/skills/hose-use`,并保留 `hose-aipro` 别名;后台服务若正在运行会自动重启。开发构建会把 Git 信息编译进版本,例如 `hose-use v0.8.6-dev.1+gabc1234 [DEV BUILD]`,不会再与正式版混淆;`hose-use version --json` 还会返回 `channel`、`isRelease` 和 `git` 元数据。只预览动作可运行 `bun run dev:override -- --dry-run`。
|
||||
|
||||
> 开发版安装会覆盖当前 PATH 中的 `hose-use`,适合本机测试;发布环境请使用正式 Release 安装脚本。不要用 `npm install -g .` 代替,它会留下不会随源码更新的旧副本。
|
||||
|
||||
---
|
||||
|
||||
### CLI 常用命令速查 (`hose-use`)
|
||||
@@ -46,17 +59,19 @@ hose-use menu list # 查看桌面端全站一级主
|
||||
hose-use workflow list # 汇总查看全部工作流列表
|
||||
hose-use workflow get <pipelineId> # 获取工作流详情与节点结构
|
||||
hose-use workflow find --task=code-js2 # 搜索包含特定节点类型的工作流
|
||||
hose-use workflow toggle <pipelineId> --state=1 # 启用/停用工作流
|
||||
hose-use workflow save <pipelineId> --file=workflow.json # 按完整快照保存草稿
|
||||
hose-use workflow toggle <pipelineId> --state=1 --yes # 启用/停用工作流
|
||||
hose-use workflow save <pipelineId> --file=workflow.json --yes # 按完整快照保存草稿
|
||||
hose-use workflow patch <pipelineId> --file=workflow.json --path=tasks.0.code --value='return 2;' --output=patched.json
|
||||
hose-use workflow history <pipelineId> # 查看服务端版本快照历史
|
||||
hose-use workflow logs <pipelineId> --state=FAILED # 查看工作流运行错误日志
|
||||
hose-use workflow check --json --fail-on-alert # 检查错误管道并按错误计数去重提醒
|
||||
hose-use workflow publish <pipelineId> # 保存后的发布/启用
|
||||
hose-use workflow publish <pipelineId> --yes # 保存后的发布/启用
|
||||
hose-use platform list # 查看企业下所有启用的自建应用
|
||||
|
||||
# 5. 单据与费用明细管理 (DataLink 字典自动还原 & 200KB 防爆拦截)
|
||||
hose-use bill list # 查看当前企业单据与报销列表 (支持分页/阶段/状态过滤)
|
||||
hose-use bill list --keyword=打车 --search-fields=name,form # 跨字段复合检索单据名称与表单明细
|
||||
hose-use bill list --since=7d # 相对时间服务端极速索引过滤 (防大租户全量拉取超时)
|
||||
hose-use bill list --json -o /tmp/bills.json # 自动转储大报文至本地文件,防止打爆上下文
|
||||
hose-use bill list --json --full # 确需完整原始数据时跳过 200KB 限制
|
||||
hose-use bill get <单号|ID> # 根据单号或 ID 查询单据结构化详情
|
||||
@@ -94,7 +109,8 @@ hose-use mcp # 启动 MCP Server (默认暴露
|
||||
|
||||
### 模块化 Agent Skill 与 IDE 插件规范
|
||||
|
||||
- **多文件 Skill 模块体系**:知识体系划分至 `references/auth.md`、`references/bill.md`、`references/workflow.md`、`references/service.md`,执行 `hose-use skill install` 自动递归安装并支持环境自愈;
|
||||
- **多文件 Skill 模块体系**:知识体系划分至 `references/auth.md`、`references/bill.md`、`references/workflow.md`、`references/service.md`,执行 `hose-use skill install` 自动递归安装到统一的 `~/.agents/skills/hose-use`;如需安装到其他位置,必须显式使用 `--dir`;
|
||||
- **开发环境检查**:Git 工作树、分支、无引用提交、canonical Skill 与全局开发版可通过 `bun run dev:status`、`bun run dev:check` 检查;清理必须先 `bun run dev:clean --dry-run`,再追加 `--yes`;
|
||||
- **原生 IDE 插件规范支持**:内嵌 `.zcode-plugin/plugin.json` 与 `.mcp.json` 清单,支持标准 IDE 插件市场/本地插件直接载入,并在设置界面支持可视化切换 MCP 开关;
|
||||
- **MCP 单文件产物**:支持通过 `bun run build:plugin` 快速编译 Node.js 兼容的轻量单文件 `dist/mcp/server.js`。
|
||||
|
||||
|
||||
Vendored
+1015
-485
File diff suppressed because it is too large.
Load diff
Vendored
+1
-1
@@ -2,7 +2,7 @@
|
||||
"openapi": "3.1.0",
|
||||
"info": {
|
||||
"title": "hose-use API & MCP Tools Specification",
|
||||
"version": "0.8.4",
|
||||
"version": "0.8.10",
|
||||
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
|
||||
},
|
||||
"servers": [
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: hose-use API & MCP Tools Specification
|
||||
version: 0.8.4
|
||||
version: 0.8.10
|
||||
description: >-
|
||||
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
|
||||
servers:
|
||||
|
||||
+8
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hose-use",
|
||||
"version": "0.8.5",
|
||||
"version": "0.8.10",
|
||||
"module": "src/server.ts",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
@@ -15,11 +15,18 @@
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "bun test",
|
||||
"bump": "bun run scripts/bump-version.ts",
|
||||
"sync:release": "bun run scripts/bump-version.ts",
|
||||
"check:version": "bun run scripts/check-version-sync.ts",
|
||||
"openapi:bundle": "bun run scripts/bundle-openapi.ts",
|
||||
"openapi:generate-raw": "bun run scripts/generate-raw-openapi.ts",
|
||||
"openapi:all": "bun run scripts/generate-raw-openapi.ts && bun run scripts/bundle-openapi.ts",
|
||||
"build:binary": "node scripts/build-binary.mjs",
|
||||
"build:plugin": "node scripts/build-plugin.mjs",
|
||||
"dev:override": "bun run scripts/dev-override.ts",
|
||||
"dev:link": "bun run scripts/dev-override.ts",
|
||||
"dev:status": "bun run scripts/dev-hygiene.ts status",
|
||||
"dev:check": "bun run scripts/dev-hygiene.ts check",
|
||||
"dev:clean": "bun run scripts/dev-hygiene.ts clean",
|
||||
"dev": "bun run --watch src/server.ts",
|
||||
"start": "bun run src/server.ts",
|
||||
"export:workflow-schema": "bun run scripts/export-workflow-schema.ts"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mkdirSync, existsSync, unlinkSync, symlinkSync } from "node:fs";
|
||||
import { mkdirSync, readFileSync, existsSync, unlinkSync, symlinkSync } from "node:fs";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
@@ -17,20 +17,77 @@ const TARGET_MAP = {
|
||||
const args = process.argv.slice(2);
|
||||
const isAll = args.includes("--all") || args.includes("--matrix");
|
||||
const targetArg = args.find((arg) => arg.startsWith("--target="))?.replace("--target=", "");
|
||||
const isRelease = args.includes("--release") ||
|
||||
process.env.HOSE_BUILD_RELEASE === "1" ||
|
||||
(Boolean(process.env.CI) && process.env.GITHUB_REF_TYPE === "tag");
|
||||
|
||||
function getBuildInfo(releaseMode) {
|
||||
const pkg = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8"));
|
||||
if (releaseMode) return { version: pkg.version, channel: "release", isRelease: true };
|
||||
|
||||
try {
|
||||
const result = spawnSync("git", ["describe", "--tags", "--long", "--dirty", "--always"], { cwd: root, encoding: "utf8" });
|
||||
if (result.status === 0 && result.stdout) {
|
||||
const trimmed = result.stdout.trim();
|
||||
const dirty = trimmed.endsWith("-dirty");
|
||||
const clean = dirty ? trimmed.slice(0, -6) : trimmed;
|
||||
const longMatch = clean.match(/^v?(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?)-(\d+)-g([0-9a-f]+)$/);
|
||||
let baseVersion = pkg.version;
|
||||
let commitsAhead = 0;
|
||||
let commit = "";
|
||||
if (longMatch) {
|
||||
baseVersion = longMatch[1];
|
||||
commitsAhead = Number.parseInt(longMatch[2], 10);
|
||||
commit = longMatch[3];
|
||||
} else {
|
||||
const revision = spawnSync("git", ["rev-parse", "--short", "HEAD"], { cwd: root, encoding: "utf8" });
|
||||
if (revision.status === 0 && revision.stdout) commit = revision.stdout.trim();
|
||||
}
|
||||
const dirtySuffix = dirty ? ".dirty" : "";
|
||||
const commitSuffix = commit ? `+g${commit}${dirtySuffix}` : dirty ? "+dirty" : "";
|
||||
return {
|
||||
version: `${baseVersion}-dev.${commitsAhead}${commitSuffix}`,
|
||||
channel: "dev",
|
||||
isRelease: false,
|
||||
git: { baseVersion, commitsAhead, commit, dirty, describe: trimmed }
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// Fall back below if git is unavailable.
|
||||
}
|
||||
return { version: `${pkg.version}-dev.0+local`, channel: "dev", isRelease: false };
|
||||
}
|
||||
|
||||
const buildInfo = getBuildInfo(isRelease);
|
||||
const buildEnv = {
|
||||
...process.env,
|
||||
HOSE_BUILD_VERSION: buildInfo.version,
|
||||
HOSE_BUILD_CHANNEL: buildInfo.channel,
|
||||
HOSE_BUILD_IS_RELEASE: String(buildInfo.isRelease),
|
||||
...(buildInfo.git ? {
|
||||
HOSE_BUILD_GIT_BASE: buildInfo.git.baseVersion,
|
||||
HOSE_BUILD_GIT_COMMITS_AHEAD: String(buildInfo.git.commitsAhead),
|
||||
HOSE_BUILD_GIT_COMMIT: buildInfo.git.commit,
|
||||
HOSE_BUILD_GIT_DIRTY: String(buildInfo.git.dirty),
|
||||
HOSE_BUILD_GIT_DESCRIBE: buildInfo.git.describe
|
||||
} : {})
|
||||
};
|
||||
|
||||
console.log(`[build:binary] version: ${buildInfo.version} (${buildInfo.channel}, isRelease: ${buildInfo.isRelease})`);
|
||||
|
||||
if (isAll) {
|
||||
for (const [name, config] of Object.entries(TARGET_MAP)) {
|
||||
buildTarget(name, config.bunTarget, resolve(root, config.outfile));
|
||||
buildTarget(name, config.bunTarget, resolve(root, config.outfile), "src/cli.ts", buildEnv);
|
||||
}
|
||||
} else if (targetArg) {
|
||||
const config = TARGET_MAP[targetArg];
|
||||
if (!config) {
|
||||
throw new Error(`Unknown target: ${targetArg}. Available targets: ${Object.keys(TARGET_MAP).join(", ")}`);
|
||||
}
|
||||
buildTarget(targetArg, config.bunTarget, resolve(root, config.outfile));
|
||||
buildTarget(targetArg, config.bunTarget, resolve(root, config.outfile), "src/cli.ts", buildEnv);
|
||||
} else {
|
||||
const outputHose = resolve(root, "dist/bin/hose-use");
|
||||
buildTarget("host", null, outputHose, "src/cli.ts");
|
||||
buildTarget("host", null, outputHose, "src/cli.ts", buildEnv);
|
||||
|
||||
// Unix Multicall Binary: 创建 hose-aipro -> hose-use 软链接别名
|
||||
const outputAipro = resolve(root, "dist/bin/hose-aipro");
|
||||
@@ -43,16 +100,16 @@ if (isAll) {
|
||||
}
|
||||
}
|
||||
|
||||
function buildTarget(name, bunTarget, output, entry = "src/cli.ts") {
|
||||
function buildTarget(name, bunTarget, output, entry = "src/cli.ts", env = process.env) {
|
||||
mkdirSync(dirname(output), { recursive: true });
|
||||
const buildArgs = ["build", "--compile"];
|
||||
const buildArgs = ["build", "--compile", "--env=HOSE_BUILD_*"];
|
||||
if (bunTarget) {
|
||||
buildArgs.push(`--target=${bunTarget}`);
|
||||
}
|
||||
buildArgs.push("--outfile", output, entry);
|
||||
|
||||
console.log(`[build:binary] compiling target: ${name} -> ${output}`);
|
||||
run(bun, buildArgs);
|
||||
run(bun, buildArgs, { env });
|
||||
|
||||
if (process.platform === "darwin" && (name.startsWith("darwin") || name === "host")) {
|
||||
try {
|
||||
@@ -71,7 +128,8 @@ function buildTarget(name, bunTarget, output, entry = "src/cli.ts") {
|
||||
function run(command, args, options = {}) {
|
||||
const result = spawnSync(command, args, {
|
||||
cwd: root,
|
||||
stdio: options.quiet ? ["ignore", "ignore", "ignore"] : "inherit"
|
||||
stdio: options.quiet ? ["ignore", "ignore", "ignore"] : "inherit",
|
||||
env: options.env ?? process.env
|
||||
});
|
||||
if (result.error) throw result.error;
|
||||
if (result.status !== 0) {
|
||||
|
||||
+9
-13
@@ -35,19 +35,14 @@ pkg.version = nextVersion;
|
||||
writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
|
||||
console.log("✓ Updated package.json");
|
||||
|
||||
// 2. src/version.ts
|
||||
const versionTsPath = join(ROOT, "src", "version.ts");
|
||||
writeFileSync(versionTsPath, `export const VERSION = "${nextVersion}";\n`);
|
||||
console.log("✓ Updated src/version.ts");
|
||||
|
||||
// 3. README.md
|
||||
// 2. README.md
|
||||
const readmePath = join(ROOT, "README.md");
|
||||
let readmeContent = readFileSync(readmePath, "utf-8");
|
||||
readmeContent = readmeContent.replace(/# hose-use \(v[\d.]+\)/g, `# hose-use (v${nextVersion})`);
|
||||
writeFileSync(readmePath, readmeContent);
|
||||
console.log("✓ Updated README.md");
|
||||
|
||||
// 4. skills/hose-use/SKILL.md
|
||||
// 3. skills/hose-use/SKILL.md
|
||||
const skillPath = join(ROOT, "skills", "hose-use", "SKILL.md");
|
||||
let skillContent = readFileSync(skillPath, "utf-8");
|
||||
skillContent = skillContent.replace(/# hose-use \(v[\d.]+\)/g, `# hose-use (v${nextVersion})`);
|
||||
@@ -57,7 +52,7 @@ skillContent = skillContent.replace(/\(v[\d.]+\)/g, `(v${nextVersion})`);
|
||||
writeFileSync(skillPath, skillContent);
|
||||
console.log("✓ Updated skills/hose-use/SKILL.md");
|
||||
|
||||
// 5. openapi/openapi.yaml
|
||||
// 4. openapi/openapi.yaml
|
||||
const openapiPath = join(ROOT, "openapi", "openapi.yaml");
|
||||
if (existsSync(openapiPath)) {
|
||||
let openapiContent = readFileSync(openapiPath, "utf-8");
|
||||
@@ -66,7 +61,7 @@ if (existsSync(openapiPath)) {
|
||||
console.log("✓ Updated openapi/openapi.yaml");
|
||||
}
|
||||
|
||||
// 5.5 .zcode-plugin/plugin.json
|
||||
// 4.5 .zcode-plugin/plugin.json
|
||||
const pluginJsonPath = join(ROOT, ".zcode-plugin", "plugin.json");
|
||||
if (existsSync(pluginJsonPath)) {
|
||||
const pluginJson = JSON.parse(readFileSync(pluginJsonPath, "utf-8"));
|
||||
@@ -75,7 +70,7 @@ if (existsSync(pluginJsonPath)) {
|
||||
console.log("✓ Updated .zcode-plugin/plugin.json");
|
||||
}
|
||||
|
||||
// 6. Sync to global ~/.agents/skills/hose-use/ if present
|
||||
// 5. Sync to global ~/.agents/skills/hose-use/ if present
|
||||
const globalSkillDir = join(process.env.HOME || "", ".agents", "skills", "hose-use");
|
||||
if (existsSync(globalSkillDir)) {
|
||||
const srcDir = join(ROOT, "skills", "hose-use");
|
||||
@@ -85,13 +80,14 @@ if (existsSync(globalSkillDir)) {
|
||||
console.log("✓ Synchronized ~/.agents/skills/hose-use/");
|
||||
}
|
||||
|
||||
// 7. Rebuild OpenAPI bundles
|
||||
console.log("==> Rebuilding OpenAPI bundles...");
|
||||
// 7. Rebuild OpenAPI and plugin bundles so generated artifacts stay in lockstep.
|
||||
console.log("==> Rebuilding OpenAPI and plugin bundles...");
|
||||
execSync("bun run openapi:all", { cwd: ROOT, stdio: "inherit" });
|
||||
execSync("bun run build:plugin", { cwd: ROOT, stdio: "inherit" });
|
||||
|
||||
console.log("\n🎉 Successfully bumped version to " + nextVersion + "!");
|
||||
console.log("\nNext steps to publish:");
|
||||
console.log(` 1. Update CHANGELOG.md (if exists)`);
|
||||
console.log(` 2. git commit -am "chore(release): bump version to v${nextVersion}"`);
|
||||
console.log(` 3. git tag -a v${nextVersion} -m "🚀 Release v${nextVersion}"`);
|
||||
console.log(` 4. git push origin main --tags\n`);
|
||||
console.log(` 4. git push origin <feature-branch>\n`);
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env bun
|
||||
import { readFileSync, existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
const root = join(import.meta.dirname, "..");
|
||||
const packageVersion = (JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as { version: string }).version;
|
||||
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"])],
|
||||
];
|
||||
|
||||
const mismatches = expected.filter(([, value]) => value !== packageVersion);
|
||||
if (mismatches.length) {
|
||||
console.error(`Version drift detected; expected ${packageVersion}:`);
|
||||
for (const [file, value] of mismatches) console.error(` ${file}: ${value ?? "missing"}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`Version synchronized: ${packageVersion}`);
|
||||
|
||||
function readJsonVersion(file: string, path: string[] = ["version"]): string | undefined {
|
||||
const fullPath = join(root, file);
|
||||
if (!existsSync(fullPath)) return undefined;
|
||||
let value: unknown = JSON.parse(readFileSync(fullPath, "utf8"));
|
||||
for (const key of path) {
|
||||
if (!value || typeof value !== "object") return undefined;
|
||||
value = (value as Record<string, unknown>)[key];
|
||||
}
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { buildCleanupPlan, classifyExitCode, isCompatibleBinaryVersion, parseDevHygieneArgs, type Finding } from "./dev-hygiene.ts";
|
||||
|
||||
describe("dev hygiene tooling", () => {
|
||||
test("only accepts development-scoped modes and confirmation flags", () => {
|
||||
expect(parseDevHygieneArgs(["status"])).toEqual({ mode: "status", dryRun: false, yes: false, pruneUnreachable: false, help: false });
|
||||
expect(parseDevHygieneArgs(["clean", "--dry-run"])).toEqual({ mode: "clean", dryRun: true, yes: false, pruneUnreachable: false, help: false });
|
||||
expect(parseDevHygieneArgs(["clean", "--yes", "--prune-unreachable"])).toEqual({ mode: "clean", dryRun: false, yes: true, pruneUnreachable: true, help: false });
|
||||
});
|
||||
|
||||
test("uses semantic exit codes for clean, warning, and blocked states", () => {
|
||||
const finding = (level: Finding["level"]): Finding => ({ id: level, level, message: level });
|
||||
expect(classifyExitCode([])).toBe(0);
|
||||
expect(classifyExitCode([finding("info")])).toBe(0);
|
||||
expect(classifyExitCode([finding("warning")])).toBe(2);
|
||||
expect(classifyExitCode([finding("blocked")])).toBe(3);
|
||||
});
|
||||
|
||||
test("accepts a development build based on the current stable version", () => {
|
||||
expect(isCompatibleBinaryVersion("0.8.6", "0.8.6")).toBe(true);
|
||||
expect(isCompatibleBinaryVersion("0.8.6-dev.2+gabc1234", "0.8.6")).toBe(true);
|
||||
expect(isCompatibleBinaryVersion("0.8.5-dev.1+gold", "0.8.6")).toBe(false);
|
||||
expect(isCompatibleBinaryVersion(undefined, "0.8.6")).toBe(false);
|
||||
});
|
||||
|
||||
test("only plans deletion for clean merged worktrees and local branches", () => {
|
||||
const snapshot = {
|
||||
repository: {} as any,
|
||||
worktrees: [
|
||||
{ path: "/tmp/merged", head: "a", branch: "feat/merged", current: false, exists: true, clean: true },
|
||||
{ path: "/tmp/dirty", head: "b", branch: "feat/dirty", current: false, exists: true, clean: false },
|
||||
],
|
||||
branches: [
|
||||
{ name: "main", sha: "m", merged: true, gone: false },
|
||||
{ name: "feat/merged", sha: "a", merged: true, gone: false },
|
||||
{ name: "feat/dirty", sha: "b", merged: true, gone: false },
|
||||
{ name: "feat/live", sha: "c", merged: false, gone: false },
|
||||
],
|
||||
unreachableCommits: ["deadbeef"],
|
||||
skill: {} as any,
|
||||
binaries: [],
|
||||
legacyConfig: {} as any,
|
||||
};
|
||||
const plan = buildCleanupPlan(snapshot, false);
|
||||
expect(plan.map((action) => action.target)).toEqual(["/tmp/merged", "feat/merged"]);
|
||||
expect(plan[1]?.kind).toBe("branch-delete");
|
||||
expect(plan.some((action) => action.kind === "git-prune")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,521 @@
|
||||
#!/usr/bin/env bun
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join, relative, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const PACKAGE = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")) as { version: string };
|
||||
const CANONICAL_SKILL_DIR = join(homedir(), ".agents", "skills", "hose-use");
|
||||
const NON_CANONICAL_SKILL_DIRS = [
|
||||
join(homedir(), ".gemini", "antigravity", "skills", "hose-use"),
|
||||
join(homedir(), ".codex", "skills", "hose-use"),
|
||||
];
|
||||
|
||||
export type FindingLevel = "info" | "warning" | "blocked";
|
||||
export type HygieneMode = "status" | "check" | "clean";
|
||||
|
||||
export interface Finding {
|
||||
id: string;
|
||||
level: FindingLevel;
|
||||
message: string;
|
||||
details?: Record<string, unknown>;
|
||||
nextAction?: string;
|
||||
}
|
||||
|
||||
export interface HygieneArgs {
|
||||
mode: HygieneMode;
|
||||
dryRun: boolean;
|
||||
yes: boolean;
|
||||
pruneUnreachable: boolean;
|
||||
help: boolean;
|
||||
}
|
||||
|
||||
export interface CleanupAction {
|
||||
kind: "worktree-remove" | "worktree-prune" | "branch-delete" | "git-prune";
|
||||
target: string;
|
||||
command: string;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
interface GitBranch {
|
||||
name: string;
|
||||
sha: string;
|
||||
upstream?: string;
|
||||
gone: boolean;
|
||||
merged: boolean;
|
||||
}
|
||||
|
||||
interface GitWorktree {
|
||||
path: string;
|
||||
head: string;
|
||||
branch?: string;
|
||||
current: boolean;
|
||||
exists: boolean;
|
||||
clean?: boolean;
|
||||
}
|
||||
|
||||
interface HygieneSnapshot {
|
||||
repository: {
|
||||
root: string;
|
||||
branch: string;
|
||||
head: string;
|
||||
upstream?: string;
|
||||
ahead: number;
|
||||
behind: number;
|
||||
clean: boolean;
|
||||
stagedChanges: number;
|
||||
unstagedChanges: number;
|
||||
untrackedFiles: number;
|
||||
};
|
||||
worktrees: GitWorktree[];
|
||||
branches: GitBranch[];
|
||||
unreachableCommits: string[];
|
||||
skill: {
|
||||
canonicalDir: string;
|
||||
canonicalExists: boolean;
|
||||
canonicalIsSymlink: boolean;
|
||||
missingFiles: string[];
|
||||
mismatchedFiles: string[];
|
||||
nonCanonicalCopies: Array<{ dir: string; exists: boolean; isSymlink: boolean; pointsToCanonical: boolean }>;
|
||||
};
|
||||
binaries: Array<{
|
||||
name: string;
|
||||
path?: string;
|
||||
version?: string;
|
||||
expectedVersion: string;
|
||||
matches: boolean;
|
||||
error?: string;
|
||||
}>;
|
||||
legacyConfig: {
|
||||
enterprisesDir: string;
|
||||
configFile: string;
|
||||
enterprisesDirExists: boolean;
|
||||
configFileExists: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export interface HygieneReport {
|
||||
schemaVersion: 1;
|
||||
mode: HygieneMode;
|
||||
generatedAt: string;
|
||||
repository: string;
|
||||
snapshot: HygieneSnapshot;
|
||||
findings: Finding[];
|
||||
counts: Record<FindingLevel, number>;
|
||||
nextActions: string[];
|
||||
exitCode: number;
|
||||
}
|
||||
|
||||
export function parseDevHygieneArgs(argv: string[]): HygieneArgs {
|
||||
const requestedMode = argv.find((arg) => !arg.startsWith("--")) || "check";
|
||||
const mode: HygieneMode = requestedMode === "status" || requestedMode === "clean" ? requestedMode : "check";
|
||||
return {
|
||||
mode,
|
||||
dryRun: argv.includes("--dry-run") || argv.includes("--dryRun"),
|
||||
yes: argv.includes("--yes") || argv.includes("--confirm"),
|
||||
pruneUnreachable: argv.includes("--prune-unreachable"),
|
||||
help: argv.includes("--help") || argv.includes("-h"),
|
||||
};
|
||||
}
|
||||
|
||||
export function classifyExitCode(findings: Finding[]): number {
|
||||
if (findings.some((finding) => finding.level === "blocked")) return 3;
|
||||
if (findings.some((finding) => finding.level === "warning")) return 2;
|
||||
return 0;
|
||||
}
|
||||
|
||||
function git(args: string[], cwd = ROOT): string {
|
||||
try {
|
||||
return execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`git ${args.join(" ")} 失败: ${detail}`);
|
||||
}
|
||||
}
|
||||
|
||||
function gitMaybe(args: string[], cwd = ROOT): string | undefined {
|
||||
try {
|
||||
return git(args, cwd).trim() || undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function parseRepository(): HygieneSnapshot["repository"] {
|
||||
const status = git(["status", "--porcelain=v1", "-b"]);
|
||||
const lines = status.split("\n").filter(Boolean);
|
||||
const branchLine = lines.shift() || "## HEAD";
|
||||
const branch = branchLine.replace(/^##\s+/, "").split("...")[0] || "HEAD";
|
||||
const changes = lines.filter((line) => !line.startsWith("##"));
|
||||
const stagedChanges = changes.filter((line) => line !== "??" && line[0] !== " " && line[0] !== "?").length;
|
||||
const unstagedChanges = changes.filter((line) => line !== "??" && line[1] !== " " && line.slice(0, 2) !== "??").length;
|
||||
const untrackedFiles = changes.filter((line) => line.startsWith("??")).length;
|
||||
const upstream = gitMaybe(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"]);
|
||||
const divergence = upstream ? gitMaybe(["rev-list", "--left-right", "--count", "HEAD...@{upstream}"]) : undefined;
|
||||
const [ahead, behind] = (divergence || "0 0").split(/\s+/).map((value) => Number(value) || 0);
|
||||
return {
|
||||
root: ROOT,
|
||||
branch,
|
||||
head: git(["rev-parse", "--short", "HEAD"]).trim(),
|
||||
...(upstream ? { upstream } : {}),
|
||||
ahead,
|
||||
behind,
|
||||
clean: changes.length === 0,
|
||||
stagedChanges,
|
||||
unstagedChanges,
|
||||
untrackedFiles,
|
||||
};
|
||||
}
|
||||
|
||||
function parseWorktrees(): GitWorktree[] {
|
||||
const records: GitWorktree[] = [];
|
||||
let current: Partial<GitWorktree> = {};
|
||||
const flush = () => {
|
||||
if (!current.path) return;
|
||||
const path = resolve(current.path);
|
||||
const exists = existsSync(path);
|
||||
let clean: boolean | undefined;
|
||||
if (exists) {
|
||||
try {
|
||||
clean = git(["status", "--porcelain=v1"], path).trim() === "";
|
||||
} catch {
|
||||
clean = undefined;
|
||||
}
|
||||
}
|
||||
records.push({
|
||||
path,
|
||||
head: current.head || "",
|
||||
...(current.branch ? { branch: current.branch } : {}),
|
||||
current: path === ROOT,
|
||||
exists,
|
||||
...(clean === undefined ? {} : { clean }),
|
||||
});
|
||||
current = {};
|
||||
};
|
||||
|
||||
for (const line of git(["worktree", "list", "--porcelain"]).split("\n")) {
|
||||
if (!line) {
|
||||
flush();
|
||||
continue;
|
||||
}
|
||||
const [key, ...rest] = line.split(" ");
|
||||
const value = rest.join(" ");
|
||||
if (key === "worktree") current.path = value;
|
||||
if (key === "HEAD") current.head = value;
|
||||
if (key === "branch") current.branch = value.replace(/^refs\/heads\//, "");
|
||||
}
|
||||
flush();
|
||||
return records;
|
||||
}
|
||||
|
||||
function parseBranches(): GitBranch[] {
|
||||
const merged = new Set(git(["branch", "--merged", "main", "--format=%(refname:short)"]).split("\n").filter(Boolean));
|
||||
return git(["for-each-ref", "--format=%(refname:short)%09%(objectname:short)%09%(upstream:short)%09%(upstream:track)", "refs/heads"])
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.map((line) => {
|
||||
const [name, sha, upstream, track] = line.split("\t");
|
||||
return { name, sha, ...(upstream ? { upstream } : {}), gone: track === "[gone]", merged: merged.has(name) };
|
||||
});
|
||||
}
|
||||
|
||||
function parseUnreachableCommits(): string[] {
|
||||
return git(["fsck", "--full", "--no-reflogs", "--unreachable"])
|
||||
.split("\n")
|
||||
.filter((line) => line.includes(" commit "))
|
||||
.map((line) => line.trim().split(/\s+/)[2])
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function listFiles(dir: string, base = dir): string[] {
|
||||
if (!existsSync(dir)) return [];
|
||||
const files: string[] = [];
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const fullPath = join(dir, entry.name);
|
||||
if (entry.isDirectory() && !entry.isSymbolicLink()) files.push(...listFiles(fullPath, base));
|
||||
else files.push(relative(base, fullPath));
|
||||
}
|
||||
return files.sort();
|
||||
}
|
||||
|
||||
function fileHash(path: string): string | undefined {
|
||||
try {
|
||||
return createHash("sha256").update(readFileSync(path)).digest("hex");
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function parseSkill(): HygieneSnapshot["skill"] {
|
||||
const expectedFiles = git(["ls-files", "skills/hose-use"]).split("\n").filter(Boolean).map((path) => path.slice("skills/hose-use/".length));
|
||||
const missingFiles = expectedFiles.filter((file) => !existsSync(join(CANONICAL_SKILL_DIR, file)));
|
||||
const mismatchedFiles = expectedFiles.filter((file) => {
|
||||
const sourceHash = fileHash(join(ROOT, "skills", "hose-use", file));
|
||||
const targetHash = fileHash(join(CANONICAL_SKILL_DIR, file));
|
||||
return sourceHash !== undefined && targetHash !== undefined && sourceHash !== targetHash;
|
||||
});
|
||||
return {
|
||||
canonicalDir: CANONICAL_SKILL_DIR,
|
||||
canonicalExists: existsSync(CANONICAL_SKILL_DIR),
|
||||
canonicalIsSymlink: existsSync(CANONICAL_SKILL_DIR) && lstatSync(CANONICAL_SKILL_DIR).isSymbolicLink(),
|
||||
missingFiles,
|
||||
mismatchedFiles,
|
||||
nonCanonicalCopies: NON_CANONICAL_SKILL_DIRS.map((dir) => ({
|
||||
dir,
|
||||
exists: existsSync(dir),
|
||||
isSymlink: existsSync(dir) && lstatSync(dir).isSymbolicLink(),
|
||||
pointsToCanonical: (() => {
|
||||
try {
|
||||
return lstatSync(dir).isSymbolicLink() && realpathSync(dir) === CANONICAL_SKILL_DIR;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})(),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function resolveCommand(name: string): string | undefined {
|
||||
const result = spawnSync("which", [name], { encoding: "utf8" });
|
||||
if (result.status === 0 && result.stdout?.trim()) return result.stdout.trim();
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function isCompatibleBinaryVersion(actual: string | undefined, expected: string): boolean {
|
||||
return actual === expected || actual?.startsWith(`${expected}-dev.`) === true;
|
||||
}
|
||||
|
||||
function inspectBinary(name: string): HygieneSnapshot["binaries"][number] {
|
||||
const path = resolveCommand(name);
|
||||
if (!path) return { name, expectedVersion: PACKAGE.version, matches: false, error: "PATH 中未找到" };
|
||||
const result = spawnSync(path, ["version", "--json"], { cwd: ROOT, encoding: "utf8", timeout: 5000 });
|
||||
if (result.status !== 0) {
|
||||
return { name, path, expectedVersion: PACKAGE.version, matches: false, error: result.stderr?.trim() || `退出码 ${result.status ?? 1}` };
|
||||
}
|
||||
try {
|
||||
const version = (JSON.parse(result.stdout) as { version?: string }).version;
|
||||
return { name, path, version, expectedVersion: PACKAGE.version, matches: isCompatibleBinaryVersion(version, PACKAGE.version) };
|
||||
} catch {
|
||||
return { name, path, expectedVersion: PACKAGE.version, matches: false, error: "版本输出不是 JSON" };
|
||||
}
|
||||
}
|
||||
|
||||
function parseLegacyConfig(): HygieneSnapshot["legacyConfig"] {
|
||||
const home = homedir();
|
||||
const enterprisesDir = join(home, ".cache", "ekb-mcp", "enterprises");
|
||||
const configFile = join(home, ".cache", "ekb-mcp", "config.json");
|
||||
return { enterprisesDir, configFile, enterprisesDirExists: existsSync(enterprisesDir), configFileExists: existsSync(configFile) };
|
||||
}
|
||||
|
||||
function collectSnapshot(): HygieneSnapshot {
|
||||
return {
|
||||
repository: parseRepository(),
|
||||
worktrees: parseWorktrees(),
|
||||
branches: parseBranches(),
|
||||
unreachableCommits: parseUnreachableCommits(),
|
||||
skill: parseSkill(),
|
||||
binaries: [inspectBinary("hose-use"), inspectBinary("hose-aipro")],
|
||||
legacyConfig: parseLegacyConfig(),
|
||||
};
|
||||
}
|
||||
|
||||
function buildFindings(snapshot: HygieneSnapshot): Finding[] {
|
||||
const findings: Finding[] = [];
|
||||
const repo = snapshot.repository;
|
||||
if (!repo.clean) {
|
||||
findings.push({ id: "repo.dirty", level: "warning", message: "当前开发工作树存在未提交修改", details: { stagedChanges: repo.stagedChanges, unstagedChanges: repo.unstagedChanges, untrackedFiles: repo.untrackedFiles }, nextAction: "先确认这些修改属于当前工作,必要时提交或单独保存" });
|
||||
}
|
||||
if (repo.branch === "HEAD") findings.push({ id: "repo.detached", level: "blocked", message: "当前处于 detached HEAD", nextAction: "切换到明确的开发分支后再进行清理" });
|
||||
if (repo.behind > 0) findings.push({ id: "repo.behind", level: "warning", message: "当前分支落后于上游分支", details: { upstream: repo.upstream, behind: repo.behind }, nextAction: "确认远程变化后再执行开发清理" });
|
||||
|
||||
for (const worktree of snapshot.worktrees) {
|
||||
if (!worktree.exists) {
|
||||
findings.push({ id: "worktree.missing", level: "blocked", message: "Git 记录了不存在的工作树路径", details: { path: worktree.path, branch: worktree.branch }, nextAction: "先用 git worktree prune 清理失效记录" });
|
||||
} else if (!worktree.current && worktree.clean === false) {
|
||||
findings.push({ id: "worktree.dirty", level: "warning", message: "额外工作树存在未提交修改", details: { path: worktree.path, branch: worktree.branch }, nextAction: "不要自动删除;先进入该工作树确认修改归属" });
|
||||
} else if (!worktree.current) {
|
||||
findings.push({ id: "worktree.extra", level: "info", message: "存在额外工作树,需人工确认是否仍有用途", details: { path: worktree.path, branch: worktree.branch } });
|
||||
}
|
||||
}
|
||||
|
||||
for (const branch of snapshot.branches) {
|
||||
if (branch.name === snapshot.repository.branch) continue;
|
||||
if (branch.name !== "main" && branch.merged) {
|
||||
const linked = snapshot.worktrees.some((worktree) => worktree.branch === branch.name);
|
||||
findings.push({ id: "branch.merged", level: linked ? "warning" : "info", message: linked ? "已合并分支仍被工作树占用" : "发现已合并的本地分支", details: { branch: branch.name, sha: branch.sha, linkedWorktree: linked } });
|
||||
} else if (branch.gone) {
|
||||
findings.push({ id: "branch.gone", level: "warning", message: "本地分支的上游远程分支已不存在", details: { branch: branch.name, upstream: branch.upstream }, nextAction: "确认本地分支不再需要后再删除" });
|
||||
}
|
||||
}
|
||||
if (snapshot.unreachableCommits.length) {
|
||||
findings.push({ id: "git.unreachable", level: "warning", message: "发现无分支或标签引用的 Git commit", details: { count: snapshot.unreachableCommits.length, commits: snapshot.unreachableCommits }, nextAction: "先检查内容,确认后使用 dev:clean --yes --prune-unreachable" });
|
||||
}
|
||||
|
||||
const skill = snapshot.skill;
|
||||
if (!skill.canonicalExists || skill.missingFiles.length || skill.mismatchedFiles.length) {
|
||||
findings.push({ id: "skill.canonical-drift", level: "warning", message: "canonical Skill 缺失或与当前源码不一致", details: { dir: skill.canonicalDir, missingFiles: skill.missingFiles, mismatchedFiles: skill.mismatchedFiles }, nextAction: "运行 bun run dev:override 同步开发版 Skill" });
|
||||
}
|
||||
for (const copy of skill.nonCanonicalCopies.filter((item) => item.exists && !item.pointsToCanonical)) {
|
||||
findings.push({ id: "skill.noncanonical-copy", level: "warning", message: "发现非 canonical Skill 副本;检查不会删除它", details: copy, nextAction: "确认外部工具不再使用后,再单独设计迁移或软链接" });
|
||||
}
|
||||
|
||||
for (const binary of snapshot.binaries) {
|
||||
if (!binary.path) {
|
||||
findings.push({ id: "binary.missing", level: "info", message: `${binary.name} 未安装到 PATH`, details: binary, nextAction: "如需全局开发版,运行 bun run dev:override" });
|
||||
} else if (!binary.matches) {
|
||||
findings.push({ id: "binary.drift", level: "warning", message: `${binary.name} 全局版本与当前源码不一致`, details: binary, nextAction: "运行 bun run dev:override 同步全局开发版" });
|
||||
}
|
||||
}
|
||||
const legacy = snapshot.legacyConfig;
|
||||
if (legacy.enterprisesDirExists || legacy.configFileExists) {
|
||||
findings.push({ id: "config.legacy", level: "warning", message: "发现旧版 ekb-mcp 配置路径;检查不会删除配置", details: legacy, nextAction: "先确认迁移结果,再按配置迁移策略清理" });
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
export function buildCleanupPlan(snapshot: HygieneSnapshot, pruneUnreachable: boolean): CleanupAction[] {
|
||||
const actions: CleanupAction[] = [];
|
||||
if (snapshot.worktrees.some((worktree) => !worktree.exists)) {
|
||||
actions.push({ kind: "worktree-prune", target: "stale-worktree-records", command: "git worktree prune", reason: "移除 Git 记录中已经不存在的工作树" });
|
||||
}
|
||||
const removableWorktreeBranches = new Set(
|
||||
snapshot.worktrees
|
||||
.filter((worktree) => !worktree.current && worktree.exists && worktree.clean && worktree.branch && snapshot.branches.some((branch) => branch.name === worktree.branch && branch.merged))
|
||||
.map((worktree) => worktree.branch)
|
||||
.filter((branch): branch is string => Boolean(branch))
|
||||
);
|
||||
const linkedPaths = new Set(
|
||||
snapshot.worktrees
|
||||
.filter((worktree) => !removableWorktreeBranches.has(worktree.branch || ""))
|
||||
.map((worktree) => worktree.branch)
|
||||
.filter((branch): branch is string => Boolean(branch))
|
||||
);
|
||||
for (const worktree of snapshot.worktrees) {
|
||||
if (!worktree.current && worktree.exists && worktree.clean && worktree.branch && snapshot.branches.some((branch) => branch.name === worktree.branch && branch.merged)) {
|
||||
actions.push({ kind: "worktree-remove", target: worktree.path, command: `git worktree remove ${JSON.stringify(worktree.path)}`, reason: `工作树干净且分支 ${worktree.branch} 已合并` });
|
||||
}
|
||||
}
|
||||
for (const branch of snapshot.branches) {
|
||||
if (branch.name !== "main" && branch.merged && !linkedPaths.has(branch.name)) {
|
||||
actions.push({ kind: "branch-delete", target: branch.name, command: `git branch -d ${branch.name}`, reason: "本地分支已合并且没有关联工作树" });
|
||||
}
|
||||
}
|
||||
if (pruneUnreachable && snapshot.unreachableCommits.length) {
|
||||
actions.push({ kind: "git-prune", target: "unreachable-objects", command: "git reflog expire --expire=now --all && git gc --prune=now", reason: "明确启用 unreachable 对象清理" });
|
||||
}
|
||||
return actions;
|
||||
}
|
||||
|
||||
function applyCleanup(actions: CleanupAction[]): Array<{ action: CleanupAction; ok: boolean; error?: string }> {
|
||||
return actions.map((action) => {
|
||||
try {
|
||||
if (action.kind === "worktree-remove") git(["worktree", "remove", action.target]);
|
||||
else if (action.kind === "worktree-prune") git(["worktree", "prune"]);
|
||||
else if (action.kind === "branch-delete") git(["branch", "-d", action.target]);
|
||||
else {
|
||||
git(["reflog", "expire", "--expire=now", "--all"]);
|
||||
git(["gc", "--prune=now"]);
|
||||
}
|
||||
return { action, ok: true };
|
||||
} catch (error) {
|
||||
return { action, ok: false, error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function createReport(mode: HygieneMode): HygieneReport {
|
||||
const snapshot = collectSnapshot();
|
||||
const findings = buildFindings(snapshot);
|
||||
const counts = {
|
||||
info: findings.filter((finding) => finding.level === "info").length,
|
||||
warning: findings.filter((finding) => finding.level === "warning").length,
|
||||
blocked: findings.filter((finding) => finding.level === "blocked").length,
|
||||
};
|
||||
const exitCode = classifyExitCode(findings);
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
mode,
|
||||
generatedAt: new Date().toISOString(),
|
||||
repository: ROOT,
|
||||
snapshot,
|
||||
findings,
|
||||
counts,
|
||||
nextActions: findings.map((finding) => finding.nextAction).filter((action): action is string => Boolean(action)),
|
||||
exitCode,
|
||||
};
|
||||
}
|
||||
|
||||
function emit(value: unknown): void {
|
||||
process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
|
||||
}
|
||||
|
||||
function emitSummary(report: HygieneReport): void {
|
||||
console.error(`[dev:${report.mode}] ${report.repository}`);
|
||||
console.error(`发现 ${report.counts.info} 条提示、${report.counts.warning} 条警告、${report.counts.blocked} 条阻塞项;退出码 ${report.exitCode}`);
|
||||
for (const finding of report.findings) console.error(`- [${finding.level}] ${finding.message}`);
|
||||
}
|
||||
|
||||
function usage(): string {
|
||||
return [
|
||||
"开发环境检查(不会进入 hose-use 用户命令):",
|
||||
" bun run dev:status 输出当前开发环境快照",
|
||||
" bun run dev:check 只读检查并返回语义化退出码",
|
||||
" bun run dev:clean --dry-run 预览安全清理动作",
|
||||
" bun run dev:clean --yes 执行干净且已合并的本地清理",
|
||||
" bun run dev:clean --yes --prune-unreachable 额外清理无引用 Git 对象",
|
||||
"",
|
||||
"stdout 始终为 JSON;人类提示和进度写入 stderr。远程分支和非 canonical Skill 目录不会被自动删除。",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export async function main(argv = process.argv.slice(2)): Promise<number> {
|
||||
const args = parseDevHygieneArgs(argv);
|
||||
if (args.help) {
|
||||
emit({ ok: true, usage: usage().split("\n") });
|
||||
console.error(usage());
|
||||
return 0;
|
||||
}
|
||||
|
||||
try {
|
||||
if (args.mode !== "clean") {
|
||||
const report = createReport(args.mode);
|
||||
emit(report);
|
||||
emitSummary(report);
|
||||
return args.mode === "status" ? 0 : report.exitCode;
|
||||
}
|
||||
|
||||
const report = createReport("clean");
|
||||
const plan = buildCleanupPlan(report.snapshot, args.pruneUnreachable);
|
||||
if (args.dryRun || !args.yes) {
|
||||
emit({ ...report, plan, dryRun: true, nextAction: "bun run dev:clean --yes" });
|
||||
emitSummary(report);
|
||||
console.error(plan.length ? "[dev:clean] 当前仅预览,追加 --yes 才会执行。" : "[dev:clean] 没有满足安全条件的本地清理动作。");
|
||||
return report.exitCode;
|
||||
}
|
||||
|
||||
if (report.snapshot.repository.branch === "HEAD") {
|
||||
emit({ ...report, plan, applied: false, error: "detached HEAD 下拒绝清理" });
|
||||
return 3;
|
||||
}
|
||||
const results = applyCleanup(plan);
|
||||
const failed = results.filter((result) => !result.ok);
|
||||
emit({ ...report, plan, applied: true, results, failed: failed.length });
|
||||
console.error(`[dev:clean] 已执行 ${results.length - failed.length} 项,失败 ${failed.length} 项。`);
|
||||
return failed.length ? 4 : 0;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
emit({ ok: false, error: message });
|
||||
console.error(`[dev:hygiene] ${message}`);
|
||||
return 4;
|
||||
}
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
main().then((exitCode) => {
|
||||
process.exitCode = exitCode;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { globalBinCandidates, parseDevOverrideArgs } from "./dev-override.js";
|
||||
|
||||
describe("dev:override", () => {
|
||||
test("parses dry-run and explicit target path without touching the host", () => {
|
||||
expect(parseDevOverrideArgs(["--dry-run", "--target-path=/tmp/hose-use-test"])).toEqual({
|
||||
dryRun: true,
|
||||
targetPath: "/tmp/hose-use-test",
|
||||
});
|
||||
});
|
||||
|
||||
test("uses stable global binary locations", () => {
|
||||
const candidates = globalBinCandidates("hose-use-test");
|
||||
expect(candidates.some((candidate) => candidate.endsWith("/hose-use-test"))).toBe(true);
|
||||
expect(candidates).toHaveLength(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
#!/usr/bin/env bun
|
||||
|
||||
import { chmodSync, copyFileSync, cpSync, existsSync, mkdirSync, rmSync, symlinkSync } from "node:fs";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
|
||||
export interface DevOverrideOptions {
|
||||
dryRun: boolean;
|
||||
targetPath?: string;
|
||||
}
|
||||
|
||||
export function parseDevOverrideArgs(argv: string[]): DevOverrideOptions {
|
||||
return {
|
||||
dryRun: argv.includes("--dry-run") || argv.includes("--dryRun"),
|
||||
targetPath: argv.find((arg) => arg.startsWith("--target-path="))?.slice("--target-path=".length),
|
||||
};
|
||||
}
|
||||
|
||||
export function globalBinCandidates(commandName = "hose-use"): string[] {
|
||||
return [
|
||||
"/opt/homebrew/bin",
|
||||
"/usr/local/bin",
|
||||
join(homedir(), ".local", "bin"),
|
||||
join(homedir(), "bin"),
|
||||
].map((dir) => join(dir, commandName));
|
||||
}
|
||||
|
||||
export function resolveTargetBinaryPath(commandName = "hose-use"): string {
|
||||
try {
|
||||
const whichRes = spawnSync("which", [commandName], { encoding: "utf8" });
|
||||
if (whichRes.status === 0 && whichRes.stdout) {
|
||||
const path = whichRes.stdout.trim();
|
||||
if (path && existsSync(path)) return path;
|
||||
}
|
||||
} catch {
|
||||
// Fall back to conventional user-level locations.
|
||||
}
|
||||
|
||||
for (const candidate of globalBinCandidates(commandName)) {
|
||||
if (existsSync(dirname(candidate))) return candidate;
|
||||
}
|
||||
|
||||
const defaultDir = join(homedir(), ".local", "bin");
|
||||
mkdirSync(defaultDir, { recursive: true });
|
||||
return join(defaultDir, commandName);
|
||||
}
|
||||
|
||||
function runBuild(): string {
|
||||
const result = spawnSync("node", ["scripts/build-binary.mjs"], {
|
||||
cwd: ROOT,
|
||||
stdio: ["ignore", "inherit", "inherit"],
|
||||
});
|
||||
if (result.error) throw result.error;
|
||||
if (result.status !== 0) throw new Error(`构建开发版二进制失败,退出码: ${result.status ?? 1}`);
|
||||
|
||||
const localBinary = join(ROOT, "dist", "bin", "hose-use");
|
||||
if (!existsSync(localBinary)) throw new Error(`未找到构建产物: ${localBinary}`);
|
||||
return localBinary;
|
||||
}
|
||||
|
||||
function stopRunningService(targetPath: string): boolean {
|
||||
try {
|
||||
const statusRes = spawnSync(targetPath, ["service", "status", "--json"], { encoding: "utf8" });
|
||||
if (statusRes.status !== 0 || !statusRes.stdout) return false;
|
||||
const status = JSON.parse(statusRes.stdout) as { running?: boolean };
|
||||
if (!status.running) return false;
|
||||
|
||||
console.error("==> [dev:override] 停止正在运行的后台服务...");
|
||||
const stopRes = spawnSync(targetPath, ["service", "stop"], { stdio: "ignore" });
|
||||
if (stopRes.status !== 0) throw new Error("无法停止后台服务,已中止替换操作");
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message.includes("无法停止")) throw error;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function installBinary(localBinary: string, targetPath: string): void {
|
||||
const targetDir = dirname(targetPath);
|
||||
mkdirSync(targetDir, { recursive: true });
|
||||
const temporaryPath = `${targetPath}.tmp.${process.pid}.${Date.now()}`;
|
||||
try {
|
||||
copyFileSync(localBinary, temporaryPath);
|
||||
chmodSync(temporaryPath, 0o755);
|
||||
if (process.platform === "darwin") {
|
||||
spawnSync("/usr/bin/codesign", ["--remove-signature", temporaryPath], { stdio: "ignore" });
|
||||
spawnSync("/usr/bin/codesign", ["--force", "--sign", "-", temporaryPath], { stdio: "ignore" });
|
||||
}
|
||||
// copyFileSync follows an existing symlink, so a package-manager shim is not
|
||||
// accidentally replaced by a regular file.
|
||||
copyFileSync(temporaryPath, targetPath);
|
||||
chmodSync(targetPath, 0o755);
|
||||
} finally {
|
||||
rmSync(temporaryPath, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function syncAgentSkill(): string | undefined {
|
||||
const source = join(ROOT, "skills", "hose-use");
|
||||
const target = join(homedir(), ".agents", "skills", "hose-use");
|
||||
if (!existsSync(source)) return undefined;
|
||||
mkdirSync(dirname(target), { recursive: true });
|
||||
cpSync(source, target, { recursive: true, force: true });
|
||||
return target;
|
||||
}
|
||||
|
||||
export async function main(argv = process.argv.slice(2)): Promise<number> {
|
||||
const options = parseDevOverrideArgs(argv);
|
||||
const targetPath = options.targetPath || resolveTargetBinaryPath();
|
||||
|
||||
console.error("==> [dev:override] 将当前工作区安装为全局开发版 hose-use");
|
||||
console.error(` 工作区: ${ROOT}`);
|
||||
console.error(` 目标: ${targetPath}`);
|
||||
|
||||
if (options.dryRun) {
|
||||
console.error("[DRY-RUN] 将执行: 构建 dist/bin/hose-use、替换全局二进制、同步 ~/.agents/skills/hose-use");
|
||||
return 0;
|
||||
}
|
||||
|
||||
const builtBinary = runBuild();
|
||||
const serviceWasRunning = stopRunningService(targetPath);
|
||||
installBinary(builtBinary, targetPath);
|
||||
|
||||
const aiproPath = join(dirname(targetPath), "hose-aipro");
|
||||
if (aiproPath !== targetPath) {
|
||||
rmSync(aiproPath, { force: true });
|
||||
symlinkSync(targetPath, aiproPath);
|
||||
}
|
||||
|
||||
try {
|
||||
const skillTarget = syncAgentSkill();
|
||||
if (skillTarget) console.error(`✓ [dev:override] 已同步 Agent Skill: ${skillTarget}`);
|
||||
} catch (error) {
|
||||
console.error(`⚠️ [dev:override] Agent Skill 同步失败: ${error}`);
|
||||
}
|
||||
|
||||
if (serviceWasRunning) {
|
||||
console.error("==> [dev:override] 使用新二进制重启后台服务...");
|
||||
const startRes = spawnSync(targetPath, ["service", "start"], { stdio: "ignore" });
|
||||
if (startRes.status !== 0) console.error("⚠️ [dev:override] 后台服务重启失败,请手动运行 hose-use service start");
|
||||
}
|
||||
|
||||
const versionRes = spawnSync(targetPath, ["version"], { encoding: "utf8" });
|
||||
if (versionRes.status !== 0) throw new Error(versionRes.stderr || "开发版安装后校验失败");
|
||||
console.error("✨ [dev:override] 全局开发版安装完成");
|
||||
process.stdout.write(versionRes.stdout || "");
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
main().catch((error) => {
|
||||
console.error(`❌ [dev:override] ${error instanceof Error ? error.message : String(error)}`);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
}
|
||||
+63
-18
@@ -116,30 +116,67 @@ download_candidate() {
|
||||
echo "==> Target install location: ${TARGET_PATH}"
|
||||
TMP_FILE="$(mktemp)"
|
||||
DOWNLOAD_SUCCESS=false
|
||||
DOWNLOADED_FORMAT="archive"
|
||||
|
||||
# Candidate mirrors
|
||||
GITEA_URL="https://git.ying-qing.cn/gitea/hose-use/releases/download/latest/${ASSET_NAME}"
|
||||
GITHUB_URL="https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
|
||||
GHPROXY_URL="https://ghfast.top/https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
|
||||
# Resolve latest Gitea tag if available
|
||||
GITEA_API_URL="https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest"
|
||||
LATEST_TAG=""
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
LATEST_TAG="$(curl -sL --connect-timeout 3 "$GITEA_API_URL" | sed -n 's/.*"tag_name":"\([^"]*\)".*/\1/p' || true)"
|
||||
fi
|
||||
[ -z "$LATEST_TAG" ] && LATEST_TAG="v0.8.9"
|
||||
|
||||
# 1. First priority: Compressed Archives (.tar.gz) - fast download & includes aliases
|
||||
GITEA_ARCHIVE_URL="https://git.ying-qing.cn/gitea/hose-use/releases/download/${LATEST_TAG}/${ASSET_NAME}.tar.gz"
|
||||
GITHUB_ARCHIVE_URL="https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}.tar.gz"
|
||||
GHPROXY_ARCHIVE_URL="https://ghfast.top/https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}.tar.gz"
|
||||
|
||||
# 1. Try Gitea mirror
|
||||
if [ "${HOSE_USE_MIRROR:-auto}" = "gitea" ] || [ "${HOSE_USE_MIRROR:-auto}" = "auto" ]; then
|
||||
if download_candidate "$GITEA_URL" "$TMP_FILE" "Gitea High-Speed Mirror"; then
|
||||
if download_candidate "$GITEA_ARCHIVE_URL" "$TMP_FILE" "Gitea High-Speed Mirror (Archive)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="archive"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 2. Try direct GitHub Releases
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
|
||||
if download_candidate "$GITHUB_URL" "$TMP_FILE" "GitHub Releases (Direct)"; then
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
|
||||
if download_candidate "$GITHUB_ARCHIVE_URL" "$TMP_FILE" "GitHub Releases (Archive Direct)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="archive"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 3. Try Fast CDN Proxy Fallback
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
|
||||
if download_candidate "$GHPROXY_URL" "$TMP_FILE" "Fast CDN Mirror (Fallback)"; then
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
|
||||
if download_candidate "$GHPROXY_ARCHIVE_URL" "$TMP_FILE" "Fast CDN Mirror (Archive Fallback)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="archive"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 2. Second priority: Raw Executable (Fallback)
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
|
||||
GITEA_RAW_URL="https://git.ying-qing.cn/gitea/hose-use/releases/download/${LATEST_TAG}/${ASSET_NAME}"
|
||||
GITHUB_RAW_URL="https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
|
||||
GHPROXY_RAW_URL="https://ghfast.top/https://github.com/${REPO}/releases/latest/download/${ASSET_NAME}"
|
||||
|
||||
if [ "${HOSE_USE_MIRROR:-auto}" = "gitea" ] || [ "${HOSE_USE_MIRROR:-auto}" = "auto" ]; then
|
||||
if download_candidate "$GITEA_RAW_URL" "$TMP_FILE" "Gitea High-Speed Mirror (Raw Binary)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="raw"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
|
||||
if download_candidate "$GITHUB_RAW_URL" "$TMP_FILE" "GitHub Releases (Raw Direct)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="raw"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$DOWNLOAD_SUCCESS" = "false" ] && [ "${HOSE_USE_MIRROR:-auto}" != "gitea" ]; then
|
||||
if download_candidate "$GHPROXY_RAW_URL" "$TMP_FILE" "Fast CDN Mirror (Raw Fallback)"; then
|
||||
DOWNLOAD_SUCCESS=true
|
||||
DOWNLOADED_FORMAT="raw"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
@@ -149,18 +186,26 @@ if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
chmod +x "$TMP_FILE"
|
||||
mv "$TMP_FILE" "$TARGET_PATH"
|
||||
|
||||
# Create hose-aipro multicall alias pointing at the single binary.
|
||||
if [ -w "$TARGET_DIR" ]; then
|
||||
ln -sf "$TARGET_PATH" "${TARGET_DIR}/hose-aipro" 2>/dev/null || true
|
||||
if [ "$DOWNLOADED_FORMAT" = "archive" ]; then
|
||||
echo "==> Extracting archive to ${TARGET_DIR}..."
|
||||
tar -xzf "$TMP_FILE" -C "$TARGET_DIR"
|
||||
rm -f "$TMP_FILE"
|
||||
chmod +x "$TARGET_PATH"
|
||||
[ -f "${TARGET_DIR}/hose-aipro" ] && chmod +x "${TARGET_DIR}/hose-aipro"
|
||||
else
|
||||
chmod +x "$TMP_FILE"
|
||||
mv "$TMP_FILE" "$TARGET_PATH"
|
||||
# Create hose-aipro multicall alias pointing at the single binary.
|
||||
if [ -w "$TARGET_DIR" ]; then
|
||||
ln -sf "$TARGET_PATH" "${TARGET_DIR}/hose-aipro" 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
|
||||
# Ad-hoc sign on macOS
|
||||
if [ "$PLATFORM" = "darwin" ] && command -v codesign >/dev/null 2>&1; then
|
||||
echo "==> Applying macOS code signature..."
|
||||
codesign --force --sign - "$TARGET_PATH" 2>/dev/null || true
|
||||
[ -f "${TARGET_DIR}/hose-aipro" ] && codesign --force --sign - "${TARGET_DIR}/hose-aipro" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
echo "==> Initializing agent skill to ~/.agents/skills/hose-use..."
|
||||
|
||||
+68
-21
@@ -1,18 +1,30 @@
|
||||
---
|
||||
name: hose-use
|
||||
description: "v0.8.5: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
|
||||
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
|
||||
metadata:
|
||||
version: 0.8.5
|
||||
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.8.5)
|
||||
version: 0.8.10
|
||||
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
|
||||
---
|
||||
|
||||
# hose-use (v0.8.5)
|
||||
# hose-use (v0.8.10)
|
||||
|
||||
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
|
||||
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
|
||||
|
||||
---
|
||||
|
||||
## 本套件结构(先看这里)
|
||||
|
||||
本 skill 是**合思/易快报系列的唯一入口**,下级技能不在模型目录中,按需读取:
|
||||
|
||||
| 需要做什么 | 去哪里 |
|
||||
|---|---|
|
||||
| 登录/租户/单据/审批/通讯录/档案/费用类型/角色/待办/应用商店/守护进程 | 本文件下方路由表;细节读 `references/*.md` |
|
||||
| 写或排错**工作流 MVEL 代码节点**脚本 | `multi/ekuaibao-mvel/SKILL.md` |
|
||||
| **批量开通工作流节点**(从浏览器 curl 提取 token/corpId/baseUrl) | `multi/ekuaibao-nodes/SKILL.md` |
|
||||
|
||||
---
|
||||
|
||||
## Agent 执行原则 (First Rules)
|
||||
|
||||
0. **一键构建上下文(Zero Source-Reading)**:在开始执行任务前,优先执行 `hose-use context --json` 或 `hose-aipro status --json` 一键获取当前账号、企业租户、登录凭证、运行模式与 AI PRO 网关状态。**严禁翻阅源码目录探查配置与企业列表**。
|
||||
@@ -22,7 +34,24 @@ metadata:
|
||||
- 面对单据明细、实体字典、工作流等大数据量查询,优先使用 `--json -o <path>` 本地转储或使用 `--limit` 限制分页;
|
||||
- 严禁盲目使用 `--full` 将上万行原始报文一次性塞入上下文;
|
||||
- 永远解析 JSON stdout,不要从格式化表格的终端字符中正则刮取数据。
|
||||
4. **无状态与并发安全**:Agent 在自动化批处理或会话中,建议使用无状态模式(添加 `--stateless` 或显式指定 `--corp=<id>`),避免多任务并发切换全局状态发生冲突。
|
||||
4. **密钥安全**:`keys` 默认在表格和 JSON 中脱敏 `appSecurity`;只有用户明确需要完整凭证时才使用 `--reveal`/`-r`。不要把明文密钥写入日志、共享文件、提示词或聊天回复;尤其不要组合 `--reveal -o <path>`。
|
||||
5. **无状态与并发安全**:Agent 在自动化批处理或会话中,建议使用无状态模式(添加 `--stateless` 或显式指定 `--corp=<id>`),避免多任务并发切换全局状态发生冲突。
|
||||
6. **写操作两阶段确认**:所有 CLI 写操作先使用 `--dry-run` 查看目标和变更,再使用同一命令追加 `--yes` 或 `--confirm` 执行;未确认时不会发起写请求或写入本地状态。
|
||||
7. **开发版全局安装**:需要让 PATH 中的命令立即跟随当前工作区时,运行 `bun run dev:override`;它会构建本机二进制、同步 Agent Skill,并更新全局 `hose-use` / `hose-aipro`。可先用 `bun run dev:override -- --dry-run` 查看计划;不要使用 `npm install -g .` 留下静态旧副本。
|
||||
8. **工具域强隔离(Zero External Tool Cross-Calling)**:在处理合思/易快报相关诉求时,严格在 `hose-use` 体系内完成,**严禁跨域调用任何外部系统的 CLI(如 `seal-use` 等)**,绝不把其他系统的状态或数据强行拼接进来。
|
||||
9. **企业状态与信息分级披露(Progressive Disclosure & Stop Rules)**:
|
||||
- **4 大状态命令正交语义(严禁概念混淆)**:
|
||||
* `hose-use probe [--corp=<id>]`:**企业接入连通性与 Token 时效探针(回答“某某企业状态怎么样/连通性如何/过期没有”的唯一标准命令)**。输出仅限网络 Session、EASO 换票、自建应用网关连通性以及 Token 剩余有效时长。
|
||||
* `hose-use auth status`:统一用户中心 (IDP) 主账号登录态与会话检查。
|
||||
* `hose-use context`:Agent 本地运行环境与配置全景自省(纯本地零网络 IO)。
|
||||
* `hose-use corps list`:本地企业租户名录与工号花名册。
|
||||
- **行为分级与终止准则**:
|
||||
* **L1 基础设施与连通性(默认)**:用户询问企业状态时,**仅执行一次 `hose-use probe`**,以简短卡片输出核心连通性与时效,**立即停止工具调用并结束 Turn**。
|
||||
* **L2 业务待办与通知(按需)**:仅在用户明确询问“有我的待办吗 / 有新消息吗”时,才调用 `task todo` 或 `message count`。
|
||||
* **L3 深度排查与健康巡检(明确指令)**:严禁在日常状态询问中擅自执行 `workflow check` 巡检错误或无条件拉取全量单据,仅在用户下达“排查系统故障 / 检查工作流报错”等明确指令时才可触发。
|
||||
10. **单据检索服务端过滤优先(Server-Side Filtering First)**:
|
||||
- 查询单据列表优先使用服务端时间过滤 `--since=7d`、`--since=30d`、`--start-date`、`--end-date` 或指定 `--code`,服务端毫秒级利用索引返回;
|
||||
- 在海量单据租户下,严禁无参数滥用全量检索,优先引导用户查看个人发起单据(`hose-use bill list --mine`)或待办(`hose-use task todo`)。
|
||||
|
||||
---
|
||||
|
||||
@@ -34,12 +63,14 @@ metadata:
|
||||
| AI PRO 审批仲裁网关状态与当前连接企业 | `hose-aipro status [--json]`, `hose-use aipro status` | [references/approval.md](references/approval.md) |
|
||||
| AI PRO 规则场景库与审核要点清单 | `hose-aipro scopes`, `hose-aipro points <索引>` | [references/approval.md](references/approval.md) |
|
||||
| AI PRO 确定性审批仲裁全流程 (核验/仲裁) | `hose-aipro bind`, `hose-aipro review`, `hose-aipro decide` | [references/approval.md](references/approval.md) |
|
||||
| 本地 AI 审批规约与规则增删改查 | `hose-use rule scopes`, `hose-use rule add`, `hose-use rule list` | [references/approval.md](references/approval.md) |
|
||||
| 本地 AI 审批规约与规则增删改查 | `hose-use rule scopes`, `hose-use rule add --dry-run/--yes`, `hose-use rule list` | [references/approval.md](references/approval.md) |
|
||||
| 首次登录 / 账密认证 / Token过期 / 多账号 | `hose-use auth login`, `hose-use auth status`, `hose-use auth refresh` | [references/auth.md](references/auth.md) |
|
||||
| 第三方免密/协助链接一键秒级导入 | `hose-use corps add-link <url>`, `hose-use auth add-link <url>` | [references/auth.md](references/auth.md) |
|
||||
| 生成企业合思 Web 免密登录直达链接 (`thirdparty.html`) | `hose-use corps link [企业ID|名称]`, `hose-use auth hose-link` | [references/auth.md](references/auth.md) |
|
||||
| 第三方免密/协助链接一键导入(自动提取持久化密钥) | `hose-use corps add-link <url> --yes`, `hose-use corps elevate [企业ID] --yes` | [references/auth.md](references/auth.md) |
|
||||
| OpenAPI 密钥持久化接入 / 从链接提取密钥 | `hose-use corps add-persistent`, `hose-use corps extract-keys <url>` | [references/auth.md](references/auth.md) |
|
||||
| 代客协助凭证导入 / 探针连通性诊断 | `hose-use auth import`, `hose-use probe` | [references/auth.md](references/auth.md) |
|
||||
| 企业租户切换 / 查看当前企业 | `hose-use corps list`, `hose-use corps switch <id>` | [references/auth.md](references/auth.md) |
|
||||
| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose-use bill list`, `hose-use bill get <单号|ID> [--risk]` | [references/bill.md](references/bill.md) |
|
||||
| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose-use bill list [--since=7d] [--code=<单号>]`, `hose-use bill get <单号|ID> [--risk]` | [references/bill.md](references/bill.md) |
|
||||
| 单据审批动作(同意/驳回/转交/加签/评论) | `hose-use bill approve|reject|transfer|add-node|comment <单号|ID> --yes` | [references/bill.md](references/bill.md) |
|
||||
| 单据审批历史 / 当前节点 / 后续流程 | `hose-use bill flow <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据风控预警 / 预算状态 / 发票风险 | `hose-use bill risk <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
@@ -66,6 +97,8 @@ metadata:
|
||||
| 工作流详情、节点草稿修改、草稿保存、版本历史、运行日志、发布与开通切换 | `hose-use workflow get`, `hose-use workflow patch`, `hose-use workflow save`, `hose-use workflow publish`, `hose-use workflow history`, `hose-use workflow logs`, `hose-use workflow toggle` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流节点树、代码依赖与静态诊断 | `hose-use workflow analyze <pipelineId>` | [references/workflow.md](references/workflow.md) |
|
||||
| 工作流错误管道扫描与本地去重提醒 | `hose-use workflow check [--fail-on-alert]` | [references/workflow.md](references/workflow.md) |
|
||||
| 企业 OpenAPI 接入密钥(默认脱敏) | `hose-use keys [--json]`, `hose-use openapi keys`, `hose-use store keys` | [references/store.md](references/store.md) |
|
||||
| 企业已购应用 / 应用商店探查 | `hose-use store list / search / get` | [references/store.md](references/store.md) |
|
||||
| 常驻守护进程管理 / 后台运行 | `hose-use service start`, `hose-use service status` | [references/service.md](references/service.md) |
|
||||
| 待办/消息事件轮询与去重 | `hose-use service poll --corp=<id>` | [references/service.md](references/service.md) |
|
||||
| 启动本地 HTTP 服务 / 打开可视化交互文档 | `hose-use http --port=8888` (访问 `/docs`) | [references/service.md](references/service.md) |
|
||||
@@ -98,7 +131,11 @@ hose-use contact list --json -o /tmp/staffs.json # 导出全量通讯录
|
||||
hose-use contact get ID01MCcOgJl1td:3LsanKdS7Uo000 # 精准获取指定员工档案
|
||||
|
||||
# 3. 单据与费用
|
||||
hose-use bill list # 查看最新单据与报销记录
|
||||
hose-use bill list --since=7d # 推荐:服务端按近 7 天极速索引检索(防大租户超时)
|
||||
hose-use bill list --since=30d --count=10 # 检索近 30 天最新 10 笔单据
|
||||
hose-use bill list --start-date=2026-09-01 --end-date=2026-09-17 # 指定明确日期区间服务端过滤
|
||||
hose-use bill list --keyword=打车 # 单据关键字跨字段复合匹配 (默认匹配 name,code,form)
|
||||
hose-use bill list --keyword=打车 --search-fields=name,form # 自定义匹配字段 (支持 name,code,form 等)
|
||||
hose-use bill link CL20260901001 # 生成官方 Web 详情直达免密跳转链接
|
||||
hose-use bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘
|
||||
hose-use bill get n0GMIM0dkQmKbS # 精准查询单据详情 (中文字段映射)
|
||||
@@ -117,11 +154,12 @@ hose-use dimension list # 查看系统与自定
|
||||
hose-use dimension items 项目 # 查看项目、成本中心等档案项
|
||||
hose-use feetype list # 树形层级查看企业费用类型
|
||||
hose-use feetype get 交通费 --specs # 查看费用类型详情与报账/申请字段
|
||||
hose-use feetype create --name="市内打车" --parent="交通费" # 在指定父级下新建费用类型
|
||||
hose-use feetype update 市内打车 --desc="滴滴企业版" # 修改费用类型属性
|
||||
hose-use feetype disable 市内打车 # 停用费用类型 (软删除)
|
||||
hose-use feetype enable 市内打车 # 重新启用费用类型
|
||||
hose-use feetype move 市内打车 --parent="差旅费用" # 移动费用类型到新父级
|
||||
hose-use feetype create --name="市内打车" --parent="交通费" --dry-run # 先预览新建
|
||||
hose-use feetype create --name="市内打车" --parent="交通费" --yes # 确认新建
|
||||
hose-use feetype update 市内打车 --desc="滴滴企业版" --yes # 修改费用类型属性
|
||||
hose-use feetype disable 市内打车 --yes # 停用费用类型 (软删除)
|
||||
hose-use feetype enable 市内打车 --yes # 重新启用费用类型
|
||||
hose-use feetype move 市内打车 --parent="差旅费用" --yes # 移动费用类型到新父级
|
||||
hose-use role list # 查看企业角色定义
|
||||
hose-use role groups # 查看角色组及其角色
|
||||
hose-use role members 财务主管 # 查看指定角色成员
|
||||
@@ -142,22 +180,29 @@ hose-use platform list # 列出企业可见的
|
||||
hose-use platform entities 新转转集团 # 查看自建应用下的业务对象与字段
|
||||
hose-use platform records 新转转集团 合同 # 查看业务对象的底层数据记录
|
||||
hose-use platform record get 新转转集团 合同 <记录ID> # 获取单条记录完整字段与属性详情
|
||||
hose-use platform record toggle 新转转集团 合同 <记录ID> # 切换单条记录停启用状态
|
||||
hose-use platform record edit 新转转集团 合同 <记录ID> --data='{"name":"新名称"}' # 编辑记录字段
|
||||
hose-use platform record recompute 新转转集团 合同 <记录ID> # 重新计算记录关联的全部台账
|
||||
hose-use platform record toggle 新转转集团 合同 <记录ID> --dry-run # 预览状态切换
|
||||
hose-use platform record edit 新转转集团 合同 <记录ID> --data='{"name":"新名称"}' --yes # 编辑记录字段
|
||||
hose-use platform record recompute 新转转集团 合同 <记录ID> --yes # 重新计算记录关联的全部台账
|
||||
hose-use menu list # 查看桌面端主框架一级导航树
|
||||
hose-use workflow list # 聚合扫描全部自建应用下的工作流
|
||||
hose-use workflow find --task=code-js2 # 查找部署了代码节点的工作流
|
||||
hose-use workflow get wf_01k83y... # 查看指定工作流节点拓扑
|
||||
hose-use workflow analyze wf_01k83y... --json # 输出节点树、引用依赖与静态诊断
|
||||
hose-use workflow save wf_01k83y... --file=workflow.json # 按完整快照保存草稿并做版本保护
|
||||
hose-use workflow patch wf_01k83y... --file=workflow.json --path=tasks.0.code --value='return 2;' --output=patched.json
|
||||
hose-use workflow save wf_01k83y... --file=workflow.json --yes # 按完整快照保存草稿并做版本保护
|
||||
hose-use workflow patch wf_01k83y... --file=workflow.json --path=tasks.0.code --value='return 2;' --output=patched.json --yes
|
||||
hose-use workflow history wf_01k83y... --json # 查看服务端版本快照历史
|
||||
hose-use workflow logs wf_01k83y... --state=FAILED # 查看运行错误日志
|
||||
hose-use workflow check --json --fail-on-alert # 扫描错误管道并只提醒新增错误计数
|
||||
hose-use workflow publish wf_01k83y... # 将保存后的工作流发布/启用
|
||||
hose-use workflow publish wf_01k83y... --yes # 将保存后的工作流发布/启用
|
||||
|
||||
# 6. 服务与守护进程
|
||||
# 6. OpenAPI 密钥与应用中心
|
||||
hose-use keys --json # 查询当前企业密钥,appSecurity 默认脱敏
|
||||
hose-use keys --reveal # 仅在用户明确授权时查看完整 appSecurity
|
||||
hose-use store list --all # 查看当前企业已购/已开通应用
|
||||
hose-use store search "开放接口" # 搜索应用商店
|
||||
hose-use store get <应用ID> # 查看应用详情(ID 可带或不带前导 $)
|
||||
|
||||
# 7. 服务与守护进程
|
||||
hose-use http --port=8888 # 启动前台 HTTP 服务与交互式文档
|
||||
hose-use service start # 后台启动常驻守护进程服务
|
||||
hose-use service status # 查看常驻守护进程运行状态与端点
|
||||
@@ -176,4 +221,6 @@ hose-use service stop # 停止后台常驻守
|
||||
- `--full`:全量输出大报文(绕过 200KB 体积防爆拦截)
|
||||
- `--stateless`:单次命令强制以无状态模式执行
|
||||
- `--stateful`:单次命令强制以有状态模式执行
|
||||
- `--dry-run`:预览写操作,不发起写请求或落盘
|
||||
- `--yes`, `--confirm`:显式确认执行写操作
|
||||
- `--help, -h`:查看命令帮助与参数说明
|
||||
@@ -5,7 +5,7 @@ auth:
|
||||
type: "none"
|
||||
tools:
|
||||
- name: "hose_cli"
|
||||
description: "执行合思/易快报 hose-use CLI 命令。详细命令语法请参考 hose-use skill 文档。"
|
||||
description: "执行合思/易快报 hose-use CLI 命令,包括 keys 凭证查询与 store 应用探查。详细命令语法请参考 hose-use skill 文档。"
|
||||
parameters:
|
||||
type: "object"
|
||||
properties:
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
---
|
||||
name: ekuaibao-mvel
|
||||
description: Generate and debug MVEL code-node scripts for 合思/易快报/Ekuaibao workflows.
|
||||
---
|
||||
|
||||
# 合思 MVEL 代码节点
|
||||
|
||||
## Core Rule
|
||||
|
||||
Generate code for Ekuaibao's modified MVEL 2.x runtime, not JavaScript, Groovy, or standard Java. First match the syntax style the user has already proven in their tenant or node.
|
||||
|
||||
- If the user provides a working snippet, preserve that dialect. For example, if `a = action_xxx; ... result;` works, use bare assignments and final-expression return.
|
||||
- If the user has not provided a working snippet, prefer conservative MVEL and be ready to simplify to a probe script.
|
||||
- Do not use `def` for variables.
|
||||
- Use `return`, `import`, or `var` only when they match the user's known working environment; otherwise avoid them in favor of final-expression return and fully qualified JDK classes.
|
||||
- Use Java collection methods: `.get()`, `.put()`, `.add()`, `.size()`.
|
||||
- For Chinese or dynamic field names, prefer `map.get("字段名")` instead of dot access.
|
||||
- Every `if`, `&&`, and `||` operand must be a strict boolean expression. Never write `if (data)`.
|
||||
|
||||
## Code Node Template
|
||||
|
||||
Use this style when the user has shown bare assignments and final-expression return work:
|
||||
|
||||
```groovy
|
||||
a = action_xxxxxx;
|
||||
|
||||
result = new java.util.HashMap();
|
||||
result.put("ok", true);
|
||||
result;
|
||||
```
|
||||
|
||||
When the user's environment supports `var/import/return`, it is acceptable to use that style, but do not mix styles unnecessarily within one answer.
|
||||
|
||||
## Tenant-Proven Short Syntax
|
||||
|
||||
This tenant has verified that these short forms work:
|
||||
|
||||
- Map literal: `["key": value]`
|
||||
- List literal: `[item1, item2]`
|
||||
- Final-expression return
|
||||
- Upstream node references use node ID variables such as `action_xxxxxx`
|
||||
|
||||
When the user asks to hard-return a config object, prefer Map/List literals first:
|
||||
|
||||
```groovy
|
||||
[
|
||||
"config": [
|
||||
"key": "value",
|
||||
"list": ["a", "b"]
|
||||
]
|
||||
]
|
||||
```
|
||||
|
||||
If Map/List literals fail in a different tenant or node, fall back to `new java.util.HashMap()` and `new java.util.ArrayList()`.
|
||||
|
||||
## Upstream Node Reference
|
||||
|
||||
When the user says the upstream node is referenced by ID, assign the node ID variable to a semantic local name first:
|
||||
|
||||
```groovy
|
||||
inputData = action_xxxxxx;
|
||||
```
|
||||
|
||||
Do not assume the platform provides a built-in variable named `inputData` unless the user explicitly says so. Replace `action_xxxxxx` with the real upstream node ID the user provides.
|
||||
|
||||
## Defensive Patterns
|
||||
|
||||
### Read First Item Only
|
||||
|
||||
When the user says to read only the first upstream record, do not loop.
|
||||
|
||||
```groovy
|
||||
a = action_xxxxxx;
|
||||
firstItem = null;
|
||||
|
||||
if (a != null && a.size() > 0) {
|
||||
firstItem = a.get(0);
|
||||
}
|
||||
```
|
||||
|
||||
### Read Nested Form Field
|
||||
|
||||
```groovy
|
||||
value = "";
|
||||
|
||||
if (firstItem != null && firstItem.get("form") != null) {
|
||||
form = firstItem.get("form");
|
||||
rawValue = form.get("E_xxx_字段名");
|
||||
|
||||
if (rawValue != null && String.valueOf(rawValue).trim() != "") {
|
||||
value = String.valueOf(rawValue).trim();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Generate Next 6-Digit Number
|
||||
|
||||
Use this for JS logic like `parseInt(num, 10) || 0` and `.padStart(6, "0")`:
|
||||
|
||||
```groovy
|
||||
num = "";
|
||||
nextStr = "000001";
|
||||
|
||||
if (rawNum != null && String.valueOf(rawNum).trim() != "") {
|
||||
num = String.valueOf(rawNum).trim();
|
||||
}
|
||||
|
||||
if (num != null && num.trim() != "" && num.trim().matches("[0-9]+")) {
|
||||
cleanNum = num.trim();
|
||||
nextNumber = java.lang.Integer.parseInt(cleanNum) + 1;
|
||||
rawNextStr = String.valueOf(nextNumber);
|
||||
|
||||
if (rawNextStr.length() < 6) {
|
||||
padded = "000000" + rawNextStr;
|
||||
nextStr = padded.substring(padded.length() - 6);
|
||||
} else {
|
||||
nextStr = rawNextStr;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Avoid
|
||||
|
||||
- Do not use JavaScript methods: `.push()`, `.length` as a property, `parseInt`, `padStart`.
|
||||
- Do not use Groovy sugar: `?.`, `?:`.
|
||||
- Do not use `try/catch` unless the user has already verified it works in their tenant.
|
||||
- Do not use third-party imports such as Fastjson.
|
||||
- Do not use `String.valueOf(map)` when downstream needs valid JSON; manually concatenate JSON strings.
|
||||
- In enhanced loops, write `for (item : list)`, never `for (var item : list)`.
|
||||
|
||||
## Debugging Silent Failures
|
||||
|
||||
If the platform gives no detailed error, simplify toward a probe script:
|
||||
|
||||
```groovy
|
||||
a = action_xxxxxx;
|
||||
|
||||
result = new java.util.HashMap();
|
||||
result.put("isNull", a == null);
|
||||
result.put("total", a != null ? a.size() : 0);
|
||||
result;
|
||||
```
|
||||
|
||||
Then add one field access at a time. For code nodes nested inside a condition branch, still return a normal object from the code node; only condition expressions themselves must return boolean.
|
||||
|
||||
Treat tenant-specific behavior as evidence, not a universal rule. Say what assumption the code is using when syntax compatibility is uncertain.
|
||||
@@ -0,0 +1,4 @@
|
||||
interface:
|
||||
display_name: "合思 MVEL"
|
||||
short_description: "生成、改写和排查合思 MVEL 代码节点运行兼容问题"
|
||||
default_prompt: "Use $ekuaibao-mvel to write a 合思 MVEL code-node script."
|
||||
@@ -0,0 +1,46 @@
|
||||
---
|
||||
name: ekuaibao-nodes
|
||||
description: |
|
||||
合思(易快报)工作流节点批量开通工具。
|
||||
当用户提到"合思"、"易快报"、"ekuaibao"、"工作流节点"、"开通节点"时使用。
|
||||
---
|
||||
|
||||
# 合思工作流节点开通
|
||||
|
||||
批量开通合思工作流节点。
|
||||
|
||||
节点名称与 type 对照见 [灰度节点清单](references/gray-nodes.md)。 **`nodes` 参数填清单中的 `type` 列值(如 `code`、`risk`),不是中文名。** 遇到同名节点或用户只提供模糊名称时,先根据 type 核对并向用户确认。
|
||||
|
||||
## 参数提取
|
||||
|
||||
用户通常会贴浏览器请求(curl),从请求中自动提取参数:
|
||||
|
||||
| 参数 | 提取位置 | 说明 |
|
||||
|------|----------|------|
|
||||
| token | Header `accesstoken` 或 Cookie `ekb-access-token` | accessToken |
|
||||
| corpId | Header `corpid` 或 URL query `corpId` | 企业 ID |
|
||||
| baseUrl | URL 协议+域名部分(如 `https://dd2.hosecloud.com`) | 自定义合思地址 |
|
||||
| nodes | 向用户确认 | 节点名,逗号分隔 |
|
||||
|
||||
**域名判断**:URL 不是 `*.hosecloud.com` 而是 `dd2.hosecloud.com` 这类就是自定义域名,必须提取为 `baseUrl`。
|
||||
|
||||
## 执行
|
||||
|
||||
```bash
|
||||
curl -s -X POST 'https://d9jxeccs5j.sealosgzg.site/hose-workflow-node' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"token":"TOKEN","corpId":"CORPID","nodes":"NODES"}'
|
||||
```
|
||||
|
||||
可选参数:
|
||||
- `baseUrl: "https://..."` — **重要:用户使用了自定义域名时(如 `dd2.hosecloud.com`),必须加上此参数。** 不传则默认走正式环境认证地址。
|
||||
- `isTest: true` — 仅用于切换内部标记,不能替代 `baseUrl`
|
||||
|
||||
## 结果处理
|
||||
|
||||
**成功**:`{"success":true,"data":{"msg":"新开通的节点:xxx"}}`
|
||||
|
||||
**失败排查**:
|
||||
- `认证失败` + `缺少或传错了 baseUrl` — 检查用户请求是否走自定义域名,加上 `baseUrl`
|
||||
- `认证失败` + 其他 — token 过期,让用户重新获取
|
||||
- 节点名错误 — 核对名称拼写
|
||||
@@ -0,0 +1,119 @@
|
||||
# 灰度节点清单
|
||||
|
||||
来源:`合思工作流开通节点_节点开通-节点列表_灰度节点.csv`。共 109 条非空记录,去重后 108 条。
|
||||
|
||||
开通请求的 `nodes` 使用本表的 **`type` 列值**(第三列),如 `code`、`risk`。第二列"节点名称"仅用于展示和核对。
|
||||
|
||||
> 注意:`数据映射`有两个可用类型(`mapping`、`dmn`);同名节点需先与用户确认具体类型。`单据查询详情(跨租户)`在源文件中有重复记录,以下仅保留一条。
|
||||
|
||||
| 显示名称 | 节点名称(nodes) | type |
|
||||
| --- | --- | --- |
|
||||
| JS节点(新) | JS节点(新) | `code-js2` |
|
||||
| 重算审批流 | 重算审批流 | `recalculate-the-approval-flow` |
|
||||
| 提示框 | 提示框 | `ui-notification` |
|
||||
| 定时任务节点 | 定时任务节点 | `start` |
|
||||
| 推送飞书消息 | 推送飞书消息 | `feishu-sendMsg` |
|
||||
| 飞书消息 | 飞书消息 | `message-feishu` |
|
||||
| if节点 | if节点 | `if` |
|
||||
| http节点 | http节点 | `http` |
|
||||
| 遍历数组 | 遍历数组 | `loop` |
|
||||
| 循环节点 | 循环节点 | `while` |
|
||||
| 企业微信开放平台获取子部门ID列表 | 企业微信开放平台获取子部门ID列表 | `wecom-department` |
|
||||
| 易桥参数转化 | 易桥参数转化 | `eBridge-mapData` |
|
||||
| 代码节点 | 代码节点 | `code` |
|
||||
| 数据映射 | 数据映射 | `mapping` |
|
||||
| 纷享销客鉴权 | 纷享销客鉴权 | `fxiaoke-auth` |
|
||||
| 纷享销客数据列表 | 纷享销客数据列表 | `fxiaoke-list` |
|
||||
| NetSuite数据列表 | NetSuite数据列表 | `netsuite-sync` |
|
||||
| NetSuite数据创建 | NetSuite数据创建 | `netsuite-create` |
|
||||
| 易桥鉴权 | 易桥鉴权 | `ebridge-auth` |
|
||||
| 新增业务对象数据 | 新增业务对象数据 | `ekuaibao-datalink-create` |
|
||||
| 定时触发 | 定时触发 | `clock` |
|
||||
| 纷享销客触发器 | 纷享销客触发器 | `fxiaoke-trigger` |
|
||||
| 到达业务对象数据中的日期时触发 | 到达业务对象数据中的日期时触发 | `ekuaibao-datalink-time-trigger` |
|
||||
| 发送邮件 | 发送邮件 | `email` |
|
||||
| 查找业务对象数据 | 查找业务对象数据 | `ekuaibao-datalink-filter` |
|
||||
| 修改业务对象数据 | 修改业务对象数据 | `ekuaibao-datalink-edit` |
|
||||
| NetSuite数据删除 | NetSuite数据删除 | `netsuite-delete` |
|
||||
| 薪人薪事触发器 | 薪人薪事触发器 | `xrxs-trigger` |
|
||||
| 新增业务对象数据时触发 | 新增业务对象数据时触发 | `ekuaibao-datalink-create-trigger` |
|
||||
| 变更业务对象数据时触发 | 变更业务对象数据时触发 | `ekuaibao-datalink-change-trigger` |
|
||||
| 单据审批事件触发器 | 单据审批事件触发器 | `ekuaibao-flowform-trigger` |
|
||||
| 发送短信 | 发送短信 | `message` |
|
||||
| webhook触发器 | webhook触发器 | `webhook` |
|
||||
| 对话框 | 对话框 | `ui-dialog` |
|
||||
| 流程日志 | 流程日志 | `task-log` |
|
||||
| 动态节点测试 | 动态节点测试 | `task-dynamic-test` |
|
||||
| 条件节点 | 条件节点 | `condition` |
|
||||
| OpenAPI | OpenAPI | `task-openapi` |
|
||||
| 终止节点 | 终止节点 | `stop` |
|
||||
| 收集节点 | 收集节点 | `context` |
|
||||
| 到达单据日期时触发 | 到达单据日期时触发 | `flow-change-trigger` |
|
||||
| 获取钉钉考勤 | 获取钉钉考勤 | `task-dynamic-ding-attendance` |
|
||||
| 摊销节点 | 摊销节点 | `apportion` |
|
||||
| 创建单据 | 创建单据 | `flow-create-task` |
|
||||
| 站内信 | 站内信 | `message-internet` |
|
||||
| 钉钉消息 | 钉钉消息 | `message-dingtalk` |
|
||||
| 修改角色 | 修改角色 | `role-update` |
|
||||
| 依次执行 | 依次执行 | `every` |
|
||||
| 查询申请事项详情 | 查询申请事项详情 | `ekuaibao-requision-detail` |
|
||||
| 查询单据详情 | 查询单据详情 | `flow-detail` |
|
||||
| 查询单据历史详情 | 查询单据历史详情 | `flow-detail-versioned` |
|
||||
| 业务对象数据按钮触发 | 业务对象数据按钮触发 | `datalink-button-trigger` |
|
||||
| 查找行程数据 | 查找行程数据 | `ekuaibao-tmc-datalink-filter` |
|
||||
| 新增行程数据时触发 | 新增行程数据时触发 | `ekuaibao-tmc-datalink-create-trigger` |
|
||||
| 变更行程数据时触发 | 变更行程数据时触发 | `ekuaibao-tmc-datalink-change-trigger` |
|
||||
| 到达行程日期时触发 | 到达行程日期时触发 | `ekuaibao-tmc-datalink-time-trigger` |
|
||||
| 查询发票 | 查询发票 | `ekuaibao-invoice-datalink-filter` |
|
||||
| 结果输出 | 结果输出 | `output` |
|
||||
| EBOT触发 | EBOT触发 | `ekuaibao-ebot-trigger` |
|
||||
| 补充发票触发 | 补充发票触发 | `other-event-trigger` |
|
||||
| 发票验真 | 发票验真 | `invoice-verification` |
|
||||
| JS节点 | JS节点 | `code-js` |
|
||||
| 数据转化 | 数据转化 | `data-convert` |
|
||||
| 新摊销 | 新摊销 | `amortization` |
|
||||
| 数据映射 | 数据映射 | `dmn` |
|
||||
| 查询人员 | 查询人员 | `ekuaibao-staff-filter` |
|
||||
| 查询单据列表 | 查询单据列表 | `flow-list` |
|
||||
| HAB触发器 | HAB触发器 | `hab-trigger-task` |
|
||||
| 申请事项触发器 | 申请事项触发器 | `ekuaibao-requisition-trigger` |
|
||||
| 创建部门 | 创建部门 | `department-create` |
|
||||
| 部门查询 | 部门查询 | `department-filter` |
|
||||
| 新增人员 | 新增人员 | `staff-create` |
|
||||
| 查询随手记列表 | 查询随手记列表 | `ekuaibao-ecard-fee-filter` |
|
||||
| 查询人员详情 | 查询人员详情 | `ekuaibao-staff-detail` |
|
||||
| 查询部门详情 | 查询部门详情 | `ekuaibao-department-detail` |
|
||||
| 查询易商卡申请事项列表 | 查询易商卡申请事项列表 | `ekuaibao-ecard-requisition-filter` |
|
||||
| 查询飞书部门 | 查询飞书部门 | `feishu-department-filter` |
|
||||
| 修改部门 | 修改部门 | `ekuaibao-department-update` |
|
||||
| 站外信 | 站外信 | `message-outnet` |
|
||||
| AI节点 | AI节点 | `ekb-ai` |
|
||||
| 修改单据 | 修改单据 | `flow-update-task` |
|
||||
| 提取文本(word,PDF) | 提取文本(word,PDF) | `ekb-ai-pdf` |
|
||||
| 单据风险写入 | 单据风险写入 | `risk` |
|
||||
| 天润工单查询 | 天润工单查询 | `tr-select` |
|
||||
| 天润工单评论 | 天润工单评论 | `tr-comment` |
|
||||
| 天润工单查询详情 | 天润工单查询详情 | `tr-detail` |
|
||||
| Dify接入 | Dify接入 | `dify` |
|
||||
| 图片URL识别 | 图片URL识别 | `ekb-ai-url` |
|
||||
| AI文本理解 | AI文本理解 | `ekb-minimax-text` |
|
||||
| AI图像理解 | AI图像理解 | `ekb-minimax-photo` |
|
||||
| 查询角色下的人员 | 查询角色下的人员 | `search-staff-by-role` |
|
||||
| 发票巡检 | 发票巡检 | `ekuaibao-invoice-inspector` |
|
||||
| 招商银行商务卡查询 | 招商银行商务卡查询 | `task-zs` |
|
||||
| 单据查询详情(跨租户) | 单据查询详情(跨租户) | `escape` |
|
||||
| 海亮单据查询详情 | 海亮单据查询详情 | `hl-detail` |
|
||||
| 单据查询详情AI审批专用 | 单据查询详情AI审批专用 | `mapping-detail` |
|
||||
| 海亮数据集列表 | 海亮数据集列表 | `hl` |
|
||||
| 查询易商卡流水的费用信息 | 查询易商卡流水的费用信息 | `ekuaibao-ecard-fee-detail-filter` |
|
||||
| Ebot审批 | Ebot审批 | `ebot-approval-flow` |
|
||||
| 给OA账号发送提醒 | 给OA账号发送提醒 | `oa` |
|
||||
| 查询历史单据测试集 | 查询历史单据测试集 | `flow-sample-list` |
|
||||
| 分类汇总 | 分类汇总 | `aggregation` |
|
||||
| 单据转译节点 | 单据转译节点 | `flow-format` |
|
||||
| 导出表格 | 导出表格 | `excel` |
|
||||
| AI附件理解 | AI附件理解 | `ai-attachment` |
|
||||
| AI智能匹配 | AI智能匹配 | `ai-classification` |
|
||||
| AI智能提取 | AI智能提取 | `ai-extraction` |
|
||||
| 延迟执行节点 | 延迟执行节点 | `task-dynamic-delay` |
|
||||
|
||||
@@ -42,24 +42,47 @@ hose-use auth refresh
|
||||
```
|
||||
- 主动调用主站会话刷新接口,续期当前企业凭据的 AccessToken。
|
||||
|
||||
### 第三方免密/协助链接一键导入 (`corps add-link` / `auth add-link`)
|
||||
### 第三方免密/协助链接一键导入与自动提权持久化 (`corps add-link` / `auth add-link`)
|
||||
```bash
|
||||
# 直接粘贴企业微信免密、合思代客或协助 thirdparty.html 链接
|
||||
hose-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=...&ekbCorpId=..."
|
||||
# 直接粘贴企业微信免密、合思代客或协助 thirdparty.html 链接(默认自动探测并持久化保存 OpenAPI appKey + appSecurity)
|
||||
hose-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToken=...&ekbCorpId=..." --yes
|
||||
|
||||
# 可选附加别名与覆盖参数
|
||||
hose-use corps add-link "<url>" --name="客户企业别名" --overwrite
|
||||
# 显式强制要求提取 OpenAPI 持久化密钥(多套密钥时可附加 --app-key 或 --force)
|
||||
hose-use corps add-link "<url>" --elevate --force --overwrite --yes
|
||||
|
||||
# 未提供服务端 expTime 时,可显式指定本地有效期
|
||||
hose-use corps add-link "<url>" --ttl 3d
|
||||
hose-use corps add-link "<url>" --expires 3 # 等价于 3 天;--days 3 也可以
|
||||
hose-use corps add-link "<url>" --ttl 3d --yes
|
||||
```
|
||||
- **全自动识别与身份探测**:
|
||||
- **全自动识别与双通道持久化**:
|
||||
- 自动从 URL 提取服务节点 `baseUrl`、集群环境 `cluster`(如 `wx2`、`app`)、`accessToken` 与 `corpId`;
|
||||
- 自动向 `$UNITY` JWT 与主站 Session 反查员工工号 (`staffId`)、员工姓名、绑定手机、企业全称与是否企业管理员,无需手动寻找工号;
|
||||
- 动态自适应多集群环境换票,确保主站单据审批与 EASO 低代码工作流平台权限全绿连通。
|
||||
- 非账号来源(link/browser/assist/curl/manual)不会触发账号换票;Token 失效时提示重新导入链接。
|
||||
- 服务端返回的 expTime 优先;未返回时不再强制套用 2 小时,可使用 `--ttl` / `--expires` 指定有效期。
|
||||
- 自动向 `$UNITY` JWT 与主站 Session 反查员工工号 (`staffId`)、员工姓名、绑定手机、企业全称与是否企业管理员;
|
||||
- **自动提取 OpenAPI 持久化密钥**:导入链接或账密登录时,自动尝试调用 `/api/innerapi/v1/key` 提取企业启用状态的 `appKey + appSecurity` 并写入 `enterprises/<corpId>.json`;
|
||||
- **双通道无感自动续期**:当会话 `accessToken` 过期时,客户端优先尝试用户级主账号 (`cloudAuthToken`) 换票,或自动通过企业级 OpenAPI 持久化密钥调用 `/api/openapi/v1/auth/getAccessToken` + `/api/openapi/v1.1/provisional/getProvisionalAuth` 签发全新会话令牌并落盘,彻底告别临时链接过期失效。
|
||||
|
||||
### 生成企业合思 Web 免密登录直达链接 (`corps link` / `auth hose-link`)
|
||||
```bash
|
||||
# 为已配置企业生成 2 小时有效期的 Web 免密直达链接 (thirdparty.html)
|
||||
hose-use corps link 新转转集团
|
||||
hose-use corps link ID01PH4Q5CJboX --json
|
||||
hose-use auth hose-link --corp=ID01PH4Q5CJboX
|
||||
```
|
||||
- 若企业已配置 OpenAPI `appKey + appSecurity`,直接调用 `getProvisionalAuth` 动态签发全新的 `thirdparty.html` 免密登录链接;
|
||||
- 若企业尚未持久化密钥,会先尝试利用当前有效会话自动提权提取 `appKey + appSecurity`,再签发直达链接。
|
||||
|
||||
### OpenAPI 持久化密钥直接接入与存量提权 (`add-persistent` / `extract-keys` / `elevate`)
|
||||
```bash
|
||||
# 1. 直接使用 appKey + appSecurity 持久化接入企业(自动探测 6 大合思域名与主管理员)
|
||||
hose-use corps add-persistent --app-key=<key> --app-security=<secret> --force --yes
|
||||
|
||||
# 2. 从协助链接中提取查看 OpenAPI 密钥(附加 --save --yes 可直接持久化落盘)
|
||||
hose-use corps extract-keys "<url>"
|
||||
hose-use corps extract-keys "<url>" --save --yes
|
||||
|
||||
# 3. 为本地已配置企业(或 --all 全部企业)提取并持久化保存 OpenAPI 密钥
|
||||
hose-use corps elevate ID01PH4Q5CJboX --yes
|
||||
hose-use corps elevate --all --yes
|
||||
hose-use keys --corp=ID01PH4Q5CJboX --save --yes
|
||||
```
|
||||
|
||||
### 代客协助凭证导入
|
||||
```bash
|
||||
@@ -67,7 +90,8 @@ hose-use auth import \
|
||||
--name="CSM代客" \
|
||||
--corp-id="Cxa3oOtQi2eS$g" \
|
||||
--staff-id="Cxa3oOtQi2eS$g:2HQbkGx2DgnM00" \
|
||||
--token="1361c470-3d7c-4a3a-a1fb-e946aee5723b"
|
||||
--token="1361c470-3d7c-4a3a-a1fb-e946aee5723b" \
|
||||
--yes
|
||||
```
|
||||
- **智能探测机制**:若 `corp-id` 包含 `$UNITY` 或特殊字符,系统会自动探测代客服务会话接口,解析 13 位过期毫秒时间戳并正确建立凭证映射。也可直接传入抓包 cURL 或包含 URL 的文本。
|
||||
|
||||
|
||||
@@ -15,15 +15,31 @@ hose-use bill list
|
||||
hose-use bill list --corp=uzU7pcWfScck00 --json
|
||||
```
|
||||
|
||||
### 过滤选项
|
||||
- `--type=<type>`:按单据大类过滤(如 `TRAVEL_EXPENSE` 差旅报销、`DAILY_EXPENSE` 日常报销、`BORROW` 借款申请、`LOAN` 借款申请等);
|
||||
- `--status=<status>`:按审批状态过滤(如 `APPROVED` 审批完成、`PROCESSING` 审批中、`REJECTED` 已驳回、`DRAFT` 草稿等);
|
||||
- `--limit=<number>`:单页数量(默认 20,最大 100);
|
||||
- `--page=<number>`:分页页码(默认 1)。
|
||||
### 过滤与检索选项
|
||||
- `--keyword=<keyword>` / `-k`: 按关键字模糊搜索,原生走服务端 `INSTR` 索引检索;
|
||||
- `--search-fields=<fields>` / `--sf`: 指定 keyword 检索匹配的字段列表,默认 `name,code,form`;可传入单字段(如 `--search-fields=name` 或 `--search-fields=code`)或逗号分隔字段列表(如 `--search-fields=name,form`),服务端自动组装为嵌套复合 OR 检索;
|
||||
- `--code=<code>` / `-c`: 按单据编号(单号)服务端索引精准匹配;
|
||||
- `--since=<duration>` / `-d`: 相对时间范围(如 `7d`、`30d`、`90d`、`1y`),大租户海量单据下强烈推荐以避免全量超时;
|
||||
- `--start-date=<date>` / `--end-date=<date>`: 起止日期过滤(支持 `YYYY-MM-DD` 或毫秒时间戳);
|
||||
- `--stage=<stage>`: 业务阶段过滤(如 `expense` 报销, `loan` 借款, `payment` 付款);
|
||||
- `--state=<state>` / `-s`: 审批与支付状态过滤(如 `paid` 已支付, `approving` 审批中, `draft` 草稿);
|
||||
- `--count=<number>` / `--limit` / `-n`: 单页拉取数量(默认 20);
|
||||
- `--mine`: 快捷查询当前登录人提交的单据(自动桥接至 `task submitted`);
|
||||
- `--select=<fields>`: 按需指定返回字段(逗号分隔,如 `id,code,name,createTime,form`);
|
||||
- `--distinct`: 是否对单据记录去重。
|
||||
|
||||
```bash
|
||||
# 查询审批通过的差旅报销单
|
||||
hose-use bill list --type=TRAVEL_EXPENSE --status=APPROVED --limit=50
|
||||
# 跨单据名称与表单字段检索含“打车”的最近 7 天单据
|
||||
hose-use bill list --keyword=打车 --search-fields=name,form --since=7d
|
||||
|
||||
# 仅按单据名称检索
|
||||
hose-use bill list --keyword=差旅 --search-fields=name --count=10
|
||||
|
||||
# 按精确单号服务端极速定位
|
||||
hose-use bill list --code=CL20260901001
|
||||
|
||||
# 查询近 30 天已支付的报销单
|
||||
hose-use bill list --since=30d --stage=expense --state=paid --limit=50
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# OpenAPI 密钥与应用中心
|
||||
|
||||
本专卷覆盖 v0.8.1 引入的企业 OpenAPI 接入密钥查询,以及企业已购应用和合思应用商店探查。执行前先确认目标企业;可用 `hose-use context --json` 或 `hose-use corps list`,跨企业任务优先显式传入 `--corp=<id>`。
|
||||
|
||||
## 密钥查询 (`keys`)
|
||||
|
||||
```bash
|
||||
hose-use keys # 当前企业的密钥列表,appSecurity 默认脱敏
|
||||
hose-use keys --json # 结构化结果,appSecurity 仍默认脱敏
|
||||
hose-use openapi keys # 同一能力的 OpenAPI 别名
|
||||
hose-use store keys # 同一能力的 store 别名
|
||||
hose-use keys --reveal # 用户明确要求时才显示完整 appSecurity
|
||||
```
|
||||
|
||||
`keys` 返回密钥备注、`appKey`、状态和创建时间。`appSecurity` 是接入密码:默认输出会遮罩;`--reveal`/`-r`/`--plain` 才请求完整值。
|
||||
|
||||
安全边界:
|
||||
|
||||
- 没有用户明确授权时,不要使用 `--reveal`,也不要从结果中推断或复述明文密钥。
|
||||
- 不要把明文密钥放进聊天、日志、命令历史、提交内容或共享目录;不要使用 `--reveal -o <path>`。
|
||||
- 只需判断密钥是否存在、状态或匹配某个 `appKey` 时,使用默认脱敏输出即可。
|
||||
- 需要交给脚本处理时优先使用不带 `--reveal` 的 `--json`;若确实必须取得明文,先确认接收方和落盘位置,再尽量短暂使用并及时清理。
|
||||
|
||||
## 应用中心与应用商店 (`store`)
|
||||
|
||||
```bash
|
||||
hose-use store list # 当前企业已购/已开通应用
|
||||
hose-use store list --all # 请求完整已购应用列表
|
||||
hose-use store list <关键词> # 按名称或简介筛选已购应用
|
||||
hose-use store search <关键词> # 搜索应用商店商品
|
||||
hose-use store get <应用ID> # 查看商品详情;ID 可带或不带前导 $
|
||||
```
|
||||
|
||||
`store list` 展示应用 ID、名称、开通状态、有效期限、配置支持和绑定能力;`store search` 返回商店结果总数及当前结果;`store get` 用于查看指定应用的详情。上述命令均支持 `--json`,适合 Agent 解析。
|
||||
|
||||
若用户说“查 OpenAPI 密钥”,路由到 `keys`;若用户说“看企业买了什么应用/查应用市场”,路由到 `store list` 或 `store search`;若已有应用 ID,再用 `store get` 下钻。`openapi keys` 与 `store keys` 只作为 `keys` 的兼容别名。
|
||||
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { runAiProCli } from "./aipro-cli.js";
|
||||
import { closeApprovalDatabase, getApprovalDatabase } from "./domains/approval/db.js";
|
||||
import { ApprovalRepository } from "./domains/approval/repository.js";
|
||||
import { getVersionInfo } from "./version.js";
|
||||
|
||||
describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
beforeEach(() => {
|
||||
@@ -25,6 +26,16 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
delete process.env.HOSE_APPROVAL_DB;
|
||||
});
|
||||
|
||||
test("version/help --json only emit machine-readable stdout", async () => {
|
||||
const version = await runAiProCli(["version", "--json"]);
|
||||
const help = await runAiProCli(["help", "--json"]);
|
||||
|
||||
expect(JSON.parse(version.stdout)).toEqual(getVersionInfo("hose-aipro"));
|
||||
expect(JSON.parse(help.stdout).help).toContain("hose-aipro");
|
||||
expect(version.stderr).toBe("");
|
||||
expect(help.stderr).toBe("");
|
||||
});
|
||||
|
||||
test("完整闭环:bind 挂载 ➔ review 证据核验 ➔ decide 网关阻拦与裁决 ➔ logs 审计追溯", async () => {
|
||||
const db = getApprovalDatabase(":memory:");
|
||||
const repo = new ApprovalRepository(db);
|
||||
|
||||
+26
-9
@@ -2,7 +2,7 @@
|
||||
import { parseArgs, stringOption, booleanOption, numberOption } from "./cli/parser.js";
|
||||
import { printJson, printTable, redactSensitiveText, formatExpiresAt } from "./cli/printer.js";
|
||||
import { initCorpRuntime } from "./cli/helpers.js";
|
||||
import { createEkbClient } from "./core/auth/ekb.js";
|
||||
import { createSessionClient } from "./core/http/session-client.js";
|
||||
import {
|
||||
ApprovalService,
|
||||
ApprovalRepository,
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
import { getRawBillFlow } from "./domains/bill/api.js";
|
||||
import { approveBill, rejectBill, getTranslatorContext } from "./domains/bill/tools.js";
|
||||
import { translateBillFlowToMarkdown } from "./domains/bill/translator.js";
|
||||
import { VERSION } from "./version.js";
|
||||
import { VERSION, formatVersionLabel, getVersionInfo } from "./version.js";
|
||||
|
||||
export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; stderr: string; exitCode: number }> {
|
||||
const parsed = parseArgs(rawArgs);
|
||||
@@ -29,7 +29,7 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
const corp = runtime.selectedCorp;
|
||||
const repo = new ApprovalRepository();
|
||||
const service = new ApprovalService(repo);
|
||||
let client: Awaited<ReturnType<typeof createEkbClient>> | undefined;
|
||||
let client: Awaited<ReturnType<typeof createSessionClient>> | undefined;
|
||||
|
||||
const positional: string[] = [];
|
||||
for (let i = 0; i < rawArgs.length; i++) {
|
||||
@@ -53,6 +53,7 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
}
|
||||
|
||||
const command = (positional[0] || "help").toLowerCase();
|
||||
const jsonMode = booleanOption(parsed.options, ["json", "j"]);
|
||||
const targetSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
|
||||
const args = positional.slice(1);
|
||||
const corpId = corp?.corpId || corp?.id;
|
||||
@@ -68,11 +69,21 @@ export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string;
|
||||
const getClient = async () => {
|
||||
const activeCorpId = requireCorpId();
|
||||
if (!corp) throw new Error("未找到当前企业配置");
|
||||
client ??= await createEkbClient(corp);
|
||||
client ??= await createSessionClient(corp);
|
||||
return { client, corpId: activeCorpId };
|
||||
};
|
||||
|
||||
try {
|
||||
if (command === "version" || command === "v" || booleanOption(parsed.options, ["version", "v"])) {
|
||||
return {
|
||||
stdout: jsonMode
|
||||
? printJson(getVersionInfo("hose-aipro")) + "\n"
|
||||
: `${formatVersionLabel("hose-aipro")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
switch (command) {
|
||||
// ── 0. 运行时上下文与身份诊断 (status / whoami / context / info) ────────
|
||||
case "status":
|
||||
@@ -1136,7 +1147,11 @@ ${corpBanner}
|
||||
7. 全流程监控日志流水查看:
|
||||
hose-aipro logs [单号] # 追溯所有 AI PRO 操作流水
|
||||
`;
|
||||
return { stdout: helpText.trim() + "\n", stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: jsonMode ? printJson({ help: helpText.trim() }) + "\n" : helpText.trim() + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
} catch (err: any) {
|
||||
@@ -1151,8 +1166,8 @@ ${corpBanner}
|
||||
summary: err.message.replace(/\n+/g, " "),
|
||||
});
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `\n${err.message}\n`,
|
||||
stdout: jsonMode ? printJson({ error: true, message: err.message, exitCode: 1 }) + "\n" : "",
|
||||
stderr: jsonMode ? "" : `\n${err.message}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -1167,8 +1182,10 @@ ${corpBanner}
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[AI PRO 错误] ${err?.message || err}\n`,
|
||||
stdout: jsonMode
|
||||
? printJson({ error: true, message: String(err?.message || err), exitCode: 1 }) + "\n"
|
||||
: "",
|
||||
stderr: jsonMode ? "" : `[AI PRO 错误] ${err?.message || err}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { stringOption, booleanOption, numberOption } from "../parser.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import {
|
||||
ApprovalService,
|
||||
ApprovalGatewayBlockedError,
|
||||
@@ -19,7 +19,7 @@ export async function handleApprovalCommand(
|
||||
);
|
||||
}
|
||||
|
||||
const client = await createEkbClient(corp);
|
||||
const client = await createSessionClient(corp);
|
||||
const corpId = corp.corpId || corp.id;
|
||||
const service = new ApprovalService();
|
||||
|
||||
|
||||
@@ -64,4 +64,20 @@ describe("cli/commands/auth > aliases and subcommands", () => {
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("当前登录与企业状态");
|
||||
});
|
||||
|
||||
it("supports auth sync-seal --dry-run", async () => {
|
||||
const res = await handleAuthCommand(
|
||||
{
|
||||
area: "auth",
|
||||
action: "sync-seal",
|
||||
args: [],
|
||||
options: { "dry-run": true },
|
||||
raw: ["auth", "sync-seal", "--dry-run"],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("从 seal-use 同步企业 OpenAPI 持久化密钥");
|
||||
});
|
||||
});
|
||||
+149
-8
@@ -1,25 +1,41 @@
|
||||
import {
|
||||
canRefreshCorpAccessToken,
|
||||
fullPasswordLogin,
|
||||
fullSmsLogin,
|
||||
fullBrowserSyncLogin,
|
||||
hasOpenApiPersistentCredentials,
|
||||
sendSmsVerificationCode,
|
||||
importCredentials,
|
||||
importF12Credentials,
|
||||
importFromLink,
|
||||
parseHeadersOrCurl,
|
||||
refreshAccountCorporations,
|
||||
refreshSingleCorpAccessToken,
|
||||
} from "../../core/auth/login.js";
|
||||
import {
|
||||
listAccounts,
|
||||
getActiveAccount,
|
||||
setActiveAccount,
|
||||
} from "../../core/auth/account-store.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import { stringOption, booleanOption } from "../parser.js";
|
||||
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
||||
import { prompt } from "../helpers.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
import {
|
||||
handleAddPersistent,
|
||||
handleElevateCorp,
|
||||
handleExtractKeys,
|
||||
handleGenerateCorpLink,
|
||||
handleSyncFromSeal,
|
||||
resolveTargetCorpByArgOrContext,
|
||||
} from "./corps.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
function isHttpUrl(val?: string): boolean {
|
||||
return Boolean(val && /^https?:\/\//i.test(val.trim()));
|
||||
}
|
||||
|
||||
export async function handleAuthCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
@@ -40,9 +56,36 @@ export async function handleAuthCommand(
|
||||
case "add":
|
||||
return handleImport(parsed, runtime);
|
||||
case "add-link":
|
||||
case "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 "accounts":
|
||||
case "list":
|
||||
case "account":
|
||||
@@ -55,7 +98,7 @@ export async function handleAuthCommand(
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `未知 auth 子命令: ${action}。支持: login, status, refresh, import, add-link, accounts, switch-account\n`,
|
||||
stderr: `未知 auth 子命令: ${action}。支持: login, status, refresh, import, link, add-link, add-persistent, extract-keys, elevate, sync-seal, accounts, switch-account\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -68,6 +111,14 @@ async function handleLogin(parsed: CliParsedArgs, runtime: CliRuntime): Promise<
|
||||
const isSync = booleanOption(parsed.options, ["sync"]);
|
||||
const isInteractive = booleanOption(parsed.options, ["interactive", "i"]) || (!phone && !password && !isSms && !isSync);
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "登录并保存企业凭证", phone || (isSync ? "浏览器会话" : "交互式登录"), {
|
||||
mode: isSync ? "browser-sync" : isSms ? "sms" : "password",
|
||||
saveAll: true,
|
||||
});
|
||||
}
|
||||
requireMutationConfirmation(parsed, runtime, "登录并保存企业凭证", `hose-use auth login${phone ? ` --phone=${phone}` : ""} --yes`);
|
||||
|
||||
// 1. 浏览器同步
|
||||
if (isSync) {
|
||||
const res = await fullBrowserSyncLogin({ saveAll: true });
|
||||
@@ -157,7 +208,7 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
|
||||
if (currentCorp) {
|
||||
try {
|
||||
const client = await createEkbClient(currentCorp);
|
||||
const client = await createSessionClient(currentCorp);
|
||||
const res = await client.get("api/account/v2/session").json<{ value?: unknown }>();
|
||||
sessionValid = !!res.value;
|
||||
sessionData = res.value;
|
||||
@@ -166,6 +217,9 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
}
|
||||
}
|
||||
|
||||
const hasOpenApi = hasOpenApiPersistentCredentials(currentCorp);
|
||||
const isPersistent = canRefreshCorpAccessToken(currentCorp);
|
||||
|
||||
const statusObj = {
|
||||
activeAccount: activeAccount?.accountId || null,
|
||||
currentCorp: currentCorp
|
||||
@@ -175,6 +229,8 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
staffId: currentCorp.credentials.staffId,
|
||||
source: currentCorp.source,
|
||||
accountId: currentCorp.accountId,
|
||||
persistent: isPersistent,
|
||||
hasOpenApiKey: hasOpenApi,
|
||||
tokenValid: sessionValid,
|
||||
}
|
||||
: null,
|
||||
@@ -190,9 +246,14 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
"当前激活企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "未配置",
|
||||
"当前员工工号": currentCorp?.credentials.staffId || "-",
|
||||
"员工真实姓名": currentCorp?.staffName || currentCorp?.session?.staffName || "-",
|
||||
"凭证来源类型": formatSourceLabel(currentCorp?.source),
|
||||
"凭证来源类型": formatSourceLabel(currentCorp?.source, hasOpenApi),
|
||||
"持久化状态": isPersistent
|
||||
? hasOpenApi
|
||||
? `✅ OpenAPI 持久化密钥 (${currentCorp?.credentials.appKey})`
|
||||
: "✅ 统一认证主账号自动换票"
|
||||
: "⚪ 短期会话",
|
||||
"Token 有效性": sessionValid ? "✅ 有效 (已通过 Session 验证)" : "❌ 无效或未连接",
|
||||
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime),
|
||||
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime, isPersistent),
|
||||
};
|
||||
|
||||
if (currentCorp?.session) {
|
||||
@@ -230,6 +291,57 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
|
||||
async function handleRefresh(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const accountId = stringOption(parsed.options, ["account", "a"]);
|
||||
const explicitCorp = parsed.args[0] || stringOption(parsed.options, ["corp"]);
|
||||
const targetCorp = explicitCorp
|
||||
? resolveTargetCorpByArgOrContext(explicitCorp, runtime)
|
||||
: !accountId && !getActiveAccount() && runtime.selectedCorp && canRefreshCorpAccessToken(runtime.selectedCorp)
|
||||
? runtime.selectedCorp
|
||||
: null;
|
||||
|
||||
if (targetCorp && !accountId) {
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "刷新单企业凭证", `${targetCorp.name} (${targetCorp.id})`, {
|
||||
corpId: targetCorp.id,
|
||||
hasOpenApiKey: hasOpenApiPersistentCredentials(targetCorp),
|
||||
});
|
||||
}
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"刷新单企业凭证",
|
||||
`hose-use auth refresh ${targetCorp.id} --yes`
|
||||
);
|
||||
const newToken = await refreshSingleCorpAccessToken(targetCorp);
|
||||
if (!newToken) {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `刷新企业 [${targetCorp.name} (${targetCorp.id})] AccessToken 失败:缺少可用的账号凭证或 OpenAPI 持久化密钥\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
corpId: targetCorp.id,
|
||||
corpName: targetCorp.name,
|
||||
refreshed: true,
|
||||
expiresAt: targetCorp.auth?.expiresAt,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: `[SUCCESS] 成功刷新企业 [${targetCorp.name} (${targetCorp.id})] 的 AccessToken!\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "刷新账号下企业凭证", accountId || "当前账号", { saveAll: true });
|
||||
}
|
||||
requireMutationConfirmation(parsed, runtime, "刷新账号下企业凭证", `hose-use auth refresh${accountId ? ` --account=${accountId}` : ""} --yes`);
|
||||
const res = await refreshAccountCorporations(accountId, { saveAll: true });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
@@ -252,6 +364,22 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
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 (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "导入并保存企业凭证", corpId || "待解析企业", {
|
||||
source: raw ? "captured-input" : "manual-input",
|
||||
elevate: elevate ? "required" : noElevate ? "disabled" : "auto-best-effort",
|
||||
overwrite,
|
||||
ttl: ttl || null,
|
||||
expires: expires || null,
|
||||
});
|
||||
}
|
||||
requireMutationConfirmation(parsed, runtime, "导入并保存企业凭证", `hose-use auth ${parsed.action || "import"} --yes`);
|
||||
|
||||
if (!raw && !accessToken && process.stdin.isTTY) {
|
||||
raw = await prompt("请粘贴抓包文本 / cURL 命令行 / 协助免密 URL (直接回车则手动逐项输入): ");
|
||||
@@ -284,6 +412,11 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
overwrite,
|
||||
ttl,
|
||||
expires,
|
||||
appKey,
|
||||
keyId,
|
||||
elevate: elevate ? true : noElevate ? false : undefined,
|
||||
autoElevate: !noElevate,
|
||||
force,
|
||||
source: raw && (raw.startsWith("http://") || raw.startsWith("https://")) ? "link" : undefined,
|
||||
});
|
||||
|
||||
@@ -291,6 +424,8 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
return { stdout: printJson(imported, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const hasOpenApi = hasOpenApiPersistentCredentials(imported);
|
||||
|
||||
const summaryPairs: Record<string, unknown> = {
|
||||
"企业名称": imported.name,
|
||||
"企业 ID": imported.id,
|
||||
@@ -299,9 +434,10 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
"员工姓名": imported.staffName || imported.session?.staffName || "-",
|
||||
"手机号码": imported.session?.cellphone || "-",
|
||||
"是否管理": imported.session?.isAdmin ? "是" : "否",
|
||||
"凭证来源": formatSourceLabel(imported.source),
|
||||
"凭证来源": formatSourceLabel(imported.source, hasOpenApi),
|
||||
"持久化密钥": hasOpenApi ? `✅ 已自动提权持久化 (appKey: ${imported.credentials.appKey})` : "⚪ 未提取到 OpenAPI 密钥 (短期会话)",
|
||||
"服务节点": imported.baseUrl,
|
||||
"过期时间": formatExpiresAt(imported.auth?.expiresAt || imported.session?.expTime),
|
||||
"过期时间": formatExpiresAt(imported.auth?.expiresAt || imported.session?.expTime, hasOpenApi),
|
||||
"保存路径": `enterprises/${imported.id}.json`,
|
||||
};
|
||||
|
||||
@@ -370,6 +506,11 @@ async function handleSwitchAccount(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
return { stdout: "", stderr: "用法: hose-use auth switch-account <accountId>\n", exitCode: 1 };
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "切换当前活跃账号", target, { activeAccountId: target });
|
||||
}
|
||||
requireMutationConfirmation(parsed, runtime, "切换当前活跃账号", `hose-use auth switch-account ${target} --yes`);
|
||||
|
||||
const success = setActiveAccount(target);
|
||||
if (!success) {
|
||||
return { stdout: "", stderr: `未找到账号: ${target}\n`, exitCode: 1 };
|
||||
|
||||
+85
-26
@@ -1,7 +1,7 @@
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { booleanOption, stringOption, numberOption } from "../parser.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import {
|
||||
searchAndFormatBills,
|
||||
getBillByCodeOrId,
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
commentBill,
|
||||
resolveBillStaffIds,
|
||||
} from "../../domains/bill/tools.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
|
||||
export async function handleBillCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -32,15 +33,24 @@ export async function handleBillCommand(
|
||||
);
|
||||
}
|
||||
|
||||
const client = await createEkbClient(corp);
|
||||
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 (booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])) return;
|
||||
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
||||
throw new Error("审批动作会改变单据状态。请显式添加 --yes(或 --confirm)后重试。");
|
||||
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 继续: ");
|
||||
@@ -68,7 +78,7 @@ export async function handleBillCommand(
|
||||
});
|
||||
const resolveApproverIds = async (values: string[] | undefined): Promise<string[]> => {
|
||||
if (!values?.length) throw new Error("请通过 --approver-id、--staff 或 --to 指定员工 ID、工号或姓名");
|
||||
return resolveBillStaffIds(client, corpId, values);
|
||||
return resolveBillStaffIds(await getClient(), corpId, values);
|
||||
};
|
||||
|
||||
switch (action) {
|
||||
@@ -77,7 +87,8 @@ export async function handleBillCommand(
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill approve <单号|ID> --yes");
|
||||
const result = await approveBill(client, corpId, target, actionOptions());
|
||||
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 };
|
||||
}
|
||||
@@ -89,7 +100,8 @@ export async function handleBillCommand(
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill reject <单号|ID> --comment <原因> --yes");
|
||||
const options = actionOptions();
|
||||
if (!options.comment?.trim()) throw new Error("驳回原因不能为空,请通过 --comment 提供原因");
|
||||
const result = await rejectBill(client, corpId, target, options);
|
||||
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 };
|
||||
}
|
||||
@@ -99,8 +111,10 @@ export async function handleBillCommand(
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill transfer <单号|ID> --approver-id <员工ID> --yes");
|
||||
const options = { ...actionOptions(), approverIds: await resolveApproverIds(actionOptions().approverIds) };
|
||||
const result = await transferBill(client, corpId, target, options);
|
||||
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 };
|
||||
}
|
||||
@@ -112,8 +126,10 @@ export async function handleBillCommand(
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供审批任务、单号或单据 ID: hose-use bill add-node <单号|ID> --approver-id <员工ID> --yes");
|
||||
const options = { ...actionOptions(), approverIds: await resolveApproverIds(actionOptions().approverIds) };
|
||||
const result = await addNodeBill(client, corpId, target, options);
|
||||
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 };
|
||||
}
|
||||
@@ -123,7 +139,9 @@ export async function handleBillCommand(
|
||||
await requireWriteConfirmation();
|
||||
const target = actionTarget();
|
||||
if (!target) throw new Error("请提供单号或单据 ID: hose-use bill comment <单号|ID> --comment <内容> --yes");
|
||||
const result = await commentBill(client, corpId, target, actionOptions());
|
||||
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 };
|
||||
}
|
||||
@@ -131,18 +149,48 @@ export async function handleBillCommand(
|
||||
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(client, corpId, {
|
||||
const result = await searchAndFormatBills(await getClient(), corpId, {
|
||||
code,
|
||||
keyword,
|
||||
searchFields,
|
||||
stage,
|
||||
state,
|
||||
count,
|
||||
since,
|
||||
startDate,
|
||||
endDate,
|
||||
order,
|
||||
filterBy,
|
||||
select,
|
||||
distinct,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
@@ -173,8 +221,19 @@ export async function handleBillCommand(
|
||||
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} | 总数: ${result.total} | 本次返回: ${result.returned}) ======\n`;
|
||||
const title = `====== 单据与费用明细列表 (企业: ${corp.name}${filterTag} | 匹配总数: ${result.total} | 本次返回: ${result.returned}) ======\n`;
|
||||
const tip = `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`;
|
||||
|
||||
return {
|
||||
@@ -192,7 +251,7 @@ export async function handleBillCommand(
|
||||
throw new Error("请提供要查询的单号或单据 ID: hose-use bill get <单号|ID>");
|
||||
}
|
||||
|
||||
const bills = await getBillByCodeOrId(client, corpId, target);
|
||||
const bills = await getBillByCodeOrId(await getClient(), corpId, target);
|
||||
|
||||
if (bills.length === 0) {
|
||||
if (runtime.jsonMode) {
|
||||
@@ -211,7 +270,7 @@ export async function handleBillCommand(
|
||||
|
||||
const withRisk = booleanOption(parsed.options, ["risk", "with-risk", "audit"]);
|
||||
const riskReports = withRisk
|
||||
? await Promise.all(bills.map((bill) => getBillRisk(client, corpId, bill.billId || bill.billCode)))
|
||||
? await Promise.all(bills.map(async (bill) => getBillRisk(await getClient(), corpId, bill.billId || bill.billCode)))
|
||||
: [];
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
@@ -287,7 +346,7 @@ export async function handleBillCommand(
|
||||
case "schema":
|
||||
case "schemas":
|
||||
case "entities": {
|
||||
const { entities } = await getFieldDictionary(client, corpId, true);
|
||||
const { entities } = await getFieldDictionary(await getClient(), corpId, true);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
@@ -328,7 +387,7 @@ export async function handleBillCommand(
|
||||
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(client, corpId, target);
|
||||
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 };
|
||||
@@ -370,7 +429,7 @@ export async function handleBillCommand(
|
||||
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(client, corpId, target);
|
||||
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 };
|
||||
@@ -400,7 +459,7 @@ export async function handleBillCommand(
|
||||
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(client, corpId, target);
|
||||
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 };
|
||||
@@ -426,7 +485,7 @@ export async function handleBillCommand(
|
||||
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(client, corpId, target);
|
||||
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 };
|
||||
@@ -455,7 +514,7 @@ export async function handleBillCommand(
|
||||
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(client, corpId, target);
|
||||
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 };
|
||||
@@ -488,7 +547,7 @@ export async function handleBillCommand(
|
||||
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(client, corpId, target);
|
||||
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 };
|
||||
@@ -511,7 +570,7 @@ export async function handleBillCommand(
|
||||
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(client, corpId, target, outputDir, fileId);
|
||||
const result = await downloadBillAttachments(await getClient(), corpId, target, outputDir, fileId);
|
||||
const summary = {
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
@@ -546,7 +605,7 @@ export async function handleBillCommand(
|
||||
};
|
||||
}
|
||||
|
||||
const items = await getBillByCodeOrId(client, corpId, target);
|
||||
const items = await getBillByCodeOrId(await getClient(), corpId, target);
|
||||
if (!items || items.length === 0) {
|
||||
return {
|
||||
stdout: "",
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
} from "../../core/config/loader.js";
|
||||
import { booleanOption } from "../parser.js";
|
||||
import { printJson, printKeyValue } from "../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
export async function handleConfigCommand(
|
||||
@@ -94,6 +95,10 @@ async function handleMode(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
}
|
||||
|
||||
const isStateful = targetMode === "stateful";
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "切换全局运行模式", targetMode, { stateful: isStateful });
|
||||
}
|
||||
requireMutationConfirmation(parsed, runtime, "切换全局运行模式", `hose-use config mode ${targetMode} --yes`);
|
||||
const updated = saveGlobalConfig({ stateful: isStateful });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
@@ -112,6 +117,10 @@ async function handleTestDir(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
const globalConfig = loadGlobalConfig();
|
||||
|
||||
if (isClear) {
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "清除测试企业目录配置", globalConfig.testEnterprisesDir || "当前未设置", { testEnterprisesDir: null });
|
||||
}
|
||||
requireMutationConfirmation(parsed, runtime, "清除测试企业目录配置", "hose-use config test-dir --clear --yes");
|
||||
const updated = saveGlobalConfig({ testEnterprisesDir: undefined });
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(updated), stderr: "", exitCode: 0 };
|
||||
@@ -144,6 +153,10 @@ async function handleTestDir(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
}
|
||||
|
||||
const resolved = resolve(dirArg);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "设置测试企业目录", resolved, { testEnterprisesDir: resolved });
|
||||
}
|
||||
requireMutationConfirmation(parsed, runtime, "设置测试企业目录", `hose-use config test-dir ${dirArg} --yes`);
|
||||
const updated = saveGlobalConfig({ testEnterprisesDir: resolved });
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(updated), stderr: "", exitCode: 0 };
|
||||
@@ -209,6 +222,10 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
|
||||
};
|
||||
}
|
||||
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "更新全局配置", resolvedKey, partial);
|
||||
}
|
||||
requireMutationConfirmation(parsed, runtime, "更新全局配置", `hose-use config set ${rawKey} ${val} --yes`);
|
||||
const updated = saveGlobalConfig(partial);
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson(updated), stderr: "", exitCode: 0 };
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { getActiveAccount } from "../../core/auth/account-store.js";
|
||||
import { canRefreshCorpAccessToken, hasOpenApiPersistentCredentials } from "../../core/auth/login.js";
|
||||
import {
|
||||
resolveGlobalConfigFile,
|
||||
resolvePrimaryEnterprisesDir,
|
||||
@@ -47,8 +48,9 @@ export async function handleContextCommand(
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const validCorps = allCorps.filter((c) => !c.expiresAt || c.expiresAt > now);
|
||||
const expiredCorps = allCorps.filter((c) => c.expiresAt && c.expiresAt <= now);
|
||||
const validCorps = allCorps.filter((c) => c.persistent || !c.expiresAt || c.expiresAt > now);
|
||||
const expiredCorps = allCorps.filter((c) => !c.persistent && c.expiresAt && c.expiresAt <= now);
|
||||
const currentPersistent = currentCorp ? canRefreshCorpAccessToken(currentCorp) : false;
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
@@ -76,11 +78,13 @@ export async function handleContextCommand(
|
||||
staffId: currentCorp.credentials?.staffId || currentCorp.staffId,
|
||||
userName: currentCorp.staffName || currentCorp.session?.staffName || null,
|
||||
source: currentCorp.source,
|
||||
persistent: currentPersistent,
|
||||
expiresAt: currentCorp.auth?.expiresAt || currentCorp.session?.expTime,
|
||||
expired:
|
||||
(currentCorp.auth?.expiresAt || currentCorp.session?.expTime)
|
||||
? (currentCorp.auth?.expiresAt || currentCorp.session?.expTime)! <= now
|
||||
: false,
|
||||
expired: currentPersistent
|
||||
? false
|
||||
: (currentCorp.auth?.expiresAt || currentCorp.session?.expTime)
|
||||
? (currentCorp.auth?.expiresAt || currentCorp.session?.expTime)! <= now
|
||||
: false,
|
||||
baseUrl: currentCorp.baseUrl,
|
||||
accountId: currentCorp.accountId || null,
|
||||
}
|
||||
@@ -130,8 +134,8 @@ export async function handleContextCommand(
|
||||
` 当前激活企业 : ${currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "⚠️ 未激活任何企业"}`,
|
||||
` 当前操作员工 : ${corpStaffId}`,
|
||||
` 员工真实姓名 : ${corpStaffName}`,
|
||||
` 凭证来源类型 : ${currentCorp ? formatSourceLabel(currentCorp.source) : "-"}`,
|
||||
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt) : "-"}`,
|
||||
` 凭证来源类型 : ${currentCorp ? formatSourceLabel(currentCorp.source, hasOpenApiPersistentCredentials(currentCorp)) : "-"}`,
|
||||
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt, currentPersistent) : "-"}`,
|
||||
` 主站 BaseURL : ${currentCorp?.baseUrl || "-"}`,
|
||||
` 已配置企业总数: ${allCorps.length} 家 (有效: ${validCorps.length} 家, 已过期: ${expiredCorps.length} 家)`,
|
||||
` AI PRO 规约库 : ${scopesStr}`,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import { parseHeadersOrCurl } from "../../core/auth/login.js";
|
||||
import { resolveCorpCluster } from "../../core/auth/easo.js";
|
||||
import { resolveCorpCluster } from "../../core/http/unity-client.js";
|
||||
import { handleCorpsCommand } from "./corps.js";
|
||||
import type { CliRuntime } from "../types.js";
|
||||
|
||||
@@ -34,7 +34,7 @@ describe("core/auth/login > parseHeadersOrCurl & URL link parsing", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("core/auth/easo > resolveCorpCluster", () => {
|
||||
describe("core/http/unity-client > resolveCorpCluster", () => {
|
||||
it("prioritizes explicit cluster config", () => {
|
||||
expect(resolveCorpCluster({ cluster: "wx2", baseUrl: "https://app.ekuaibao.com" })).toBe("wx2");
|
||||
});
|
||||
@@ -315,4 +315,52 @@ describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
|
||||
expect(res.stdout).toContain("search <关键词>");
|
||||
expect(res.stdout).toContain("find");
|
||||
});
|
||||
|
||||
it("generates login link via corps link [corp] with preserveSensitiveStdout=true", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = (async () =>
|
||||
new Response(JSON.stringify({ items: [] }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
})) as unknown as typeof fetch;
|
||||
|
||||
try {
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "link",
|
||||
args: ["corpAlpha"],
|
||||
options: {},
|
||||
raw: ["corps", "link", "corpAlpha"],
|
||||
},
|
||||
searchRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.preserveSensitiveStdout).toBe(true);
|
||||
expect(res.stdout).toContain("thirdparty.html?accessToken=token-alpha&ekbCorpId=alphaPhysicalId");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
it("supports corps add-persistent --dry-run", async () => {
|
||||
const res = await handleCorpsCommand(
|
||||
{
|
||||
area: "corps",
|
||||
action: "add-persistent",
|
||||
args: [],
|
||||
options: {
|
||||
"app-key": "key-1",
|
||||
"app-security": "sec-1",
|
||||
"dry-run": true,
|
||||
},
|
||||
raw: ["corps", "add-persistent", "--app-key=key-1", "--app-security=sec-1", "--dry-run"],
|
||||
},
|
||||
searchRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("通过 OpenAPI 持久化密钥接入企业");
|
||||
});
|
||||
});
|
||||
+670
-14
@@ -1,9 +1,25 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { importFromLink } from "../../core/auth/login.js";
|
||||
import {
|
||||
canRefreshCorpAccessToken,
|
||||
elevateCorpWithOpenApiKey,
|
||||
extractOpenApiKeysFromLink,
|
||||
fetchHoseRoleDefGroups,
|
||||
getCorpProvisionalAuthLink,
|
||||
hasOpenApiPersistentCredentials,
|
||||
importFromLink,
|
||||
listHoseStaffsByOpenApi,
|
||||
maskOpenApiSecurity,
|
||||
onboardHosePersistent,
|
||||
probeHoseDomain,
|
||||
syncOpenApiFromSealUse,
|
||||
} from "../../core/auth/login.js";
|
||||
import { resolveWritableEnterprisesDir } from "../../core/config/loader.js";
|
||||
import { stringOption, booleanOption } from "../parser.js";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import { stringOption, booleanOption, numberOption } from "../parser.js";
|
||||
import { prompt } from "../helpers.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";
|
||||
|
||||
const FIELD_LABEL_MAP: Record<string, string> = {
|
||||
@@ -15,6 +31,34 @@ const FIELD_LABEL_MAP: Record<string, string> = {
|
||||
accountId: "所属账号",
|
||||
};
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
export async function handleCorpsCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime
|
||||
@@ -39,15 +83,46 @@ export async function handleCorpsCommand(
|
||||
case "active":
|
||||
return handleCurrent(parsed, runtime);
|
||||
case "add-link":
|
||||
case "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, add-link\n`,
|
||||
stderr: `未知 corps 子命令: ${action}。支持: list, search, switch, current, link, add-link, add-persistent, extract-keys, elevate, sync-seal\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
@@ -63,7 +138,12 @@ export function printCorpsHelp(): string {
|
||||
search <关键词> 根据关键词模糊搜索企业(支持 id, name, corpId, staffId, staffName, accountId,别名: find)
|
||||
switch <企业ID> 切换当前激活的工作企业 (别名: use)
|
||||
current 查看当前激活的企业配置与凭证详情
|
||||
add-link <URL> 从第三方协助/免密链接导入企业凭证
|
||||
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 格式输出
|
||||
@@ -74,6 +154,9 @@ export function printCorpsHelp(): string {
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -114,6 +197,7 @@ async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
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,
|
||||
@@ -126,6 +210,7 @@ async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
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[] }> = [];
|
||||
@@ -175,6 +260,7 @@ async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
baseUrl: m.baseUrl,
|
||||
current: m.current,
|
||||
expiresAt: m.expiresAt,
|
||||
persistent: m.persistent,
|
||||
matchedFields: m.matchedFields,
|
||||
})),
|
||||
},
|
||||
@@ -204,7 +290,7 @@ async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
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),
|
||||
formatExpiresAt(m.expiresAt, m.persistent),
|
||||
];
|
||||
});
|
||||
|
||||
@@ -247,7 +333,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
c.name,
|
||||
c.staffId,
|
||||
c.source || "manual",
|
||||
formatExpiresAt(c.expiresAt),
|
||||
formatExpiresAt(c.expiresAt, c.persistent),
|
||||
c.accountId || "-",
|
||||
]);
|
||||
|
||||
@@ -269,6 +355,11 @@ async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
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 {
|
||||
@@ -300,13 +391,17 @@ async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
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),
|
||||
"Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime),
|
||||
"凭证来源": 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 的统一执行环境",
|
||||
@@ -345,39 +440,153 @@ async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
};
|
||||
}
|
||||
|
||||
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 = numberOption(parsed.options, ["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,
|
||||
};
|
||||
}
|
||||
|
||||
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) {
|
||||
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 <企业别名>] [--ttl 3d|--expires 3] [--overwrite]\n",
|
||||
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 targetDir = resolveWritableEnterprisesDir();
|
||||
const savedPath = join(targetDir, `${corp.id}.json`);
|
||||
const hasOpenApi = hasOpenApiPersistentCredentials(corp);
|
||||
|
||||
const summaryPairs: Record<string, unknown> = {
|
||||
"企业名称": corp.name,
|
||||
@@ -387,9 +596,10 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
"员工姓名": corp.staffName || corp.session?.staffName || "-",
|
||||
"手机号码": corp.session?.cellphone || "-",
|
||||
"是否管理": corp.session?.isAdmin ? "是" : "否",
|
||||
"凭证来源": formatSourceLabel(corp.source),
|
||||
"凭证来源": formatSourceLabel(corp.source, hasOpenApi),
|
||||
"持久化密钥": hasOpenApi ? `✅ 已自动提权持久化 (appKey: ${corp.credentials.appKey})` : "⚪ 未提取到 OpenAPI 密钥 (短期会话)",
|
||||
"服务节点": corp.baseUrl,
|
||||
"过期时间": formatExpiresAt(corp.auth?.expiresAt || corp.session?.expTime),
|
||||
"过期时间": formatExpiresAt(corp.auth?.expiresAt || corp.session?.expTime, hasOpenApi),
|
||||
"保存路径": savedPath,
|
||||
};
|
||||
|
||||
@@ -418,3 +628,449 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import { searchDimensions, resolveDimension } from "../../domains/dimension/tools.js";
|
||||
|
||||
export async function handleDimensionCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。");
|
||||
const client = await createEkbClient(corp);
|
||||
const client = await createSessionClient(corp);
|
||||
const corpId = corp.corpId || corp.id;
|
||||
const action = parsed.action?.toLowerCase() || "list";
|
||||
if (["list", "search", "catalogs", undefined].includes(action)) {
|
||||
|
||||
@@ -229,8 +229,9 @@ describe("CLI - feetype 费用类型管理命令", () => {
|
||||
options: {
|
||||
name: "酒店住宿",
|
||||
parent: "差旅费用",
|
||||
yes: true,
|
||||
},
|
||||
raw: ["feetype", "create", "--name=酒店住宿", "--parent=差旅费用"],
|
||||
raw: ["feetype", "create", "--name=酒店住宿", "--parent=差旅费用", "--yes"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
@@ -266,8 +267,8 @@ describe("CLI - feetype 费用类型管理命令", () => {
|
||||
area: "feetype",
|
||||
action: "update",
|
||||
args: ["酒店住宿"],
|
||||
options: { desc: "新说明" },
|
||||
raw: ["feetype", "update", "酒店住宿", "--desc=新说明"],
|
||||
options: { desc: "新说明", yes: true },
|
||||
raw: ["feetype", "update", "酒店住宿", "--desc=新说明", "--yes"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
@@ -324,8 +325,8 @@ describe("CLI - feetype 费用类型管理命令", () => {
|
||||
area: "feetype",
|
||||
action: "enable",
|
||||
args: ["酒店住宿"],
|
||||
options: {},
|
||||
raw: ["feetype", "enable", "酒店住宿"],
|
||||
options: { yes: true },
|
||||
raw: ["feetype", "enable", "酒店住宿", "--yes"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
@@ -355,8 +356,8 @@ describe("CLI - feetype 费用类型管理命令", () => {
|
||||
area: "feetype",
|
||||
action: "move",
|
||||
args: ["酒店住宿"],
|
||||
options: { parent: "办公费" },
|
||||
raw: ["feetype", "move", "酒店住宿", "--parent=办公费"],
|
||||
options: { parent: "办公费", yes: true },
|
||||
raw: ["feetype", "move", "酒店住宿", "--parent=办公费", "--yes"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
@@ -368,6 +369,28 @@ describe("CLI - feetype 费用类型管理命令", () => {
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("feetype create --dry-run 不创建费用类型", async () => {
|
||||
const spy = spyOn(feetypeTools, "createFeeType").mockResolvedValue({} as any);
|
||||
|
||||
const res = await handleFeeTypeCommand(
|
||||
{
|
||||
area: "feetype",
|
||||
action: "create",
|
||||
args: [],
|
||||
options: { name: "酒店住宿", parent: "差旅费用", "dry-run": true },
|
||||
raw: ["feetype", "create", "--name=酒店住宿", "--parent=差旅费用", "--dry-run"],
|
||||
},
|
||||
dummyRuntimeWithCorp
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("DRY-RUN");
|
||||
expect(res.stdout).toContain("新建费用类型");
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
|
||||
spy.mockRestore();
|
||||
});
|
||||
|
||||
it("feetype fields 打印报账与申请字段表格", async () => {
|
||||
const spy = spyOn(feetypeTools, "getFeeTypeFieldsList").mockResolvedValue({
|
||||
feeType: {
|
||||
|
||||
+89
-10
@@ -1,7 +1,7 @@
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import {
|
||||
createFeeType,
|
||||
disableFeeTypeItem,
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
updateFeeTypeInfo,
|
||||
} from "../../domains/feetype/tools.js";
|
||||
import { FeeTypeNode } from "../../domains/feetype/types.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
|
||||
/**
|
||||
* 递归渲染树形层级格式
|
||||
@@ -65,9 +66,13 @@ export async function handleFeeTypeCommand(
|
||||
);
|
||||
}
|
||||
|
||||
const client = await createEkbClient(corp);
|
||||
const corpId = corp.corpId || corp.id;
|
||||
const action = (parsed.action?.toLowerCase() || "list").trim();
|
||||
let client: Awaited<ReturnType<typeof createSessionClient>> | undefined;
|
||||
const getClient = async () => {
|
||||
client ??= await createSessionClient(corp);
|
||||
return client;
|
||||
};
|
||||
|
||||
// ── 1. 列表 / 树形展示 (list / tree) ──────────────────────────────────────────
|
||||
if (["list", "tree", "all", "search"].includes(action)) {
|
||||
@@ -80,7 +85,7 @@ export async function handleFeeTypeCommand(
|
||||
const keyword =
|
||||
stringOption(parsed.options, ["keyword", "q", "query"]) || parsed.args[0];
|
||||
|
||||
const result = await listFeeTypes(client, corpId, {
|
||||
const result = await listFeeTypes(await getClient(), corpId, {
|
||||
all: includeAll,
|
||||
flat: isFlat,
|
||||
keyword,
|
||||
@@ -142,7 +147,7 @@ export async function handleFeeTypeCommand(
|
||||
}
|
||||
|
||||
const includeSpecs = booleanOption(parsed.options, ["specs", "spec", "fields"]);
|
||||
const detail = await getFeeTypeDetail(client, corpId, target, { includeSpecs });
|
||||
const detail = await getFeeTypeDetail(await getClient(), corpId, target, { includeSpecs });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
@@ -215,7 +220,26 @@ export async function handleFeeTypeCommand(
|
||||
const color = stringOption(parsed.options, ["color"]);
|
||||
const icon = stringOption(parsed.options, ["icon"]);
|
||||
|
||||
const created = await createFeeType(client, corpId, {
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"新建费用类型",
|
||||
`hose-use feetype create --name="${name.trim()}" --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "新建费用类型", name.trim(), {
|
||||
corpId,
|
||||
name: name.trim(),
|
||||
code: code || null,
|
||||
parentId: parent || null,
|
||||
enName: enName || null,
|
||||
description: description || null,
|
||||
color: color || null,
|
||||
icon: icon || null,
|
||||
});
|
||||
}
|
||||
|
||||
const created = await createFeeType(await getClient(), corpId, {
|
||||
name: name.trim(),
|
||||
code,
|
||||
parentId: parent,
|
||||
@@ -283,7 +307,25 @@ export async function handleFeeTypeCommand(
|
||||
throw new Error("请至少提供一个待更新的属性参数 (例如 --name, --code, --desc, --color)");
|
||||
}
|
||||
|
||||
const updated = await updateFeeTypeInfo(client, corpId, target, {
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"修改费用类型",
|
||||
`hose-use feetype update ${target} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "修改费用类型", target, {
|
||||
corpId,
|
||||
name: name ?? null,
|
||||
code: code ?? null,
|
||||
enName: enName ?? null,
|
||||
description: description ?? null,
|
||||
color: color ?? null,
|
||||
icon: icon ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
const updated = await updateFeeTypeInfo(await getClient(), corpId, target, {
|
||||
name,
|
||||
code,
|
||||
enName,
|
||||
@@ -329,7 +371,17 @@ export async function handleFeeTypeCommand(
|
||||
throw new Error("请指定待停用的费用类型: hose-use feetype disable <ID|编码|名称>");
|
||||
}
|
||||
|
||||
const res = await disableFeeTypeItem(client, corpId, target);
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"停用费用类型",
|
||||
`hose-use feetype disable ${target} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "停用费用类型", target, { corpId, active: false });
|
||||
}
|
||||
|
||||
const res = await disableFeeTypeItem(await getClient(), corpId, target);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
@@ -365,7 +417,21 @@ export async function handleFeeTypeCommand(
|
||||
const recursive =
|
||||
booleanOption(parsed.options, ["recursive", "r"]) !== false;
|
||||
|
||||
const res = await enableFeeTypeItem(client, corpId, target, { recursive });
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"启用费用类型",
|
||||
`hose-use feetype enable ${target} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "启用费用类型", target, {
|
||||
corpId,
|
||||
active: true,
|
||||
recursive,
|
||||
});
|
||||
}
|
||||
|
||||
const res = await enableFeeTypeItem(await getClient(), corpId, target, { recursive });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
@@ -404,7 +470,20 @@ export async function handleFeeTypeCommand(
|
||||
throw new Error("请指定目标父级: --parent=<目标父级ID|编码|名称> 或 --parent=root (移至顶级)");
|
||||
}
|
||||
|
||||
const res = await moveFeeTypeItem(client, corpId, target, parentTarget);
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"移动费用类型",
|
||||
`hose-use feetype move ${target} --parent=${parentTarget} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "移动费用类型", target, {
|
||||
corpId,
|
||||
parent: parentTarget,
|
||||
});
|
||||
}
|
||||
|
||||
const res = await moveFeeTypeItem(await getClient(), corpId, target, parentTarget);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
@@ -443,7 +522,7 @@ export async function handleFeeTypeCommand(
|
||||
throw new Error("请指定费用类型: hose-use feetype fields <ID|编码|名称>");
|
||||
}
|
||||
|
||||
const res = await getFeeTypeFieldsList(client, corpId, target);
|
||||
const res = await getFeeTypeFieldsList(await getClient(), corpId, target);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { fetchOpenApiKeys } from "../../domains/store/tools.js";
|
||||
import { booleanOption } from "../parser.js";
|
||||
import { selectOpenApiKey } from "../../core/auth/login.js";
|
||||
import { saveCorpConfig } from "../../core/config/loader.js";
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
function formatDate(ts: number): string {
|
||||
@@ -39,9 +42,80 @@ export async function handleKeysCommand(
|
||||
parsed.action === "reveal" ||
|
||||
parsed.args[0] === "reveal";
|
||||
|
||||
const save =
|
||||
booleanOption(parsed.options, ["save", "persist", "elevate"]) ||
|
||||
parsed.action === "save" ||
|
||||
parsed.args[0] === "save";
|
||||
|
||||
const appKeyOpt = stringOption(parsed.options, ["app-key", "appKey"]);
|
||||
const keyIdOpt = stringOption(parsed.options, ["key-id", "keyId"]);
|
||||
const force = booleanOption(parsed.options, ["force", "f"]);
|
||||
|
||||
if (save) {
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "提取并持久化企业 OpenAPI 密钥", `${currentCorp.name} (${currentCorp.id})`, {
|
||||
corpId: currentCorp.id,
|
||||
appKey: appKeyOpt || "auto-select",
|
||||
keyId: keyIdOpt || null,
|
||||
});
|
||||
}
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"提取并持久化企业 OpenAPI 密钥",
|
||||
`hose-use keys --corp=${currentCorp.id} --save --yes`
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const keys = await fetchOpenApiKeys(currentCorp);
|
||||
|
||||
if (save) {
|
||||
const selected = selectOpenApiKey(
|
||||
keys.map((k) => ({
|
||||
id: k.id,
|
||||
name: k.name || undefined,
|
||||
appKey: k.appKey,
|
||||
appSecurity: k.appSecurity,
|
||||
active: k.active,
|
||||
createTime: k.createTime,
|
||||
updateTime: k.updateTime,
|
||||
})),
|
||||
currentCorp.id,
|
||||
{ appKey: appKeyOpt, keyId: keyIdOpt, force }
|
||||
);
|
||||
currentCorp.credentials.appKey = selected.appKey;
|
||||
currentCorp.credentials.appSecurity = selected.appSecurity;
|
||||
const savedPath = saveCorpConfig(currentCorp);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(
|
||||
{
|
||||
saved: true,
|
||||
corpId: currentCorp.id,
|
||||
corpName: currentCorp.name,
|
||||
appKey: selected.appKey,
|
||||
appSecurity: reveal ? selected.appSecurity : maskSecret(selected.appSecurity),
|
||||
keyName: selected.name || "-",
|
||||
path: savedPath,
|
||||
},
|
||||
runtime.outputOptions
|
||||
),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: reveal,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] 已为企业 [${currentCorp.name}] 持久化保存 OpenAPI 密钥 (appKey: ${selected.appKey})!\n保存路径: ${savedPath}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: reveal,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
const outputData = reveal
|
||||
? keys
|
||||
@@ -53,6 +127,7 @@ export async function handleKeysCommand(
|
||||
stdout: printJson(outputData, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: reveal,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -81,12 +156,13 @@ export async function handleKeysCommand(
|
||||
const title = `====== [${currentCorp.name}] 企业 OpenAPI 接入密钥列表 (共 ${keys.length} 个) ======`;
|
||||
const hint = reveal
|
||||
? ""
|
||||
: "\n提示: 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整明文;使用 --json 可输出完整结构。\n";
|
||||
: "\n提示: 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整明文;附加 --save --yes 可持久化到当前企业配置;使用 --json 可输出完整结构。\n";
|
||||
|
||||
return {
|
||||
stdout: `${title}\n\n${table}\n${hint}`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
preserveSensitiveStdout: reveal,
|
||||
};
|
||||
} catch (err: any) {
|
||||
return {
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import { filterMessages, listMessages, mergeMessages, readMessage } from "../../domains/message/tools.js";
|
||||
import type { MessageItem } from "../../domains/message/types.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
|
||||
function formatTime(value: number | undefined): string {
|
||||
return value === undefined ? "-" : new Date(value).toISOString().replace("T", " ").slice(0, 16);
|
||||
@@ -26,10 +27,10 @@ export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRu
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) throw new Error("未指定或未找到有效企业。请运行 hose-use corps list 或指定 --corp=<id>");
|
||||
const action = parsed.action || parsed.args[0] || "list";
|
||||
const client = await createEkbClient(corp);
|
||||
const corpId = corp.corpId || corp.id;
|
||||
|
||||
if (action === "count" || action === "unread") {
|
||||
const client = await createSessionClient(corp);
|
||||
const result = await listMessages(client, corpId, { start: 0, count: 1, read: false });
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, unread: result.total }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `未读消息: ${result.total}\n`, stderr: "", exitCode: 0 };
|
||||
@@ -38,12 +39,22 @@ export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRu
|
||||
if (action === "read" || action === "mark-read") {
|
||||
const messageId = parsed.args[0] || stringOption(parsed.options, ["id", "message-id"]);
|
||||
if (!messageId) return { stdout: "", stderr: "用法: hose-use message read <messageId>\n", exitCode: 1 };
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "标记消息为已读", messageId, { read: true });
|
||||
}
|
||||
requireMutationConfirmation(parsed, runtime, "标记消息为已读", `hose-use message read ${messageId} --yes`);
|
||||
const client = await createSessionClient(corp);
|
||||
await readMessage(client, corpId, messageId);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, id: messageId, read: true }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return { stdout: `已标记消息为已读: ${messageId}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
if (action === "read-all" || action === "mark-all-read") {
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "批量标记未读消息为已读", `corp:${corpId}`, { read: true, allUnread: true });
|
||||
}
|
||||
requireMutationConfirmation(parsed, runtime, "批量标记未读消息为已读", "hose-use message read-all --yes");
|
||||
const client = await createSessionClient(corp);
|
||||
const ids: string[] = [];
|
||||
let start = 0;
|
||||
let total = 0;
|
||||
@@ -63,6 +74,8 @@ export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRu
|
||||
return { stdout: "", stderr: `未知消息子命令: ${action}。支持: list, count, read <messageId>, read-all\n`, exitCode: 1 };
|
||||
}
|
||||
|
||||
const client = await createSessionClient(corp);
|
||||
|
||||
const read = booleanOption(parsed.options, ["read"]);
|
||||
const unread = booleanOption(parsed.options, ["unread"]);
|
||||
const all = booleanOption(parsed.options, ["all"]);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import { getPermissions } from "../../domains/permission/tools.js";
|
||||
|
||||
export async function handlePermissionCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
@@ -8,7 +8,7 @@ export async function handlePermissionCommand(parsed: CliParsedArgs, runtime: Cl
|
||||
if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。");
|
||||
const action = parsed.action?.toLowerCase() || "get";
|
||||
if (!["get", "list", "show"].includes(action)) throw new Error(`未知 permission 子命令: ${action}。支持: get`);
|
||||
const client = await createEkbClient(corp);
|
||||
const client = await createSessionClient(corp);
|
||||
const report = await getPermissions(client, corp.corpId || corp.id);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId: corp.corpId || corp.id, corpName: corp.name, ...report }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = report.permissions.map((item) => [item.name, item.auth ? "启用" : "停用"]);
|
||||
|
||||
@@ -140,7 +140,7 @@ describe("CLI - platform 命令与 record 动作", () => {
|
||||
spies.push(toggleSpy);
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "record", args: ["toggle", "platform-1", "entity-1", "r-1"], options: {}, raw: [] },
|
||||
{ area: "platform", action: "record", args: ["toggle", "platform-1", "entity-1", "r-1"], options: { yes: true }, raw: ["platform", "record", "toggle", "platform-1", "entity-1", "r-1", "--yes"] },
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
@@ -161,8 +161,8 @@ describe("CLI - platform 命令与 record 动作", () => {
|
||||
area: "platform",
|
||||
action: "record",
|
||||
args: ["edit", "platform-1", "entity-1", "r-1"],
|
||||
options: { data: '{"name":"更新后的名称"}' },
|
||||
raw: [],
|
||||
options: { data: '{"name":"更新后的名称"}', yes: true },
|
||||
raw: ["platform", "record", "edit", "platform-1", "entity-1", "r-1", "--yes"],
|
||||
},
|
||||
dummyRuntime
|
||||
);
|
||||
@@ -188,7 +188,7 @@ describe("CLI - platform 命令与 record 动作", () => {
|
||||
spies.push(recomputeSpy);
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "record", args: ["recompute", "platform-1", "entity-1", "r-1"], options: {}, raw: [] },
|
||||
{ area: "platform", action: "record", args: ["recompute", "platform-1", "entity-1", "r-1"], options: { yes: true }, raw: ["platform", "record", "recompute", "platform-1", "entity-1", "r-1", "--yes"] },
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ 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";
|
||||
|
||||
function requiredTarget(parsed: CliParsedArgs, index: number, usage: string): string {
|
||||
const target = parsed.args[index]?.trim();
|
||||
@@ -251,6 +252,20 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
: parsed.options.active !== undefined
|
||||
? booleanOption(parsed.options, ["active"], true)
|
||||
: undefined;
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"切换业务对象记录状态",
|
||||
`hose-use platform record toggle ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "切换业务对象记录状态", recordId, {
|
||||
corpId: resolved.corpId,
|
||||
platformId: resolved.platform.id,
|
||||
entityId: resolved.entity.id,
|
||||
active: explicitState ?? "toggle",
|
||||
});
|
||||
}
|
||||
const res = await api.toggleRecordState(resolved.clients.ekbClient, resolved.corpId, recordId, explicitState);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
@@ -278,6 +293,21 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
}
|
||||
}
|
||||
const activeOpt = parsed.options.active !== undefined ? booleanOption(parsed.options, ["active"], true) : undefined;
|
||||
const changes = {
|
||||
dataLinkEntityId: resolved.entity.id,
|
||||
dataLinkId: recordId,
|
||||
form,
|
||||
active: activeOpt ?? null,
|
||||
};
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"编辑业务对象记录",
|
||||
`hose-use platform record edit ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "编辑业务对象记录", recordId, changes);
|
||||
}
|
||||
const result = await api.editRecord(resolved.clients.ekbClient, resolved.corpId, {
|
||||
dataLinkEntityId: resolved.entity.id,
|
||||
dataLinkId: recordId,
|
||||
@@ -293,6 +323,19 @@ async function handleRecordAction(parsed: CliParsedArgs, runtime: CliRuntime): P
|
||||
}
|
||||
case "recompute":
|
||||
case "recalc": {
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"触发业务对象记录台账重算",
|
||||
`hose-use platform record recompute ${resolved.platform.id} ${resolved.entity.id} ${recordId} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "触发业务对象记录台账重算", recordId, {
|
||||
corpId: resolved.corpId,
|
||||
platformId: resolved.platform.id,
|
||||
entityId: resolved.entity.id,
|
||||
});
|
||||
}
|
||||
const result = await api.recomputeRecordLedger(resolved.clients.ekbClient, resolved.corpId, recordId);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ success: true, recordId, result }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
return {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { getEasoClient } from "../../core/auth/easo.js";
|
||||
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 { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
@@ -17,6 +17,9 @@ export async function handleProbeCommand(
|
||||
};
|
||||
}
|
||||
|
||||
const hasOpenApi = hasOpenApiPersistentCredentials(currentCorp);
|
||||
const isPersistent = canRefreshCorpAccessToken(currentCorp);
|
||||
|
||||
const results: Record<string, unknown> = {
|
||||
enterprise: {
|
||||
id: currentCorp.id,
|
||||
@@ -25,6 +28,8 @@ export async function handleProbeCommand(
|
||||
baseUrl: currentCorp.baseUrl,
|
||||
source: currentCorp.source,
|
||||
accountId: currentCorp.accountId,
|
||||
persistent: isPersistent,
|
||||
hasOpenApiKey: hasOpenApi,
|
||||
},
|
||||
ekbSession: { status: "pending" },
|
||||
easoToken: { status: "pending" },
|
||||
@@ -32,10 +37,10 @@ export async function handleProbeCommand(
|
||||
};
|
||||
|
||||
// 1. 独立测试 EKB 主站 Session
|
||||
let ekbClient: Awaited<ReturnType<typeof createEkbClient>> | null = null;
|
||||
let sessionClient: Awaited<ReturnType<typeof createSessionClient>> | null = null;
|
||||
try {
|
||||
ekbClient = await createEkbClient(currentCorp);
|
||||
const sessionRes = await ekbClient
|
||||
sessionClient = await createSessionClient(currentCorp);
|
||||
const sessionRes = await sessionClient
|
||||
.get("api/account/v2/session")
|
||||
.json<{ value?: { userId?: string; loginStaffId?: string; expTime?: number } }>();
|
||||
|
||||
@@ -54,9 +59,9 @@ export async function handleProbeCommand(
|
||||
|
||||
// 2. 独立测试自建应用列表访问
|
||||
let platforms: any[] = [];
|
||||
if (ekbClient) {
|
||||
if (sessionClient) {
|
||||
try {
|
||||
platforms = await api.listPlatforms(ekbClient, currentCorp.credentials.corpId);
|
||||
platforms = await api.listPlatforms(sessionClient, currentCorp.credentials.corpId);
|
||||
results.platformAccess = {
|
||||
status: "ok",
|
||||
totalPlatforms: platforms.length,
|
||||
@@ -99,8 +104,13 @@ export async function handleProbeCommand(
|
||||
"企业 ID": currentCorp.id,
|
||||
"员工工号": currentCorp.credentials.staffId,
|
||||
"员工姓名": currentCorp.staffName || currentCorp.session?.staffName || "-",
|
||||
"凭证来源": formatSourceLabel(currentCorp.source),
|
||||
"Token 过期时间": formatExpiresAt(currentCorp.auth?.expiresAt || currentCorp.session?.expTime),
|
||||
"凭证来源": formatSourceLabel(currentCorp.source, hasOpenApi),
|
||||
"持久化状态": isPersistent
|
||||
? hasOpenApi
|
||||
? `✅ OpenAPI 持久化密钥 (${currentCorp.credentials.appKey})`
|
||||
: "✅ 统一认证主账号自动换票"
|
||||
: "⚪ 短期会话",
|
||||
"Token 过期时间": formatExpiresAt(currentCorp.auth?.expiresAt || currentCorp.session?.expTime, isPersistent),
|
||||
"主站 Session 连通": (results.ekbSession as any).status === "ok" ? "🟢 正常" : "🔴 异常",
|
||||
"EASO 引擎鉴权换票": (results.easoToken as any).status === "ok" ? "🟢 握手成功" : "🔴 失败",
|
||||
"自建应用扫描": (results.platformAccess as any).status === "ok" ? `🟢 可访问 (${(results.platformAccess as any).totalPlatforms} 个自建应用)` : "🔴 失败",
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import { getRoleGroups, getRoleMembers, searchRoles } from "../../domains/role/tools.js";
|
||||
|
||||
export async function handleRoleCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。");
|
||||
const client = await createEkbClient(corp), corpId = corp.corpId || corp.id;
|
||||
const client = await createSessionClient(corp), corpId = corp.corpId || corp.id;
|
||||
const action = parsed.action?.toLowerCase() || "list";
|
||||
if (["list", "search"].includes(action)) {
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]) || parsed.args[0];
|
||||
|
||||
@@ -87,7 +87,8 @@ describe("CLI - hose-use rule 规则与场景索引命令", () => {
|
||||
"add",
|
||||
"办公采购",
|
||||
"单笔采购大于1万,[必须附采购合同]{硬性};[建议由采购员集中办理]{建议}。",
|
||||
"--json"
|
||||
"--json",
|
||||
"--yes"
|
||||
]);
|
||||
expect(addRes.exitCode).toBe(0);
|
||||
const addData = JSON.parse(addRes.stdout);
|
||||
@@ -102,6 +103,41 @@ describe("CLI - hose-use rule 规则与场景索引命令", () => {
|
||||
expect(scopesData.scopes[2].scope).toBe("办公采购");
|
||||
});
|
||||
|
||||
test("hose-use rule add --dry-run 只预览且不写入数据库", async () => {
|
||||
const res = await runCli([
|
||||
"rule",
|
||||
"add",
|
||||
"办公采购",
|
||||
"单笔采购大于1万,[必须附采购合同]{硬性}。",
|
||||
"--json",
|
||||
"--dry-run",
|
||||
]);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
const data = JSON.parse(res.stdout);
|
||||
expect(data.dryRun).toBe(true);
|
||||
expect(data.operation).toBe("新增审批规则");
|
||||
expect(data.changes.scope).toBe("办公采购");
|
||||
|
||||
const scopes = await runCli(["rule", "scopes", "--json"]);
|
||||
expect(JSON.parse(scopes.stdout).count).toBe(2);
|
||||
});
|
||||
|
||||
test("hose-use rule add 未确认时拒绝写入并给出下一步", async () => {
|
||||
const res = await runCli([
|
||||
"rule",
|
||||
"add",
|
||||
"办公采购",
|
||||
"单笔采购大于1万,[必须附采购合同]{硬性}。",
|
||||
]);
|
||||
|
||||
expect(res.exitCode).not.toBe(0);
|
||||
expect(res.stderr).toContain("--dry-run");
|
||||
expect(res.stderr).toContain("--yes");
|
||||
const scopes = await runCli(["rule", "scopes", "--json"]);
|
||||
expect(JSON.parse(scopes.stdout).count).toBe(2);
|
||||
});
|
||||
|
||||
test("hose-use rule add 语法错误拦截并阻止入库", async () => {
|
||||
const failRes = await runCli([
|
||||
"rule",
|
||||
|
||||
@@ -2,6 +2,7 @@ import { ApprovalRepository, parseRuleBody } from "../../domains/approval/index.
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
|
||||
export async function handleRuleCommand(
|
||||
parsed: CliParsedArgs,
|
||||
@@ -205,6 +206,22 @@ export async function handleRuleCommand(
|
||||
|
||||
if (!scope) throw new Error("缺少适用场景/索引参数:请输入索引名称或使用 --scope 指定");
|
||||
if (!body) throw new Error("缺少规约正文参数:请输入正文或使用 --body 指定,须包含 [动作句式]{硬性|弹性|建议|特殊}");
|
||||
// 先做纯函数校验,让调用方在确认前就能修正格式错误。
|
||||
parseRuleBody(body);
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"新增审批规则",
|
||||
`hose-use rule add --scope=${scope} --body='${body}' --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "新增审批规则", scope, {
|
||||
scope,
|
||||
body,
|
||||
status: "active",
|
||||
});
|
||||
}
|
||||
|
||||
const rule = repo.createRule({
|
||||
scope,
|
||||
@@ -240,6 +257,19 @@ export async function handleRuleCommand(
|
||||
ruleId = found.id;
|
||||
}
|
||||
|
||||
requireMutationConfirmation(
|
||||
parsed,
|
||||
runtime,
|
||||
"删除审批规则",
|
||||
`hose-use rule delete ${ruleId} --yes`
|
||||
);
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "删除审批规则", ruleId, {
|
||||
id: ruleId,
|
||||
irreversible: true,
|
||||
});
|
||||
}
|
||||
|
||||
const deleted = repo.deleteRule(ruleId);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { runServiceCommand, ServiceConfig, getPidFile, getLogFile } from "../ser
|
||||
import { printJson, printKeyValue } from "../printer.js";
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import { EventStore } from "../../domains/events/store.js";
|
||||
import { pollEvents } from "../../domains/events/poller.js";
|
||||
|
||||
@@ -23,7 +23,7 @@ export async function handleServiceCommand(
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) throw new Error("事件轮询需要企业上下文,请通过 --corp=<id> 指定企业。");
|
||||
const corpId = corp.corpId || corp.id;
|
||||
const client = await createEkbClient(corp);
|
||||
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 result = await pollEvents(client, corpId, store, limit);
|
||||
|
||||
+11
-18
@@ -1,13 +1,14 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
EMBEDDED_SKILL_FILES,
|
||||
getDefaultGlobalSkillDir,
|
||||
getAgentSkillCandidates,
|
||||
getSkillContent,
|
||||
installSkillFiles,
|
||||
} from "../../core/embedded-skill.js";
|
||||
import { booleanOption, stringOption } from "../parser.js";
|
||||
import { printJson, printKeyValue } from "../printer.js";
|
||||
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
|
||||
export async function handleSkillCommand(
|
||||
@@ -41,19 +42,16 @@ export async function handleSkillCommand(
|
||||
? join(process.cwd(), ".agents", "skills", "hose-use")
|
||||
: getDefaultGlobalSkillDir();
|
||||
|
||||
const result = installSkillFiles(targetDir);
|
||||
|
||||
// 也同时尝试安装到其它检测到的候选目录
|
||||
const candidates = getAgentSkillCandidates();
|
||||
for (const dir of candidates) {
|
||||
if (dir !== targetDir) {
|
||||
try {
|
||||
installSkillFiles(dir);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
if (isDryRun(parsed, runtime)) {
|
||||
return mutationPreview(parsed, runtime, "安装 Agent Skill 文件", targetDir, {
|
||||
fileCount: Object.keys(EMBEDDED_SKILL_FILES).length,
|
||||
local: isLocal,
|
||||
targetPolicy: customDir ? "explicit" : isLocal ? "workspace" : "global-canonical",
|
||||
});
|
||||
}
|
||||
requireMutationConfirmation(parsed, runtime, "安装 Agent Skill 文件", `hose-use skill install${customDir ? ` --dir=${customDir}` : ""} --yes`);
|
||||
|
||||
const result = installSkillFiles(targetDir);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
@@ -79,7 +77,6 @@ export async function handleSkillCommand(
|
||||
case "get": {
|
||||
const globalDir = getDefaultGlobalSkillDir();
|
||||
const localDir = join(process.cwd(), ".agents", "skills", "hose-use");
|
||||
const candidates = getAgentSkillCandidates();
|
||||
|
||||
const statusObj = {
|
||||
global: {
|
||||
@@ -90,10 +87,6 @@ export async function handleSkillCommand(
|
||||
dir: localDir,
|
||||
installed: existsSync(join(localDir, "SKILL.md")),
|
||||
},
|
||||
candidates: candidates.map((dir) => ({
|
||||
dir,
|
||||
installed: existsSync(join(dir, "SKILL.md")),
|
||||
})),
|
||||
};
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import { listTasks } from "../../domains/task/tools.js";
|
||||
import type { TaskView } from "../../domains/task/types.js";
|
||||
|
||||
@@ -40,7 +40,7 @@ export async function handleTaskCommand(parsed: CliParsedArgs, runtime: CliRunti
|
||||
const unread = booleanOption(parsed.options, ["unread"]);
|
||||
// Carbon copy defaults to unread, while the other views do not use this flag.
|
||||
const readFilter = view === "cc" ? read && !unread : undefined;
|
||||
const result = await listTasks(await createEkbClient(corp), corp.corpId || corp.id, view, { start, count, staffId, from, to, read: readFilter });
|
||||
const result = await listTasks(await createSessionClient(corp), corp.corpId || corp.id, view, { start, count, staffId, from, to, read: readFilter });
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return { stdout: printJson({ corpId: corp.corpId || corp.id, corpName: corp.name, ...result }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
|
||||
@@ -53,18 +53,19 @@ describe("normalizeRepo and isValidRepo", () => {
|
||||
describe("matchAssetForPlatform", () => {
|
||||
const assets: GitHubAsset[] = [
|
||||
{ name: "hose-use-darwin-arm64", downloadUrl: "https://example.com/darwin-arm64", size: 100 },
|
||||
{ name: "hose-use-darwin-arm64.tar.gz", downloadUrl: "https://example.com/darwin-arm64.tar.gz", size: 40 },
|
||||
{ name: "hose-use-darwin-x64", downloadUrl: "https://example.com/darwin-x64", size: 100 },
|
||||
{ name: "hose-use-linux-x64.tar.gz", downloadUrl: "https://example.com/linux-x64.tar.gz", size: 100 },
|
||||
{ name: "hose-use-linux-arm64", downloadUrl: "https://example.com/linux-arm64", size: 100 },
|
||||
{ name: "hose-use-windows-x64.zip", downloadUrl: "https://example.com/win-x64.zip", size: 100 },
|
||||
];
|
||||
|
||||
test("matches darwin arm64", () => {
|
||||
test("matches darwin arm64 with archive priority", () => {
|
||||
const matched = matchAssetForPlatform(assets, "darwin", "arm64");
|
||||
expect(matched?.name).toBe("hose-use-darwin-arm64");
|
||||
expect(matched?.name).toBe("hose-use-darwin-arm64.tar.gz");
|
||||
});
|
||||
|
||||
test("matches darwin x64", () => {
|
||||
test("matches darwin x64 fallback to raw binary when no archive present", () => {
|
||||
const matched = matchAssetForPlatform(assets, "darwin", "x64");
|
||||
expect(matched?.name).toBe("hose-use-darwin-x64");
|
||||
});
|
||||
|
||||
+52
-16
@@ -1,4 +1,4 @@
|
||||
import { chmodSync, existsSync, mkdirSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { chmodSync, existsSync, mkdirSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { isCompiledBinary, resolveAppRoot } from "../../core/runtime.js";
|
||||
@@ -458,8 +458,28 @@ export async function handleUpdateCommand(
|
||||
// ignore
|
||||
}
|
||||
renameSync(newBinaryPath, execPath);
|
||||
|
||||
// Ensure Windows hose-aipro.cmd wrapper exists
|
||||
const cmdWrapper = join(execDir, "hose-aipro.cmd");
|
||||
if (!existsSync(cmdWrapper)) {
|
||||
try {
|
||||
writeFileSync(cmdWrapper, '@echo off\r\n"%~dp0hose-use.exe" %*\r\n', "utf8");
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
} else {
|
||||
renameSync(newBinaryPath, execPath);
|
||||
|
||||
// Ensure Unix hose-aipro symlink exists and points to the main binary
|
||||
const aiproLink = join(execDir, "hose-aipro");
|
||||
if (!existsSync(aiproLink)) {
|
||||
try {
|
||||
symlinkSync(execPath, aiproLink);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const skillSync = syncGlobalSkillIfPresent();
|
||||
@@ -715,7 +735,16 @@ export function matchAssetForPlatform(
|
||||
return matchesP && matchesA;
|
||||
});
|
||||
|
||||
// Prefer direct raw executable over tar.gz / zip if both exist
|
||||
// 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") &&
|
||||
@@ -723,16 +752,7 @@ export function matchAssetForPlatform(
|
||||
!asset.name.endsWith(".zip") &&
|
||||
!asset.name.endsWith(".sha256")
|
||||
);
|
||||
if (directBinary) return directBinary;
|
||||
|
||||
// Fallback to archive
|
||||
const archive = matched.find(
|
||||
(asset) =>
|
||||
asset.name.endsWith(".tar.gz") ||
|
||||
asset.name.endsWith(".tgz") ||
|
||||
asset.name.endsWith(".zip")
|
||||
);
|
||||
return archive || matched[0];
|
||||
return directBinary || matched[0];
|
||||
}
|
||||
|
||||
function logProgress(msg: string) {
|
||||
@@ -877,15 +897,24 @@ function extractTarGz(archivePath: string, targetDir: string, platform: string):
|
||||
}
|
||||
unlinkSync(archivePath);
|
||||
|
||||
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
|
||||
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;
|
||||
return files[0] || archivePath;
|
||||
|
||||
// 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 {
|
||||
@@ -895,15 +924,22 @@ function extractZip(archivePath: string, targetDir: string, platform: string): s
|
||||
}
|
||||
unlinkSync(archivePath);
|
||||
|
||||
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
|
||||
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;
|
||||
return files[0] || archivePath;
|
||||
|
||||
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 {
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
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");
|
||||
|
||||
@@ -118,6 +119,20 @@ async function handlePatch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<
|
||||
}
|
||||
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 };
|
||||
@@ -147,6 +162,21 @@ async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
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);
|
||||
@@ -159,7 +189,6 @@ async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
|
||||
dirtyPaths: ["*"],
|
||||
};
|
||||
|
||||
const forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]);
|
||||
if (!forceWrite && hasWorkflowVersionConflict(state, remote)) {
|
||||
throw new Error(
|
||||
`工作流版本已变化,拒绝覆盖:远端 tasksVersion=${remote.tasksVersion}, 文件 tasksVersion=${parsedWorkflow.tasksVersion}。确认来源后使用 --force-write。`
|
||||
@@ -300,6 +329,15 @@ async function handleCheck(parsed: CliParsedArgs, runtime: CliRuntime): Promise<
|
||||
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 };
|
||||
@@ -468,6 +506,15 @@ async function handleToggle(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
export type CliExitCode = 1 | 2 | 10 | 11 | 12;
|
||||
|
||||
export class CliError extends Error {
|
||||
readonly exitCode: CliExitCode;
|
||||
readonly nextAction?: string;
|
||||
|
||||
constructor(message: string, exitCode: CliExitCode, nextAction?: string) {
|
||||
super(message);
|
||||
this.name = "CliError";
|
||||
this.exitCode = exitCode;
|
||||
this.nextAction = nextAction;
|
||||
}
|
||||
}
|
||||
|
||||
export class PayloadTooLargeError extends CliError {
|
||||
constructor(message: string, nextAction?: string) {
|
||||
super(message, 12, nextAction);
|
||||
this.name = "PayloadTooLargeError";
|
||||
}
|
||||
}
|
||||
|
||||
export function usageError(message: string, nextAction?: string): CliError {
|
||||
return new CliError(message, 2, nextAction);
|
||||
}
|
||||
|
||||
export function confirmationRequired(message: string, nextAction: string): CliError {
|
||||
return new CliError(message, 10, nextAction);
|
||||
}
|
||||
|
||||
export function classifyCliError(error: unknown): {
|
||||
exitCode: CliExitCode;
|
||||
nextAction?: string;
|
||||
} {
|
||||
if (error instanceof CliError) {
|
||||
return { exitCode: error.exitCode, nextAction: error.nextAction };
|
||||
}
|
||||
|
||||
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)) {
|
||||
return { exitCode: 11, nextAction: "hose-use auth login" };
|
||||
}
|
||||
if (/^(?:Usage:|用法:|未知(?:命令|.*子命令)|缺少|请提供|请指定|Invalid|Missing|required)/i.test(value)) {
|
||||
return { exitCode: 2 };
|
||||
}
|
||||
if (/without --(?:yes|confirm)|请显式添加 --yes|需要 --(?:yes|confirm)/i.test(value)) {
|
||||
return { exitCode: 10 };
|
||||
}
|
||||
return { exitCode: 1 };
|
||||
}
|
||||
|
||||
function responseStatus(error: unknown): number | undefined {
|
||||
if (!error || typeof error !== "object") return undefined;
|
||||
const response = (error as { response?: unknown }).response;
|
||||
if (!response || typeof response !== "object") return undefined;
|
||||
const status = (response as { status?: unknown }).status;
|
||||
return typeof status === "number" ? status : undefined;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
export interface HelpTopic {
|
||||
summary: string;
|
||||
usage: string;
|
||||
commands: Record<string, string>;
|
||||
options?: string[];
|
||||
}
|
||||
|
||||
export const HELP_REGISTRY: Record<string, HelpTopic> = {
|
||||
context: { summary: "全局运行上下文与身份诊断", usage: "hose-use context [--json]", commands: { context: "输出当前企业、账号、运行模式与认证状态" } },
|
||||
auth: {
|
||||
summary: "认证与凭证管理(支持主账号登录与企业级 OpenAPI 持久化)",
|
||||
usage: "hose-use auth <子命令>",
|
||||
commands: {
|
||||
login: "登录并保存企业凭证",
|
||||
status: "查看当前认证状态",
|
||||
refresh: "刷新账号或企业 AccessToken",
|
||||
link: "生成企业 Web 免密登录直达链接 (别名: hose-link)",
|
||||
"add-link": "从协助链接导入企业凭证(自动探测并持久化 OpenAPI 密钥)",
|
||||
"add-persistent": "通过 OpenAPI 密钥 (appKey + appSecurity) 持久化接入企业",
|
||||
"extract-keys": "从协助链接提取 OpenAPI 密钥",
|
||||
elevate: "为已配置企业提取并持久化保存 OpenAPI 密钥",
|
||||
accounts: "列出已保存账号",
|
||||
"switch-account": "切换默认账号",
|
||||
},
|
||||
},
|
||||
corps: {
|
||||
summary: "多企业租户管理",
|
||||
usage: "hose-use corps <子命令>",
|
||||
commands: {
|
||||
list: "列出本地企业配置",
|
||||
search: "搜索企业与员工",
|
||||
switch: "切换当前工作企业",
|
||||
current: "查看当前企业",
|
||||
link: "生成企业 Web 免密登录直达链接 (别名: hose-link)",
|
||||
"add-link": "从链接导入企业凭证(自动探测并持久化 OpenAPI 密钥)",
|
||||
"add-persistent": "通过 OpenAPI 密钥持久化接入企业",
|
||||
"extract-keys": "从协助链接提取 OpenAPI 密钥",
|
||||
elevate: "为已配置企业提取并持久化保存 OpenAPI 密钥",
|
||||
},
|
||||
},
|
||||
config: { summary: "全局运行模式与路径配置", usage: "hose-use config <子命令>", commands: { paths: "诊断配置目录链", get: "查看全局配置", mode: "切换 stateful/stateless", set: "更新指定配置项" } },
|
||||
workflow: { summary: "工作流查询、草稿与生命周期管理", usage: "hose-use workflow <子命令> [参数] [选项]", commands: { list: "列出工作流", get: "查看工作流详情", find: "按节点类型搜索", analyze: "静态分析工作流", patch: "生成草稿字段补丁", save: "保存草稿到远端", toggle: "切换启停状态", publish: "发布并启用工作流", history: "查看版本历史", logs: "查看运行日志", check: "检查错误管道" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作", "--file=<workflow.json> 指定工作流快照"] },
|
||||
bill: { summary: "单据检索与审批动作", usage: "hose-use bill <子命令> [单号|ID] [选项]", commands: { list: "查询单据", get: "查看单据详情", flow: "查看审批流程", approve: "同意审批", reject: "驳回审批", transfer: "转交审批", "add-node": "加签审批", comment: "添加评论" }, options: ["--dry-run 只预览审批动作", "--yes/--confirm 确认执行审批动作", "--comment=<原因> 驳回或评论内容"] },
|
||||
platform: { summary: "自建应用、业务对象与底层记录", usage: "hose-use platform <子命令> [参数]", commands: { list: "列出自建应用", entities: "列出业务对象", schema: "查看字段定义", records: "查询记录", record: "查看或修改单条记录", permissions: "查看权限", imports: "查看导入任务" }, options: ["--dry-run 只预览记录写操作", "--yes/--confirm 确认记录写操作"] },
|
||||
feetype: { summary: "费用类型全生命周期管理", usage: "hose-use feetype <子命令> [参数]", commands: { list: "查看费用类型树", get: "查看详情与字段", create: "新建费用类型", update: "修改属性", disable: "停用", enable: "启用", move: "移动层级", fields: "查看字段配置" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作"] },
|
||||
rule: { summary: "本地审批规约管理", usage: "hose-use rule <子命令> [参数]", commands: { scopes: "列出适用场景", scope: "查看场景明细", list: "列出规则", get: "查看规则详情", add: "新增规则", delete: "删除规则" }, options: ["--dry-run 只预览增删", "--yes/--confirm 确认增删"] },
|
||||
approval: { summary: "确定性审批网关与要点仲裁", usage: "hose-use approval audit <子命令> [单号]", commands: { points: "查看审核要点", checklist: "查看核验清单", review: "核验事实", decide: "生成或执行仲裁决定" }, options: ["--apply --yes 执行真实审批流转"] },
|
||||
message: { summary: "消息中心与通知管理", usage: "hose-use message <子命令>", commands: { list: "查询消息", count: "查看未读数", read: "标记消息已读", "read-all": "全部标记已读" } },
|
||||
task: { summary: "待办中心与审批任务", usage: "hose-use task <子命令>", commands: { todo: "待我审批", approved: "我已审批", submitted: "我发起的", records: "审批记录", cc: "抄送任务" } },
|
||||
contact: { summary: "企业通讯录与人员检索", usage: "hose-use contact <子命令>", commands: { list: "列出员工", search: "搜索员工", get: "查看员工详情" } },
|
||||
dimension: { summary: "系统与自定义档案维度", usage: "hose-use dimension <子命令>", commands: { list: "列出维度", items: "列出维度项" } },
|
||||
role: { summary: "企业角色定义与成员", usage: "hose-use role <子命令>", commands: { list: "列出角色", groups: "列出角色组", members: "查看角色成员" } },
|
||||
permission: { summary: "权限模型快照", usage: "hose-use permission get", commands: { get: "查看角色权限开关" } },
|
||||
app: { summary: "桌面端工作台应用管理", usage: "hose-use app <子命令>", commands: { list: "列出应用", get: "查看应用详情" } },
|
||||
menu: { summary: "桌面端主导航菜单树", usage: "hose-use menu list", commands: { list: "查看主导航", apps: "查看应用入口" } },
|
||||
openapi: { summary: "OpenAPI 规范导出与路径查询", usage: "hose-use openapi [paths|info|--raw|keys]", commands: { paths: "列出路径概要", info: "查看规范元数据", keys: "查看企业接入密钥" } },
|
||||
keys: { summary: "企业 OpenAPI 接入凭证", usage: "hose-use keys [--json] [--reveal] [--save]", commands: { keys: "读取当前企业密钥(默认脱敏)" }, options: ["--reveal 仅在明确授权后查看明文", "--save --yes 提取并持久化保存到本地企业配置"] },
|
||||
store: { summary: "已购应用与应用商店探查", usage: "hose-use store <list|search|get>", commands: { list: "列出已购应用", search: "搜索应用商店", get: "查看应用详情" } },
|
||||
update: { summary: "版本自更新与发布记录", usage: "hose-use update [check|--changelog]", commands: { update: "检查并升级版本", check: "只检查可用版本", changelog: "查看发布记录" } },
|
||||
skill: { summary: "Agent Skill 管理", usage: "hose-use skill <install|status|dump>", commands: { install: "安装内嵌 Skill", status: "查看安装状态", dump: "导出 Skill 文件" } },
|
||||
service: { summary: "常驻守护进程管理", usage: "hose-use service <start|stop|restart|status|logs|poll>", commands: { start: "启动服务", stop: "停止服务", restart: "重启服务", status: "查看服务状态", logs: "查看服务日志", poll: "轮询事件" } },
|
||||
probe: { summary: "企业连通性诊断", usage: "hose-use probe [corpId]", commands: { probe: "检查认证与 API 连通性" } },
|
||||
http: { summary: "轻量 HTTP Server 与交互文档", usage: "hose-use http [--port=<port>]", commands: { http: "启动 HTTP 服务" } },
|
||||
mcp: { summary: "MCP Server", usage: "hose-use mcp serve", commands: { serve: "启动 MCP 服务" } },
|
||||
aipro: { summary: "AI PRO 确定性审批仲裁", usage: "hose-use aipro <子命令>", commands: { status: "查看网关状态", bind: "绑定单据", review: "核验要点", decide: "执行仲裁" } },
|
||||
};
|
||||
|
||||
export function renderScopedHelp(target: string[]): string {
|
||||
const area = target[0]?.toLowerCase();
|
||||
const topic = area ? HELP_REGISTRY[area] : undefined;
|
||||
if (!topic) return `未找到命令域帮助: ${target.join(" ") || "<empty>"}\n运行 hose-use --help 查看全部命令域。`;
|
||||
|
||||
const action = target[1]?.toLowerCase();
|
||||
const lines = [`${area} - ${topic.summary}`, "", `用法: ${topic.usage}`, "", "子命令:"];
|
||||
if (action && topic.commands[action]) lines.push(` ${action.padEnd(14)} ${topic.commands[action]}`);
|
||||
else for (const [name, description] of Object.entries(topic.commands)) lines.push(` ${name.padEnd(14)} ${description}`);
|
||||
if (topic.options?.length) lines.push("", "常用选项:", ...topic.options.map((option) => ` ${option}`));
|
||||
lines.push("", "提示: 追加 --json 获取机器可解析结果;写操作先用 --dry-run,再用 --yes 或 --confirm 执行。", "更多: hose-use --help");
|
||||
return lines.join("\n");
|
||||
}
|
||||
+19
-9
@@ -2,9 +2,11 @@ import readline from "readline";
|
||||
import { loadCorpConfigs, loadGlobalConfig, getEnterprisesDirCandidates } from "../core/config/loader.js";
|
||||
import { CorpContext, resolveCorpConfig } from "../core/config/manager.js";
|
||||
import { CorpConfig } from "../core/config/types.js";
|
||||
import { createEkbClient } from "../core/auth/ekb.js";
|
||||
import { getEasoClient } from "../core/auth/easo.js";
|
||||
import { getPiperClient } from "../core/auth/piper.js";
|
||||
import {
|
||||
createSessionClient,
|
||||
getUnityClient,
|
||||
getScriptEngineClient,
|
||||
} from "../core/http/index.js";
|
||||
import { CliRuntime, OutputOptions } from "./types.js";
|
||||
|
||||
export function initCorpRuntime(
|
||||
@@ -13,6 +15,8 @@ export function initCorpRuntime(
|
||||
stateless?: boolean;
|
||||
stateful?: boolean;
|
||||
jsonMode?: boolean;
|
||||
dryRun?: boolean;
|
||||
confirmed?: boolean;
|
||||
outputOptions?: OutputOptions;
|
||||
appRoot?: string;
|
||||
entryFile?: string;
|
||||
@@ -48,6 +52,8 @@ export function initCorpRuntime(
|
||||
corpContext,
|
||||
selectedCorp,
|
||||
jsonMode: options.jsonMode ?? false,
|
||||
dryRun: options.dryRun ?? false,
|
||||
confirmed: options.confirmed ?? false,
|
||||
outputOptions: options.outputOptions,
|
||||
appRoot: options.appRoot,
|
||||
entryFile: options.entryFile,
|
||||
@@ -56,19 +62,23 @@ export function initCorpRuntime(
|
||||
}
|
||||
|
||||
export async function createClientsForCorp(corp: CorpConfig) {
|
||||
const ekbClient = await createEkbClient(corp);
|
||||
const { client: easoClient } = await getEasoClient(corp);
|
||||
const sessionClient = await createSessionClient(corp);
|
||||
const { client: unityClient } = await getUnityClient(corp);
|
||||
return {
|
||||
corp,
|
||||
ekbClient,
|
||||
easoClient,
|
||||
sessionClient,
|
||||
ekbClient: sessionClient,
|
||||
unityClient,
|
||||
easoClient: unityClient,
|
||||
};
|
||||
}
|
||||
|
||||
export async function createPiperClientForCorp(corp: CorpConfig, platformId: string) {
|
||||
return getPiperClient(corp, platformId);
|
||||
export async function createScriptEngineClientForCorp(corp: CorpConfig, platformId: string) {
|
||||
return getScriptEngineClient(corp, platformId);
|
||||
}
|
||||
|
||||
export const createPiperClientForCorp = createScriptEngineClientForCorp;
|
||||
|
||||
export function prompt(question: string): Promise<string> {
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
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 { handleMessageCommand } from "./commands/message.js";
|
||||
import { handleSkillCommand } from "./commands/skill.js";
|
||||
import type { CliRuntime } from "./types.js";
|
||||
|
||||
const runtime: CliRuntime = {
|
||||
corpContext: {
|
||||
listCorps: () => [],
|
||||
getCurrent: () => null,
|
||||
switchCorp: () => true,
|
||||
resolve: () => null,
|
||||
} as any,
|
||||
selectedCorp: {
|
||||
id: "corp-test",
|
||||
name: "测试企业",
|
||||
corpId: "corp-test",
|
||||
credentials: { accessToken: "token", corpId: "corp-test", staffId: "staff-test" },
|
||||
} as any,
|
||||
jsonMode: true,
|
||||
};
|
||||
|
||||
describe("CLI mutation boundaries", () => {
|
||||
test("auth login dry-run does not prompt or call the login API", async () => {
|
||||
const result = await handleAuthCommand({ area: "auth", action: "login", args: [], options: { "dry-run": true }, raw: ["auth", "login", "--dry-run"] }, runtime);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(JSON.parse(result.stdout).dryRun).toBe(true);
|
||||
});
|
||||
|
||||
test("corps/config state changes share the dry-run protocol", async () => {
|
||||
const corp = await handleCorpsCommand({ area: "corps", action: "switch", args: ["corp-next"], options: { "dry-run": true }, raw: ["corps", "switch", "corp-next", "--dry-run"] }, runtime);
|
||||
const config = await handleConfigCommand({ area: "config", action: "mode", args: ["stateless"], options: { "dry-run": true }, raw: ["config", "mode", "stateless", "--dry-run"] }, runtime);
|
||||
expect(JSON.parse(corp.stdout).operation).toContain("工作企业");
|
||||
expect(JSON.parse(config.stdout).changes.stateful).toBe(false);
|
||||
});
|
||||
|
||||
test("skill installation and message read never write during dry-run", async () => {
|
||||
const skill = await handleSkillCommand({ area: "skill", action: "install", args: [], options: { "dry-run": true }, raw: ["skill", "install", "--dry-run"] }, runtime);
|
||||
const message = await handleMessageCommand({ area: "message", action: "read", args: ["message-1"], options: { "dry-run": true }, raw: ["message", "read", "message-1", "--dry-run"] }, runtime);
|
||||
expect(JSON.parse(skill.stdout).dryRun).toBe(true);
|
||||
expect(JSON.parse(message.stdout).changes.read).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { handleBillCommand } from "./commands/bill.js";
|
||||
import type { CliRuntime } from "./types.js";
|
||||
|
||||
const runtime: CliRuntime = {
|
||||
corpContext: {} as any,
|
||||
selectedCorp: {
|
||||
id: "corp-test",
|
||||
name: "测试企业",
|
||||
source: "account",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
credentials: {
|
||||
corpId: "corp-test",
|
||||
staffId: "staff-test",
|
||||
accessToken: "token-test",
|
||||
},
|
||||
},
|
||||
jsonMode: true,
|
||||
};
|
||||
|
||||
describe("CLI mutation protocol", () => {
|
||||
test("bill --dry-run returns a preview without creating an API client", async () => {
|
||||
const result = await handleBillCommand(
|
||||
{
|
||||
area: "bill",
|
||||
action: "approve",
|
||||
args: ["S26000001"],
|
||||
options: { "dry-run": true },
|
||||
raw: ["bill", "approve", "S26000001", "--dry-run"],
|
||||
},
|
||||
runtime
|
||||
);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
const preview = JSON.parse(result.stdout);
|
||||
expect(preview.dryRun).toBe(true);
|
||||
expect(preview.operation).toBe("同意单据审批");
|
||||
expect(preview.target).toBe("S26000001");
|
||||
expect(preview.nextAction).not.toContain("--dry-run");
|
||||
expect(preview.nextAction).toContain("--yes");
|
||||
});
|
||||
|
||||
test("bill write without confirmation is rejected before the API call", async () => {
|
||||
await expect(
|
||||
handleBillCommand(
|
||||
{
|
||||
area: "bill",
|
||||
action: "approve",
|
||||
args: ["S26000001"],
|
||||
options: {},
|
||||
raw: ["bill", "approve", "S26000001"],
|
||||
},
|
||||
runtime
|
||||
)
|
||||
).rejects.toThrow("--yes");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import { booleanOption } from "./parser.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "./types.js";
|
||||
import { CliError } from "./errors.js";
|
||||
|
||||
/**
|
||||
* All mutating CLI commands use the same two-step contract:
|
||||
* 1. --dry-run only describes the intended change;
|
||||
* 2. --yes/--confirm is required before the real operation runs.
|
||||
*
|
||||
* The parsed-argument fallback keeps command handlers easy to unit-test without
|
||||
* requiring every hand-built CliRuntime to include the newer fields.
|
||||
*/
|
||||
export class MutationConfirmationRequired extends CliError {
|
||||
readonly operation: string;
|
||||
|
||||
constructor(operation: string, nextAction: string) {
|
||||
super(
|
||||
`拒绝执行${operation}:该操作会改变数据。请先使用 --dry-run 预览,确认后追加 --yes(或 --confirm)。`,
|
||||
10,
|
||||
nextAction
|
||||
);
|
||||
this.name = "MutationConfirmationRequired";
|
||||
this.operation = operation;
|
||||
}
|
||||
}
|
||||
|
||||
export function isDryRun(parsed: CliParsedArgs, runtime: CliRuntime): boolean {
|
||||
return runtime.dryRun === true || booleanOption(parsed.options, ["dry-run", "dryRun", "dryrun"]);
|
||||
}
|
||||
|
||||
export function isConfirmed(parsed: CliParsedArgs, runtime: CliRuntime): boolean {
|
||||
return (
|
||||
runtime.confirmed === true ||
|
||||
booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"])
|
||||
);
|
||||
}
|
||||
|
||||
export function requireMutationConfirmation(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime,
|
||||
operation: string,
|
||||
nextAction: string
|
||||
): void {
|
||||
if (isDryRun(parsed, runtime) || isConfirmed(parsed, runtime)) return;
|
||||
throw new MutationConfirmationRequired(operation, nextAction);
|
||||
}
|
||||
|
||||
export function mutationPreview(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime,
|
||||
operation: string,
|
||||
target: string,
|
||||
changes: Record<string, unknown>
|
||||
): CliResult {
|
||||
const confirmedArgs = parsed.raw.filter((arg) => !["--dry-run", "--dryRun", "--dryrun"].includes(arg));
|
||||
const nextAction = `hose-use ${confirmedArgs.join(" ")} --yes`;
|
||||
const payload = {
|
||||
dryRun: true,
|
||||
operation,
|
||||
target,
|
||||
changes,
|
||||
nextAction,
|
||||
};
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: `${JSON.stringify(payload, null, 2)}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const lines = [
|
||||
"[DRY-RUN] 未执行任何写操作。",
|
||||
`操作: ${operation}`,
|
||||
`目标: ${target}`,
|
||||
"变更:",
|
||||
...Object.entries(changes).map(([key, value]) => ` ${key}: ${formatPreviewValue(value)}`),
|
||||
`下一步: ${nextAction}`,
|
||||
];
|
||||
return { stdout: `${lines.join("\n")}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
function formatPreviewValue(value: unknown): string {
|
||||
if (typeof value === "string") return value;
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
@@ -27,6 +27,9 @@ const KNOWN_BOOLEAN_FLAGS = new Set([
|
||||
"yes",
|
||||
"confirm",
|
||||
"force-write",
|
||||
"dry-run",
|
||||
"dryRun",
|
||||
"dryrun",
|
||||
]);
|
||||
|
||||
export function parseArgs(rawArgs: string[]): CliParsedArgs {
|
||||
|
||||
+30
-17
@@ -1,6 +1,8 @@
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { VERSION } from "../version.js";
|
||||
import { formatVersionLabel } from "../version.js";
|
||||
import type { OutputOptions } from "./types.js";
|
||||
import { PayloadTooLargeError } from "./errors.js";
|
||||
import { renderScopedHelp } from "./help.js";
|
||||
|
||||
export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
|
||||
|
||||
@@ -15,8 +17,9 @@ export function protectLargeOutput(result: unknown, options: OutputOptions = {})
|
||||
if (options.allowFull || options.outputFile) return;
|
||||
const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8");
|
||||
if (bodyBytes > DEFAULT_OUTPUT_BYTES_LIMIT) {
|
||||
throw new Error(
|
||||
`输出体积过大 (${bodyBytes} 字节,超过安全阈值 ${DEFAULT_OUTPUT_BYTES_LIMIT} 字节)。请使用 --output-file <路径> (或 -o <路径>) 转储到本地文件;若确需完整大报文请附加 --full 参数。`
|
||||
throw new PayloadTooLargeError(
|
||||
`输出体积过大 (${bodyBytes} 字节,超过安全阈值 ${DEFAULT_OUTPUT_BYTES_LIMIT} 字节)。请使用 --output-file <路径> (或 -o <路径>) 转储到本地文件;若确需完整大报文请附加 --full 参数。`,
|
||||
"hose-use <command> --json --output-file <path>"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -38,40 +41,46 @@ export function printJson(data: unknown, options: OutputOptions = {}): string {
|
||||
return json;
|
||||
}
|
||||
|
||||
export function formatSourceLabel(source?: string): string {
|
||||
export function formatSourceLabel(source?: string, persistentOpenApi?: boolean): string {
|
||||
const suffix = persistentOpenApi && source !== "openapi" ? " + OpenAPI 持久化密钥" : "";
|
||||
switch (source) {
|
||||
case "openapi":
|
||||
return "开放平台持久化密钥 (OpenAPI AppKey)";
|
||||
case "assist":
|
||||
return "官方协助/代客平台 (Assist Platform)";
|
||||
return `官方协助/代客平台 (Assist Platform)${suffix}`;
|
||||
case "account":
|
||||
return "统一认证中心 (IDP 账密/短信)";
|
||||
return `统一认证中心 (IDP 账密/短信)${suffix}`;
|
||||
case "browser":
|
||||
return "浏览器会话同步 (WebBridge)";
|
||||
return `浏览器会话同步 (WebBridge)${suffix}`;
|
||||
case "link":
|
||||
return "协助/免密链接导入 (Assistance Link)";
|
||||
return `协助/免密链接导入 (Assistance Link)${suffix}`;
|
||||
case "curl":
|
||||
case "f12":
|
||||
return "cURL 抓包导入 (cURL/F12)";
|
||||
return `cURL 抓包导入 (cURL/F12)${suffix}`;
|
||||
case "manual":
|
||||
return "手动配置";
|
||||
return `手动配置${suffix}`;
|
||||
default:
|
||||
return source || "未知来源";
|
||||
return (source || "未知来源") + suffix;
|
||||
}
|
||||
}
|
||||
|
||||
export function formatExpiresAt(expiresAt?: number | null): string {
|
||||
export function formatExpiresAt(expiresAt?: number | null, persistent?: boolean): string {
|
||||
if (!expiresAt || expiresAt <= 0) return "长期有效 / 服务端未显式限制";
|
||||
const diffMs = expiresAt - Date.now();
|
||||
const dateStr = new Date(expiresAt).toLocaleString("zh-CN", { hour12: false });
|
||||
if (diffMs <= 0) {
|
||||
if (persistent) {
|
||||
return `${dateStr} (🔄 持久化密钥自动续期)`;
|
||||
}
|
||||
return `${dateStr} (⚠️ 已过期)`;
|
||||
}
|
||||
const diffMins = Math.floor(diffMs / 60000);
|
||||
if (diffMins < 60) {
|
||||
return `${dateStr} (约剩余 ${diffMins} 分钟)`;
|
||||
return `${dateStr} (约剩余 ${diffMins} 分钟${persistent ? ",支持自动续期" : ""})`;
|
||||
}
|
||||
const diffHours = (diffMs / 3600000).toFixed(1);
|
||||
if (Number(diffHours) < 24) {
|
||||
return `${dateStr} (约剩余 ${diffHours} 小时)`;
|
||||
return `${dateStr} (约剩余 ${diffHours} 小时${persistent ? ",支持自动续期" : ""})`;
|
||||
}
|
||||
const diffDays = Math.floor(diffMs / 86400000);
|
||||
return `${dateStr} (约剩余 ${diffDays} 天)`;
|
||||
@@ -109,9 +118,10 @@ export function printTable(
|
||||
return [headerLine, separatorLine, ...dataLines].map((l) => ` ${l}`).join("\n");
|
||||
}
|
||||
|
||||
export function printHelp(): string {
|
||||
export function printHelp(target: string[] = []): string {
|
||||
if (target.length) return renderScopedHelp(target);
|
||||
return `
|
||||
合思/易快报企业级 CLI 工具 (hose-use) v${VERSION}
|
||||
合思/易快报企业级 CLI 工具 (${formatVersionLabel("hose-use")})
|
||||
|
||||
用法:
|
||||
hose-use <命令域> <子命令> [参数] [选项]
|
||||
@@ -155,7 +165,9 @@ export function printHelp(): string {
|
||||
--full 允许全量输出大体积 JSON (绕过 200KB 防爆拦截)
|
||||
--stateless 单次强制以无状态模式执行
|
||||
--stateful 单次强制以有状态模式执行
|
||||
--yes, -y 确认执行会改变单据状态的审批动作
|
||||
--dry-run 只预览写操作,不发起写请求或落盘
|
||||
--yes, -y 确认执行会改变数据的写操作
|
||||
--confirm --yes 的可读别名;写操作必须显式确认
|
||||
--help, -h 查看帮助信息
|
||||
|
||||
常用示例:
|
||||
@@ -189,6 +201,7 @@ export function printHelp(): string {
|
||||
# 查询记录并只输出指定字段
|
||||
hose-use platform permissions <应用> [对象] # 查看应用/对象权限快照
|
||||
hose-use bill list # 查看当前企业单据与报销列表
|
||||
hose-use bill list --keyword=打车 --search-fields=name,form # 跨字段复合检索单据
|
||||
hose-use bill flow S26000001 # 查看单据审批历史与后续节点
|
||||
hose-use bill risk S26000001 # 查看风控预警、预算与发票风险
|
||||
hose-use bill refs S26000001 # 二级解析提交人、部门、法人实体与费用类型引用
|
||||
|
||||
+41
-3
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { runCli } from "./runner.js";
|
||||
import { VERSION } from "../version.js";
|
||||
import { VERSION_INFO, formatVersionLabel } from "../version.js";
|
||||
|
||||
describe("CLI runner - version and help aliases", () => {
|
||||
const versionVariants = [
|
||||
@@ -25,7 +25,7 @@ describe("CLI runner - version and help aliases", () => {
|
||||
const result = await runCli(args);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stderr).toBe("");
|
||||
expect(result.stdout).toBe(`hose-use v${VERSION}\n`);
|
||||
expect(result.stdout).toBe(`${formatVersionLabel("hose-use")}\n`);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ describe("CLI runner - version and help aliases", () => {
|
||||
const result = await runCli(args);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stderr).toBe("");
|
||||
expect(result.stdout).toContain(`合思/易快报企业级 CLI 工具 (hose-use) v${VERSION}`);
|
||||
expect(result.stdout).toContain(`合思/易快报企业级 CLI 工具 (${formatVersionLabel("hose-use")})`);
|
||||
expect(result.stdout).toContain("用法:");
|
||||
});
|
||||
}
|
||||
@@ -60,4 +60,42 @@ describe("CLI runner - version and help aliases", () => {
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("未知命令域: unknown-command-xyz");
|
||||
});
|
||||
|
||||
it("returns semantic confirmation exit code and nextAction", async () => {
|
||||
const result = await runCli([
|
||||
"rule",
|
||||
"add",
|
||||
"办公采购",
|
||||
"采购时,[必须附采购合同]{硬性}。",
|
||||
"--json",
|
||||
]);
|
||||
|
||||
expect(result.exitCode).toBe(10);
|
||||
const data = JSON.parse(result.stdout);
|
||||
expect(data.exitCode).toBe(10);
|
||||
expect(data.nextAction).toContain("--yes");
|
||||
});
|
||||
|
||||
it("supports layered help by command domain and subcommand", async () => {
|
||||
const domain = await runCli(["help", "workflow"]);
|
||||
expect(domain.exitCode).toBe(0);
|
||||
expect(domain.stdout).toContain("workflow -");
|
||||
expect(domain.stdout).toContain("patch");
|
||||
expect(domain.stdout).toContain("--dry-run");
|
||||
|
||||
const command = await runCli(["workflow", "publish", "--help"]);
|
||||
expect(command.exitCode).toBe(0);
|
||||
expect(command.stdout).toContain("publish");
|
||||
expect(command.stdout).toContain("发布并启用工作流");
|
||||
});
|
||||
|
||||
it("keeps help and version machine-readable when --json is requested", async () => {
|
||||
const help = await runCli(["help", "workflow", "--json"]);
|
||||
const version = await runCli(["version", "--json"]);
|
||||
|
||||
expect(JSON.parse(help.stdout).help).toContain("workflow -");
|
||||
expect(JSON.parse(version.stdout)).toEqual(VERSION_INFO);
|
||||
expect(help.stderr).toBe("");
|
||||
expect(version.stderr).toBe("");
|
||||
});
|
||||
});
|
||||
+44
-11
@@ -1,6 +1,7 @@
|
||||
import { VERSION } from "../version.js";
|
||||
import { VERSION_INFO, formatVersionLabel } from "../version.js";
|
||||
import { parseArgs, stringOption, booleanOption, outputOptions } from "./parser.js";
|
||||
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";
|
||||
@@ -65,11 +66,13 @@ async function runCliOnce(
|
||||
): Promise<CliResult> {
|
||||
const stdoutChunks: string[] = [];
|
||||
const stderrChunks: string[] = [];
|
||||
const machineJson = booleanOption(parseArgs(rawArgs).options, ["json", "j"]);
|
||||
const originalLog = console.log;
|
||||
const originalError = console.error;
|
||||
|
||||
console.log = (...values: unknown[]) => {
|
||||
stdoutChunks.push(values.map((v) => (typeof v === "string" ? v : String(v))).join(" "));
|
||||
const line = values.map((v) => (typeof v === "string" ? v : String(v))).join(" ");
|
||||
(machineJson ? stderrChunks : stdoutChunks).push(line);
|
||||
};
|
||||
console.error = (...values: unknown[]) => {
|
||||
stderrChunks.push(values.map((v) => (typeof v === "string" ? v : String(v))).join(" "));
|
||||
@@ -79,10 +82,14 @@ async function runCliOnce(
|
||||
const result = await dispatchCli(rawArgs, options);
|
||||
const extraStdout = stdoutChunks.length ? `${stdoutChunks.join("\n")}\n` : "";
|
||||
const extraStderr = stderrChunks.length ? `${stderrChunks.join("\n")}\n` : "";
|
||||
const bodyStdout = result.preserveSensitiveStdout
|
||||
? result.stdout || ""
|
||||
: redactSensitiveText(result.stdout || "");
|
||||
return {
|
||||
stdout: redactSensitiveText(extraStdout + (result.stdout || "")),
|
||||
stdout: redactSensitiveText(extraStdout) + bodyStdout,
|
||||
stderr: redactSensitiveText(extraStderr + (result.stderr || "")),
|
||||
exitCode: result.exitCode,
|
||||
preserveSensitiveStdout: result.preserveSensitiveStdout,
|
||||
};
|
||||
} finally {
|
||||
console.log = originalLog;
|
||||
@@ -116,31 +123,51 @@ function isVersionRequested(parsed: CliParsedArgs): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
function resolveHelpTarget(parsed: CliParsedArgs): string[] {
|
||||
if (["help", "h", "?"].includes((parsed.area || "").toLowerCase())) {
|
||||
return [parsed.action, parsed.args[0]].filter((value): value is string => Boolean(value));
|
||||
}
|
||||
return [parsed.area, parsed.action].filter((value): value is string => Boolean(value));
|
||||
}
|
||||
|
||||
async function dispatchCli(
|
||||
rawArgs: string[],
|
||||
options: CliRunOptions = {}
|
||||
): Promise<CliResult> {
|
||||
const parsed = parseArgs(rawArgs);
|
||||
const jsonMode = booleanOption(parsed.options, ["json", "j"]);
|
||||
|
||||
if (isHelpRequested(parsed)) {
|
||||
return { stdout: printHelp() + "\n", stderr: "", exitCode: 0 };
|
||||
const help = printHelp(resolveHelpTarget(parsed));
|
||||
return {
|
||||
stdout: jsonMode ? printJson({ help }) : `${help}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (isVersionRequested(parsed)) {
|
||||
return { stdout: `hose-use v${VERSION}\n`, stderr: "", exitCode: 0 };
|
||||
return {
|
||||
stdout: jsonMode ? printJson(VERSION_INFO) : `${formatVersionLabel("hose-use")}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const jsonMode = booleanOption(parsed.options, ["json", "j"]);
|
||||
const corpIdOption = stringOption(parsed.options, ["corp", "c"]);
|
||||
const statelessOption = booleanOption(parsed.options, ["stateless"]);
|
||||
const statefulOption = booleanOption(parsed.options, ["stateful"]);
|
||||
const outputOpts = outputOptions(parsed.options);
|
||||
const dryRun = booleanOption(parsed.options, ["dry-run", "dryRun", "dryrun"]);
|
||||
const confirmed = booleanOption(parsed.options, ["yes", "y", "confirm", "force-write"]);
|
||||
|
||||
const runtime = initCorpRuntime({
|
||||
corpId: corpIdOption,
|
||||
stateless: statelessOption,
|
||||
stateful: statefulOption,
|
||||
jsonMode,
|
||||
dryRun,
|
||||
confirmed,
|
||||
outputOptions: outputOpts,
|
||||
appRoot: options.appRoot,
|
||||
entryFile: options.entryFile,
|
||||
@@ -265,7 +292,7 @@ async function dispatchCli(
|
||||
case "mcp":
|
||||
return await handleMcpCommand(parsed, options);
|
||||
case undefined:
|
||||
return { stdout: printHelp() + "\n", stderr: "", exitCode: 0 };
|
||||
return { stdout: printHelp(resolveHelpTarget(parsed)) + "\n", stderr: "", exitCode: 0 };
|
||||
default:
|
||||
return {
|
||||
stdout: "",
|
||||
@@ -275,17 +302,23 @@ async function dispatchCli(
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMsg = redactSensitiveText(error instanceof Error ? error.message : String(error));
|
||||
const classification = classifyCliError(error);
|
||||
if (jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ error: true, message: errorMsg }),
|
||||
stdout: JSON.stringify({
|
||||
error: true,
|
||||
message: errorMsg,
|
||||
exitCode: classification.exitCode,
|
||||
...(classification.nextAction ? { nextAction: classification.nextAction } : {}),
|
||||
}, null, 2),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
exitCode: classification.exitCode,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] ${errorMsg}\n`,
|
||||
exitCode: 1,
|
||||
stderr: `[ERROR] ${errorMsg}${classification.nextAction ? `\n下一步: ${classification.nextAction}` : ""}\n`,
|
||||
exitCode: classification.exitCode,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ export interface CliResult {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
exitCode: number;
|
||||
preserveSensitiveStdout?: boolean;
|
||||
}
|
||||
|
||||
export interface OutputOptions {
|
||||
@@ -34,6 +35,8 @@ export interface CliRuntime {
|
||||
corpContext: CorpContext;
|
||||
selectedCorp: CorpConfig | null;
|
||||
jsonMode: boolean;
|
||||
dryRun?: boolean;
|
||||
confirmed?: boolean;
|
||||
outputOptions?: OutputOptions;
|
||||
appRoot?: string;
|
||||
entryFile?: string;
|
||||
|
||||
+13
-10
@@ -6,15 +6,20 @@ Core 层负责基础设施:企业配置管理、认证 Token 获取与缓存
|
||||
|
||||
```text
|
||||
src/core/
|
||||
├── auth/ # 登录认证与 Token 获取、刷新、缓存
|
||||
│ ├── login.ts # 登录四矩阵(RSA账密登录、短信验证码、F12/cURL凭证导入、浏览器同步)
|
||||
│ ├── account-store.ts # 多账号持久化存储 (~/.cache/ekb-mcp/accounts.json)
|
||||
├── auth/ # 登录认证协议与凭证存储(纯凭据层:用户级主账号 + 企业级 OpenAPI 持久化双通道)
|
||||
│ ├── login.ts # 登录与换票矩阵(RSA账密、短信、F12/协助链接导入、浏览器同步、OpenAPI 密钥持久化与 getProvisionalAuth 续期)
|
||||
│ ├── account-store.ts # 多账号持久化存储 (~/.config/hose-use/accounts.json)
|
||||
│ ├── tools.ts # MCP Auth Tools 注册与调度
|
||||
│ ├── ekb.ts # 快报主站三 Header 认证
|
||||
│ ├── easo.ts # EASO(unity.ekuaibao.com)四步认证
|
||||
│ ├── piper.ts # Piper(piper.ekuaibao.com)三步认证
|
||||
│ ├── token-store.ts # 动态 Token 缓存(兼容 ~/.config/hose-use/tokens.json 与历史路径)
|
||||
│ ├── token-store.ts # 动态 Token 缓存 (~/.config/hose-use/tokens.json)
|
||||
│ └── 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 脚本调试引擎客户端
|
||||
│ └── index.ts # 统一导出入口
|
||||
├── cache/ # 统一多级协同缓存
|
||||
│ ├── memory.ts # L1 内存缓存(TTL、容量限制、按命名空间清理)
|
||||
│ ├── sqlite.ts # L2 SQLite 持久化缓存(跨 CLI 进程复用)
|
||||
@@ -28,14 +33,12 @@ src/core/
|
||||
│ ├── loader.ts
|
||||
│ ├── manager.ts
|
||||
│ └── types.ts
|
||||
├── http/ # HTTP 客户端工厂
|
||||
│ └── factory.ts
|
||||
└── errors.ts # 统一异常语义(EkbError 子类)
|
||||
```
|
||||
|
||||
## 分层约束
|
||||
|
||||
- `domains/*/api.ts` 只通过 `core/http/factory.ts` 或 `core/auth/*` 获取客户端
|
||||
- `domains/*` 优先通过 `core/http/` 获取语义化客户端(`createSessionClient`, `createOpenApiClient`, `getUnityClient`, `getScriptEngineClient`),保持底层网络与指纹统一
|
||||
- `domains/*` 层只抛 `EkbError` 子类
|
||||
- `server.ts` 负责把 `EkbError` 映射为 MCP error
|
||||
- 业务域如果需要缓存,统一使用 `core/cache/` 提供的多级缓存门面
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { readFileSync, writeFileSync, mkdirSync } from "fs";
|
||||
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
||||
import { join, dirname } from "path";
|
||||
import { homedir } from "os";
|
||||
import { z } from "zod";
|
||||
|
||||
const ACCOUNT_CACHE_PATH = join(
|
||||
export const ACCOUNT_CACHE_PATH = join(
|
||||
homedir(),
|
||||
".cache",
|
||||
"ekb-mcp",
|
||||
".config",
|
||||
"hose-use",
|
||||
"accounts.json"
|
||||
);
|
||||
|
||||
@@ -38,7 +38,13 @@ export type AccountEntry = z.infer<typeof AccountEntrySchema>;
|
||||
export type AccountStore = z.infer<typeof AccountStoreSchema>;
|
||||
|
||||
function ensureDir(path: string): void {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
const dir = dirname(path);
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
}
|
||||
try {
|
||||
chmodSync(dir, 0o700);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function loadAccountStore(): AccountStore {
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { canRefreshCorpAccessToken, resolveLinkExpiresAt } from "./login.js";
|
||||
import { createEkbClient } from "./ekb.js";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
|
||||
function corp(overrides: Partial<CorpConfig> = {}): CorpConfig {
|
||||
return {
|
||||
id: "corp-1",
|
||||
name: "测试企业",
|
||||
source: "link",
|
||||
credentials: { accessToken: "token", corpId: "corp-1", staffId: "staff-1" },
|
||||
...overrides,
|
||||
baseUrl: overrides.baseUrl ?? "https://app.ekuaibao.com",
|
||||
};
|
||||
}
|
||||
|
||||
describe("core/auth/ekb refresh policy", () => {
|
||||
it("only allows account credentials with an explicit account binding to refresh", () => {
|
||||
expect(canRefreshCorpAccessToken(corp())).toBe(false);
|
||||
expect(canRefreshCorpAccessToken(corp({ source: "browser", accountId: "86-1" }))).toBe(false);
|
||||
expect(canRefreshCorpAccessToken(corp({ source: "account" }))).toBe(false);
|
||||
expect(canRefreshCorpAccessToken(corp({ source: "account", accountId: "86-1" }))).toBe(true);
|
||||
expect(canRefreshCorpAccessToken(corp({ source: "account", accountId: "86-1", session: { isShortTermToken: true } }))).toBe(false);
|
||||
});
|
||||
|
||||
it("fails expired temporary credentials without retrying or refreshing", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
let calls = 0;
|
||||
globalThis.fetch = (async () => {
|
||||
calls += 1;
|
||||
return new Response("expired", { status: 401 });
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
try {
|
||||
const client = await createEkbClient(corp());
|
||||
await expect(client.get("api/test")).rejects.toThrow("临时凭证已过期,请使用 hose-use corps add-link 重新导入");
|
||||
expect(calls).toBe(1);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("core/auth/login link expiry", () => {
|
||||
it("parses explicit ttl and expires durations", () => {
|
||||
const base = 1_700_000_000_000;
|
||||
expect(resolveLinkExpiresAt({ ttl: "72h" }, base)).toBe(base + 72 * 60 * 60 * 1000);
|
||||
expect(resolveLinkExpiresAt({ ttl: "3d" }, base)).toBe(base + 3 * 24 * 60 * 60 * 1000);
|
||||
expect(resolveLinkExpiresAt({ expires: "3" }, base)).toBe(base + 3 * 24 * 60 * 60 * 1000);
|
||||
expect(resolveLinkExpiresAt({}, base)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,40 +0,0 @@
|
||||
import { CorpConfig } from "../config/types.js";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
import { createAuthClient } from "../http/factory.js";
|
||||
import { canRefreshCorpAccessToken, refreshSingleCorpAccessToken } from "./login.js";
|
||||
|
||||
export function getEkbHeaders(corp: CorpConfig): Record<string, string> {
|
||||
return {
|
||||
accesstoken: corp.credentials.accessToken,
|
||||
corpid: corp.corpId || corp.credentials.corpId,
|
||||
staffid: corp.staffId || corp.credentials.staffId,
|
||||
};
|
||||
}
|
||||
|
||||
export async function createEkbClient(corp: CorpConfig) {
|
||||
const canRefresh = canRefreshCorpAccessToken(corp);
|
||||
|
||||
// 1. 预检:若 Token 即将过期 (提前 refreshTtl 秒),静默无感自动续杯
|
||||
if (canRefresh && corp.auth?.expiresAt) {
|
||||
const ttlMs = (corp.auth.refreshTtl || 300) * 1000;
|
||||
if (Date.now() >= corp.auth.expiresAt - ttlMs) {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 仅账号凭证启用 401 自动重试与换票;临时凭证直接给出可操作错误
|
||||
return createAuthClient({
|
||||
prefixUrl: corp.baseUrl || "https://app.ekuaibao.com",
|
||||
getHeaders: () => getEkbHeaders(corp),
|
||||
retryUnauthorized: canRefresh,
|
||||
...(canRefresh
|
||||
? {
|
||||
onUnauthorized: async () => {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
},
|
||||
}
|
||||
: {
|
||||
onAuthFailure: () => new AuthenticationError("临时凭证已过期,请使用 hose-use corps add-link 重新导入"),
|
||||
}),
|
||||
});
|
||||
}
|
||||
+1290
-37
File diff suppressed because it is too large.
Load diff
@@ -10,20 +10,9 @@ export const PRIMARY_TOKEN_CACHE_PATH = join(
|
||||
"tokens.json"
|
||||
);
|
||||
|
||||
export const LEGACY_TOKEN_CACHE_PATH = join(
|
||||
homedir(),
|
||||
".cache",
|
||||
"ekb-mcp",
|
||||
"tokens.json"
|
||||
);
|
||||
export const TOKEN_CACHE_PATH = PRIMARY_TOKEN_CACHE_PATH;
|
||||
|
||||
function resolveTokenCachePath(): string {
|
||||
if (existsSync(PRIMARY_TOKEN_CACHE_PATH)) {
|
||||
return PRIMARY_TOKEN_CACHE_PATH;
|
||||
}
|
||||
if (existsSync(LEGACY_TOKEN_CACHE_PATH)) {
|
||||
return LEGACY_TOKEN_CACHE_PATH;
|
||||
}
|
||||
return PRIMARY_TOKEN_CACHE_PATH;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import { CorpContext } from "../config/manager.js";
|
||||
import { createEkbClient } from "./ekb.js";
|
||||
import { createSessionClient } from "../http/session-client.js";
|
||||
|
||||
// ── 精简 MCP Auth Tools (其余复杂登录/刷新均由 CLI 直接提供) ───────────────────
|
||||
|
||||
@@ -54,7 +54,7 @@ export const authTools = [
|
||||
let sessionValid = false;
|
||||
let sessionData: unknown = null;
|
||||
try {
|
||||
const client = await createEkbClient(current);
|
||||
const client = await createSessionClient(current);
|
||||
const res = await client.get("api/account/v2/session").json<{ value?: unknown }>();
|
||||
sessionData = res.value;
|
||||
sessionValid = !!res.value;
|
||||
|
||||
Vendored
+3
-1
@@ -80,7 +80,9 @@ export class SqliteCache implements ICache {
|
||||
[namespace, key, serialized, expiresAt, now]
|
||||
);
|
||||
} catch (err) {
|
||||
console.error(`[cache] SqliteCache.set error for ${namespace}:${key}:`, err);
|
||||
if (process.env.DEBUG || process.env.NODE_ENV === "development") {
|
||||
console.error(`[cache] SqliteCache.set error for ${namespace}:${key}:`, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync } from "node:fs";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync, utimesSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
@@ -11,6 +11,8 @@ import {
|
||||
loadGlobalConfig,
|
||||
saveGlobalConfig,
|
||||
resolveGlobalConfigFile,
|
||||
syncLegacyEnterprisesDir,
|
||||
syncLegacyGlobalConfig,
|
||||
} from "./loader.js";
|
||||
import type { CorpConfig } from "./types.js";
|
||||
|
||||
@@ -170,4 +172,45 @@ describe("core/config/loader", () => {
|
||||
expect(updated.stateful).toBe(false);
|
||||
expect(updated.defaultCorpId).toBe("test-corp-123");
|
||||
});
|
||||
|
||||
test("syncLegacyEnterprisesDir copies legacy credentials and removes stale legacy directory", () => {
|
||||
const primary = join(tempDir, "primary");
|
||||
const legacy = join(tempDir, "legacy");
|
||||
mkdirSync(legacy, { recursive: true });
|
||||
writeFileSync(join(legacy, "corp-old.json"), JSON.stringify(createMockCorp("corp-old", "旧企业")));
|
||||
const old = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000);
|
||||
utimesSync(join(legacy, "corp-old.json"), old, old);
|
||||
utimesSync(legacy, old, old);
|
||||
|
||||
const result = syncLegacyEnterprisesDir(primary, legacy);
|
||||
expect(result.copied).toEqual(["corp-old.json"]);
|
||||
expect(result.deletedLegacyDir).toBe(true);
|
||||
expect(existsSync(join(primary, "corp-old.json"))).toBe(true);
|
||||
expect(existsSync(legacy)).toBe(false);
|
||||
});
|
||||
|
||||
test("syncLegacyEnterprisesDir preserves a recently modified legacy directory", () => {
|
||||
const primary = join(tempDir, "primary-recent");
|
||||
const legacy = join(tempDir, "legacy-recent");
|
||||
mkdirSync(legacy, { recursive: true });
|
||||
writeFileSync(join(legacy, "corp-recent.json"), JSON.stringify(createMockCorp("corp-recent", "近期企业")));
|
||||
|
||||
const result = syncLegacyEnterprisesDir(primary, legacy);
|
||||
expect(result.deletedLegacyDir).toBe(false);
|
||||
expect(existsSync(legacy)).toBe(true);
|
||||
});
|
||||
|
||||
test("syncLegacyGlobalConfig migrates and removes a stale legacy config", () => {
|
||||
const primary = join(tempDir, "config", "config.json");
|
||||
const legacy = join(tempDir, "legacy-config.json");
|
||||
writeFileSync(legacy, JSON.stringify({ stateful: false }));
|
||||
const old = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000);
|
||||
utimesSync(legacy, old, old);
|
||||
|
||||
const result = syncLegacyGlobalConfig(primary, legacy);
|
||||
expect(result.copied).toBe(true);
|
||||
expect(result.deletedLegacyFile).toBe(true);
|
||||
expect(JSON.parse(readFileSync(primary, "utf8")).stateful).toBe(false);
|
||||
expect(existsSync(legacy)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
||||
import { 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";
|
||||
@@ -14,6 +14,8 @@ export const USER_ENTERPRISES_DIR = PRIMARY_USER_ENTERPRISES_DIR;
|
||||
export const PRIMARY_GLOBAL_CONFIG_FILE = join(homedir(), ".config", "hose-use", "config.json");
|
||||
export const LEGACY_GLOBAL_CONFIG_FILE = join(homedir(), ".cache", "ekb-mcp", "config.json");
|
||||
|
||||
const LEGACY_CLEANUP_GRACE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
function ensureDir(dir: string): void {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
@@ -27,7 +29,14 @@ export function resolveEnterprisesDirs(): string[] {
|
||||
const configuredUserDir = process.env[USER_DIR_ENV]?.trim();
|
||||
const userDirs = configuredUserDir
|
||||
? (existsSync(configuredUserDir) ? [configuredUserDir] : [])
|
||||
: [PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR];
|
||||
: (() => {
|
||||
try {
|
||||
syncLegacyEnterprisesDir();
|
||||
} catch {
|
||||
// Legacy migration must never prevent normal CLI startup.
|
||||
}
|
||||
return [PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR];
|
||||
})();
|
||||
|
||||
const globalConfig = loadGlobalConfig();
|
||||
const testDir = globalConfig.testEnterprisesDir?.trim();
|
||||
@@ -69,11 +78,70 @@ export function getEnterprisesDirCandidates(): string[] {
|
||||
export function resolveGlobalConfigFile(): string {
|
||||
const configured = process.env[GLOBAL_CONFIG_ENV]?.trim();
|
||||
if (configured) return configured;
|
||||
try {
|
||||
syncLegacyGlobalConfig();
|
||||
} catch {
|
||||
// Legacy migration must never prevent normal CLI startup.
|
||||
}
|
||||
if (existsSync(PRIMARY_GLOBAL_CONFIG_FILE)) return PRIMARY_GLOBAL_CONFIG_FILE;
|
||||
if (existsSync(LEGACY_GLOBAL_CONFIG_FILE)) return LEGACY_GLOBAL_CONFIG_FILE;
|
||||
return PRIMARY_GLOBAL_CONFIG_FILE;
|
||||
}
|
||||
|
||||
export function syncLegacyEnterprisesDir(
|
||||
primaryDir: string = PRIMARY_USER_ENTERPRISES_DIR,
|
||||
legacyDir: string = LEGACY_USER_ENTERPRISES_DIR
|
||||
): { copied: string[]; deletedLegacyDir: boolean } {
|
||||
if (!existsSync(legacyDir)) return { copied: [], deletedLegacyDir: false };
|
||||
|
||||
mkdirSync(primaryDir, { recursive: true, mode: 0o700 });
|
||||
const copied: string[] = [];
|
||||
const files = readdirSync(legacyDir).filter((file) => file.endsWith(".json"));
|
||||
|
||||
for (const file of files) {
|
||||
const legacyPath = join(legacyDir, file);
|
||||
const primaryPath = join(primaryDir, file);
|
||||
if (!existsSync(primaryPath) || statSync(legacyPath).mtimeMs > statSync(primaryPath).mtimeMs) {
|
||||
copyFileSync(legacyPath, primaryPath);
|
||||
copied.push(file);
|
||||
}
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const hasRecentEntry = readdirSync(legacyDir).some((file) => now - statSync(join(legacyDir, file)).mtimeMs < LEGACY_CLEANUP_GRACE_MS);
|
||||
const hasNewerLegacyFile = files.some((file) => {
|
||||
const legacyPath = join(legacyDir, file);
|
||||
const primaryPath = join(primaryDir, file);
|
||||
return existsSync(primaryPath) && statSync(legacyPath).mtimeMs > statSync(primaryPath).mtimeMs;
|
||||
});
|
||||
const directoryIsRecent = now - statSync(legacyDir).mtimeMs < LEGACY_CLEANUP_GRACE_MS;
|
||||
const deletedLegacyDir = !hasRecentEntry && !hasNewerLegacyFile && !directoryIsRecent;
|
||||
if (deletedLegacyDir) rmSync(legacyDir, { recursive: true, force: true });
|
||||
return { copied, deletedLegacyDir };
|
||||
}
|
||||
|
||||
export function syncLegacyGlobalConfig(
|
||||
primaryFile: string = PRIMARY_GLOBAL_CONFIG_FILE,
|
||||
legacyFile: string = LEGACY_GLOBAL_CONFIG_FILE
|
||||
): { copied: boolean; deletedLegacyFile: boolean } {
|
||||
if (!existsSync(legacyFile)) return { copied: false, deletedLegacyFile: false };
|
||||
mkdirSync(dirname(primaryFile), { recursive: true, mode: 0o700 });
|
||||
|
||||
let copied = false;
|
||||
if (!existsSync(primaryFile) || statSync(legacyFile).mtimeMs > statSync(primaryFile).mtimeMs) {
|
||||
copyFileSync(legacyFile, primaryFile);
|
||||
copied = true;
|
||||
}
|
||||
|
||||
const oldEnough = Date.now() - statSync(legacyFile).mtimeMs >= LEGACY_CLEANUP_GRACE_MS;
|
||||
const safeToDelete = existsSync(primaryFile) && statSync(legacyFile).mtimeMs <= statSync(primaryFile).mtimeMs && oldEnough;
|
||||
if (safeToDelete) {
|
||||
rmSync(legacyFile, { force: true });
|
||||
return { copied, deletedLegacyFile: true };
|
||||
}
|
||||
return { copied, deletedLegacyFile: false };
|
||||
}
|
||||
|
||||
export function loadGlobalConfig(): GlobalConfig {
|
||||
const file = resolveGlobalConfigFile();
|
||||
try {
|
||||
@@ -140,6 +208,26 @@ export function loadCorpConfigs(overrideDirs?: string[]): CorpConfig[] {
|
||||
export function saveCorpConfig(config: CorpConfig, dir?: string): string {
|
||||
const targetDir = dir || resolveWritableEnterprisesDir();
|
||||
ensureDir(targetDir);
|
||||
const candidatePath = join(targetDir, `${config.id}.json`);
|
||||
if (!config.credentials?.appKey && existsSync(candidatePath)) {
|
||||
try {
|
||||
const existing = JSON.parse(readFileSync(candidatePath, "utf-8"));
|
||||
const existingKey = existing?.credentials?.appKey || existing?.auth?.appKey;
|
||||
const existingSec = existing?.credentials?.appSecurity || existing?.auth?.appSecurity;
|
||||
if (existingKey && existingSec) {
|
||||
config = {
|
||||
...config,
|
||||
credentials: {
|
||||
...config.credentials,
|
||||
appKey: existingKey,
|
||||
appSecurity: existingSec,
|
||||
},
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// ignore malformed existing file
|
||||
}
|
||||
}
|
||||
const validated = CorpConfigSchema.parse(config);
|
||||
const filePath = join(targetDir, `${validated.id}.json`);
|
||||
writeFileSync(filePath, JSON.stringify(validated, null, 2), "utf-8");
|
||||
|
||||
+21
-12
@@ -12,6 +12,7 @@ export interface CorpSummary {
|
||||
baseUrl?: string;
|
||||
current: boolean;
|
||||
expiresAt?: number;
|
||||
persistent?: boolean;
|
||||
}
|
||||
|
||||
export function resolveCorpConfig(
|
||||
@@ -150,17 +151,25 @@ export class CorpContext {
|
||||
}
|
||||
|
||||
listCorps(): CorpSummary[] {
|
||||
return Array.from(this.corps.values()).map((corp) => ({
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
corpId: corp.corpId || corp.credentials.corpId,
|
||||
staffId: corp.credentials.staffId,
|
||||
staffName: corp.staffName || corp.session?.staffName || undefined,
|
||||
source: corp.source || "manual",
|
||||
accountId: corp.accountId,
|
||||
baseUrl: corp.baseUrl,
|
||||
current: corp.id === this.current?.id,
|
||||
expiresAt: corp.auth?.expiresAt || (corp.session?.expTime ?? undefined),
|
||||
}));
|
||||
return Array.from(this.corps.values()).map((corp) => {
|
||||
const hasOpenApiKeys = Boolean(
|
||||
(corp.credentials?.appKey || corp.auth?.appKey) &&
|
||||
(corp.credentials?.appSecurity || corp.auth?.appSecurity)
|
||||
);
|
||||
const hasAccountBinding = corp.source === "account" && !corp.session?.isShortTermToken && Boolean(corp.accountId);
|
||||
return {
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
corpId: corp.corpId || corp.credentials.corpId,
|
||||
staffId: corp.credentials.staffId,
|
||||
staffName: corp.staffName || corp.session?.staffName || undefined,
|
||||
source: corp.source || "manual",
|
||||
accountId: corp.accountId,
|
||||
baseUrl: corp.baseUrl,
|
||||
current: corp.id === this.current?.id,
|
||||
expiresAt: corp.auth?.expiresAt || (corp.session?.expTime ?? undefined),
|
||||
persistent: hasOpenApiKeys || hasAccountBinding,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { z } from "zod";
|
||||
|
||||
export const CredentialSourceSchema = z.enum([
|
||||
"account", // 官方统一认证中心 (IDP) 账密/短信登录
|
||||
"openapi", // 开放平台持久化密钥 (appKey + appSecurity)
|
||||
"assist", // 官方协助/代客平台 (Assist Platform) 调试授权会话
|
||||
"browser", // 浏览器会话 / Cookie 同步
|
||||
"link", // 协助/免密链接导入 (thirdparty.html / assistance link)
|
||||
@@ -12,15 +13,19 @@ export const CredentialSourceSchema = z.enum([
|
||||
export type CredentialSource = z.infer<typeof CredentialSourceSchema>;
|
||||
|
||||
export const CorpCredentialsSchema = z.object({
|
||||
accessToken: z.string().describe("主站访问令牌"),
|
||||
accessToken: z.string().default("").describe("主站访问令牌"),
|
||||
corpId: z.string().describe("企业 ID"),
|
||||
staffId: z.string().describe("员工 ID"),
|
||||
appKey: z.string().optional().describe("开放平台应用 AppKey (持久化凭证)"),
|
||||
appSecurity: z.string().optional().describe("开放平台应用 AppSecurity (持久化凭证)"),
|
||||
});
|
||||
|
||||
export const CorpAuthConfigSchema = z.object({
|
||||
refreshTtl: z.number().default(300).describe("提前多少秒刷新,默认 5 分钟"),
|
||||
refreshToken: z.string().optional().describe("OAuth2 Refresh Token"),
|
||||
expiresAt: z.number().optional().describe("AccessToken 到期时间戳 (ms)"),
|
||||
appKey: z.string().optional().describe("开放平台应用 AppKey (兼容冗余字段)"),
|
||||
appSecurity: z.string().optional().describe("开放平台应用 AppSecurity (兼容冗余字段)"),
|
||||
});
|
||||
|
||||
export const CorpSessionInfoSchema = z.object({
|
||||
|
||||
@@ -66,6 +66,45 @@ describe("Core DB - 数据库连接与结构化迁移机制 (加固测试)", ()
|
||||
expect(countRow.c).toBe(2);
|
||||
});
|
||||
|
||||
test("migration 2 可以平滑升级遗留的单列主键 cache_entries 表", () => {
|
||||
const legacyDb = new Database(":memory:");
|
||||
legacyDb.run(`
|
||||
CREATE TABLE cache_entries (
|
||||
key TEXT PRIMARY KEY,
|
||||
namespace TEXT NOT NULL,
|
||||
value TEXT NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
`);
|
||||
legacyDb.run(
|
||||
"INSERT INTO cache_entries (key, namespace, value, expires_at, updated_at) VALUES ('k1', 'n1', 'v1', 9999, 1000)"
|
||||
);
|
||||
|
||||
// 运行全量迁移
|
||||
runMigrations(legacyDb);
|
||||
|
||||
// 验证升级后支持相同 key 不同 namespace
|
||||
expect(() => {
|
||||
legacyDb.run(
|
||||
"INSERT INTO cache_entries (key, namespace, value, expires_at, updated_at) VALUES ('k1', 'n2', 'v2', 9999, 1000)"
|
||||
);
|
||||
}).not.toThrow();
|
||||
|
||||
// 验证 ON CONFLICT(namespace, key) 正常工作
|
||||
expect(() => {
|
||||
legacyDb.run(`
|
||||
INSERT INTO cache_entries (namespace, key, value, expires_at, updated_at)
|
||||
VALUES ('n1', 'k1', 'v1_updated', 9999, 2000)
|
||||
ON CONFLICT(namespace, key) DO UPDATE SET value = excluded.value
|
||||
`);
|
||||
}).not.toThrow();
|
||||
|
||||
const row = legacyDb.query("SELECT value FROM cache_entries WHERE namespace = 'n1' AND key = 'k1'").get() as { value: string };
|
||||
expect(row.value).toBe("v1_updated");
|
||||
legacyDb.close();
|
||||
});
|
||||
|
||||
test("再次执行 runMigrations 保证幂等且不抛错", () => {
|
||||
expect(() => runMigrations(db)).not.toThrow();
|
||||
});
|
||||
|
||||
@@ -144,6 +144,46 @@ export const migrations: DatabaseMigration[] = [
|
||||
seedDefaultPreference(db);
|
||||
},
|
||||
},
|
||||
{
|
||||
version: 2,
|
||||
name: "002_cache_entries_composite_primary_key",
|
||||
up(db: Database): void {
|
||||
// 检查 cache_entries 的主键约束
|
||||
// 兼容历史遗留的 key PRIMARY KEY 单列主键库,平滑升级为复合主键 (namespace, key)
|
||||
const tableInfo = db.query("PRAGMA table_info(cache_entries)").all() as Array<{
|
||||
name: string;
|
||||
pk: number;
|
||||
}>;
|
||||
const pkColumns = tableInfo.filter((col) => col.pk > 0);
|
||||
const isCompositePk =
|
||||
pkColumns.length === 2 &&
|
||||
pkColumns.some((c) => c.name === "namespace") &&
|
||||
pkColumns.some((c) => c.name === "key");
|
||||
|
||||
if (!isCompositePk) {
|
||||
db.run(`
|
||||
CREATE TABLE IF NOT EXISTS cache_entries_v2 (
|
||||
namespace TEXT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
value TEXT NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (namespace, key)
|
||||
);
|
||||
`);
|
||||
try {
|
||||
db.run(`
|
||||
INSERT OR IGNORE INTO cache_entries_v2 (namespace, key, value, expires_at, updated_at)
|
||||
SELECT namespace, key, value, expires_at, updated_at FROM cache_entries;
|
||||
`);
|
||||
} catch {}
|
||||
db.run("DROP TABLE IF EXISTS cache_entries;");
|
||||
db.run("ALTER TABLE cache_entries_v2 RENAME TO cache_entries;");
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_cache_namespace ON cache_entries(namespace);");
|
||||
db.run("CREATE INDEX IF NOT EXISTS idx_cache_expires_at ON cache_entries(expires_at);");
|
||||
}
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
function seedDefaultPreference(db: Database): void {
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, rmSync, existsSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { homedir, tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { EMBEDDED_SKILL_FILES, getSkillContent, installSkillFiles } from "./embedded-skill.js";
|
||||
import { EMBEDDED_SKILL_FILES, getDefaultGlobalSkillDir, getSkillContent, installSkillFiles } from "./embedded-skill.js";
|
||||
|
||||
describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
|
||||
test("全局 Skill 目录固定为 ~/.agents/skills/hose-use", () => {
|
||||
expect(getDefaultGlobalSkillDir()).toBe(join(homedir(), ".agents", "skills", "hose-use"));
|
||||
});
|
||||
|
||||
test("正确内嵌 SKILL.md、agents/openai.yaml 及各领域参考专卷", () => {
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("name: hose-use");
|
||||
@@ -32,6 +36,17 @@ describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
|
||||
expect(EMBEDDED_SKILL_FILES["references/approval.md"]).toContain("hose-aipro");
|
||||
expect(EMBEDDED_SKILL_FILES["references/feetype.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/feetype.md"]).toContain("feetype");
|
||||
expect(EMBEDDED_SKILL_FILES["references/store.md"]).toBeDefined();
|
||||
expect(EMBEDDED_SKILL_FILES["references/store.md"]).toContain("hose-use keys");
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("--reveal -o <path>");
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("references/store.md");
|
||||
|
||||
// 套件结构:根入口路由到 multi/ 下的子技能
|
||||
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("multi/ekuaibao-mvel/SKILL.md");
|
||||
expect(EMBEDDED_SKILL_FILES["multi/ekuaibao-mvel/SKILL.md"]).toContain("name: ekuaibao-mvel");
|
||||
expect(EMBEDDED_SKILL_FILES["multi/ekuaibao-mvel/agents/openai.yaml"]).toContain("ekuaibao-mvel");
|
||||
expect(EMBEDDED_SKILL_FILES["multi/ekuaibao-nodes/SKILL.md"]).toContain("name: ekuaibao-nodes");
|
||||
expect(EMBEDDED_SKILL_FILES["multi/ekuaibao-nodes/references/gray-nodes.md"]).toContain("灰度节点清单");
|
||||
});
|
||||
|
||||
test("installSkillFiles 递归保留层级结构并落盘到目标目录", () => {
|
||||
@@ -39,7 +54,7 @@ describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
|
||||
try {
|
||||
const res = installSkillFiles(tmp);
|
||||
expect(res.targetDir).toBe(tmp);
|
||||
expect(res.files.length).toBe(13);
|
||||
expect(res.files.length).toBe(18);
|
||||
expect(existsSync(join(tmp, "SKILL.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "agents", "openai.yaml"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "auth.md"))).toBe(true);
|
||||
@@ -50,6 +65,9 @@ describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
|
||||
expect(existsSync(join(tmp, "references", "role.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "workflow.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "service.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "store.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "multi", "ekuaibao-mvel", "SKILL.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "multi", "ekuaibao-nodes", "references", "gray-nodes.md"))).toBe(true);
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
@@ -15,6 +15,11 @@ import refDimension from "../../skills/hose-use/references/dimension.md" with {
|
||||
import refRole from "../../skills/hose-use/references/role.md" with { type: "text" };
|
||||
import refApproval from "../../skills/hose-use/references/approval.md" with { type: "text" };
|
||||
import refFeeType from "../../skills/hose-use/references/feetype.md" with { type: "text" };
|
||||
import refStore from "../../skills/hose-use/references/store.md" with { type: "text" };
|
||||
import multiMvel from "../../skills/hose-use/multi/ekuaibao-mvel/SKILL.md" with { type: "text" };
|
||||
import multiMvelAgent from "../../skills/hose-use/multi/ekuaibao-mvel/agents/openai.yaml" with { type: "text" };
|
||||
import multiNodes from "../../skills/hose-use/multi/ekuaibao-nodes/SKILL.md" with { type: "text" };
|
||||
import multiNodesGray from "../../skills/hose-use/multi/ekuaibao-nodes/references/gray-nodes.md" with { type: "text" };
|
||||
|
||||
export const EMBEDDED_SKILL_FILES: Record<string, string> = {
|
||||
"SKILL.md": skillMain,
|
||||
@@ -30,6 +35,11 @@ export const EMBEDDED_SKILL_FILES: Record<string, string> = {
|
||||
"references/role.md": refRole,
|
||||
"references/workflow.md": refWorkflow,
|
||||
"references/service.md": refService,
|
||||
"references/store.md": refStore,
|
||||
"multi/ekuaibao-mvel/SKILL.md": multiMvel,
|
||||
"multi/ekuaibao-mvel/agents/openai.yaml": multiMvelAgent,
|
||||
"multi/ekuaibao-nodes/SKILL.md": multiNodes,
|
||||
"multi/ekuaibao-nodes/references/gray-nodes.md": multiNodesGray,
|
||||
};
|
||||
|
||||
export function getSkillContent(): string {
|
||||
@@ -40,14 +50,6 @@ export function getDefaultGlobalSkillDir(): string {
|
||||
return join(homedir(), ".agents", "skills", "hose-use");
|
||||
}
|
||||
|
||||
export function getAgentSkillCandidates(): string[] {
|
||||
return [
|
||||
join(homedir(), ".agents", "skills", "hose-use"),
|
||||
join(homedir(), ".gemini", "antigravity", "skills", "hose-use"),
|
||||
join(homedir(), ".codex", "skills", "hose-use"),
|
||||
];
|
||||
}
|
||||
|
||||
export function installSkillFiles(targetDir: string = getDefaultGlobalSkillDir()): {
|
||||
targetDir: string;
|
||||
files: string[];
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import {
|
||||
getBrowserFingerprintHeaders,
|
||||
DEFAULT_USER_AGENT,
|
||||
DEFAULT_REFERER,
|
||||
DEFAULT_ORIGIN,
|
||||
} from "./fingerprint.js";
|
||||
import {
|
||||
getSessionHeaders,
|
||||
createSessionClient,
|
||||
} from "./session-client.js";
|
||||
import {
|
||||
createOpenApiClient,
|
||||
getOpenApiHeaders,
|
||||
} from "./openapi-client.js";
|
||||
import { resolveCorpCluster } from "./unity-client.js";
|
||||
import { getScriptEngineClient } from "./script-engine-client.js";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
|
||||
function mockCorp(overrides: Partial<CorpConfig> = {}): CorpConfig {
|
||||
return {
|
||||
id: "mock-corp",
|
||||
name: "测试企业",
|
||||
source: "link",
|
||||
credentials: {
|
||||
accessToken: "mock-access-token",
|
||||
corpId: "mock-corp-id",
|
||||
staffId: "mock-staff-id",
|
||||
},
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("core/http/fingerprint", () => {
|
||||
it("generates default modern browser fingerprint headers", () => {
|
||||
const headers = getBrowserFingerprintHeaders();
|
||||
expect(headers["User-Agent"]).toBe(DEFAULT_USER_AGENT);
|
||||
expect(headers["Referer"]).toBe(DEFAULT_REFERER);
|
||||
expect(headers["Origin"]).toBe(DEFAULT_ORIGIN);
|
||||
expect(headers["sec-ch-ua-platform"]).toBe('"macOS"');
|
||||
expect(headers["sec-ch-ua"]).toContain("Chrome");
|
||||
expect(headers["Cookie"]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("supports custom cookie and referer", () => {
|
||||
const headers = getBrowserFingerprintHeaders({
|
||||
cookie: "SESSION=abc123xyz; cloud_waf=token456",
|
||||
referer: "https://custom.ekuaibao.com/flow",
|
||||
});
|
||||
expect(headers["Cookie"]).toBe("SESSION=abc123xyz; cloud_waf=token456");
|
||||
expect(headers["Referer"]).toBe("https://custom.ekuaibao.com/flow");
|
||||
});
|
||||
});
|
||||
|
||||
describe("core/http/session-client", () => {
|
||||
it("merges closed session headers with browser fingerprint", () => {
|
||||
const corp = mockCorp();
|
||||
const headers = getSessionHeaders(corp);
|
||||
|
||||
// 核心三 Header 校验
|
||||
expect(headers.accesstoken).toBe("mock-access-token");
|
||||
expect(headers.corpid).toBe("mock-corp-id");
|
||||
expect(headers.staffid).toBe("mock-staff-id");
|
||||
|
||||
// 统一防爬指纹校验
|
||||
expect(headers["User-Agent"]).toBe(DEFAULT_USER_AGENT);
|
||||
expect(headers["Origin"]).toBe(DEFAULT_ORIGIN);
|
||||
});
|
||||
|
||||
it("createSessionClient produces valid client", async () => {
|
||||
const corp = mockCorp();
|
||||
const client = await createSessionClient(corp);
|
||||
expect(client).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("core/http/openapi-client", () => {
|
||||
it("builds correct OpenAPI request headers", () => {
|
||||
const headers = getOpenApiHeaders("test-app-token-123");
|
||||
expect(headers["app-token"]).toBe("test-app-token-123");
|
||||
expect(headers["Authorization"]).toBe("Bearer test-app-token-123");
|
||||
expect(headers["User-Agent"]).toBe(DEFAULT_USER_AGENT);
|
||||
});
|
||||
|
||||
it("creates OpenAPI client with static appToken", async () => {
|
||||
const client = await createOpenApiClient({
|
||||
appToken: "static-token",
|
||||
baseUrl: "https://app.ekuaibao.com",
|
||||
});
|
||||
expect(client).toBeDefined();
|
||||
});
|
||||
|
||||
it("fails to create OpenAPI client when neither auth nor appToken is provided", async () => {
|
||||
await expect(createOpenApiClient({})).rejects.toThrow(
|
||||
"创建 OpenAPI 客户端失败: 必须提供 auth 凭据或 appToken"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("core/http/unity-client & script-engine-client", () => {
|
||||
it("resolves corp cluster from cluster property or baseUrl", () => {
|
||||
expect(resolveCorpCluster({ cluster: "shanghai" })).toBe("shanghai");
|
||||
expect(resolveCorpCluster({ baseUrl: "https://wx2.ekuaibao.com" })).toBe("wx2");
|
||||
expect(resolveCorpCluster({ baseUrl: "https://app.ekuaibao.com" })).toBe("app");
|
||||
expect(resolveCorpCluster({})).toBe("app");
|
||||
});
|
||||
|
||||
it("getScriptEngineClient is defined and callable", () => {
|
||||
expect(getScriptEngineClient).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import ky, { KyInstance } from "ky";
|
||||
export interface CreateClientOptions {
|
||||
prefixUrl: string;
|
||||
headers?: Record<string, string>;
|
||||
timeout?: number | false;
|
||||
}
|
||||
|
||||
export interface CreateAuthClientOptions {
|
||||
@@ -11,18 +12,21 @@ export interface CreateAuthClientOptions {
|
||||
onUnauthorized?: () => Promise<void> | void;
|
||||
onAuthFailure?: (response: Response) => Error;
|
||||
retryUnauthorized?: boolean;
|
||||
timeout?: number | false;
|
||||
}
|
||||
|
||||
export function createClient(options: CreateClientOptions): KyInstance {
|
||||
return ky.create({
|
||||
prefix: options.prefixUrl,
|
||||
headers: options.headers,
|
||||
timeout: options.timeout ?? 30000,
|
||||
});
|
||||
}
|
||||
|
||||
export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
|
||||
return ky.create({
|
||||
prefix: options.prefixUrl,
|
||||
timeout: options.timeout ?? 30000,
|
||||
retry: {
|
||||
limit: options.retryUnauthorized === false ? 0 : 1,
|
||||
methods: ["get", "post", "put", "delete", "patch"],
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* 统一浏览器指纹与请求头生成器
|
||||
* 用于防范 WAF 拦截 (如 CloudWAF 418/403) 及统一 Web 会话环境
|
||||
*/
|
||||
|
||||
export interface BrowserFingerprintOptions {
|
||||
/** 自定义 Cookie 字符串 */
|
||||
cookie?: string;
|
||||
/** 自定义 Referer 来源 (默认 https://app.ekuaibao.com/) */
|
||||
referer?: string;
|
||||
/** 自定义 Origin 域 (默认 https://app.ekuaibao.com) */
|
||||
origin?: string;
|
||||
/** 是否禁用 Sec-Ch-Ua 等客户端提示头 (默认 false) */
|
||||
disableClientHints?: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_USER_AGENT =
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36";
|
||||
|
||||
export const DEFAULT_REFERER = "https://app.ekuaibao.com/";
|
||||
export const DEFAULT_ORIGIN = "https://app.ekuaibao.com";
|
||||
|
||||
/**
|
||||
* 获取伪装现代浏览器的标准指纹请求头
|
||||
*/
|
||||
export function getBrowserFingerprintHeaders(
|
||||
options: BrowserFingerprintOptions = {}
|
||||
): Record<string, string> {
|
||||
const headers: Record<string, string> = {
|
||||
"User-Agent": DEFAULT_USER_AGENT,
|
||||
Accept: "application/json, text/plain, */*",
|
||||
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
|
||||
Referer: options.referer ?? DEFAULT_REFERER,
|
||||
Origin: options.origin ?? DEFAULT_ORIGIN,
|
||||
};
|
||||
|
||||
if (!options.disableClientHints) {
|
||||
headers["sec-ch-ua"] = '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"';
|
||||
headers["sec-ch-ua-mobile"] = "?0";
|
||||
headers["sec-ch-ua-platform"] = '"macOS"';
|
||||
}
|
||||
|
||||
if (options.cookie && options.cookie.trim()) {
|
||||
headers["Cookie"] = options.cookie.trim();
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* HTTP 客户端基础设施总入口
|
||||
* 包含基础 Ky 客户端工厂、浏览器指纹伪装、闭合用户会话客户端、开放平台客户端、集群客户端及脚本流引擎客户端。
|
||||
*/
|
||||
|
||||
// 1. 底层 Ky 基础工厂
|
||||
export {
|
||||
createClient,
|
||||
createAuthClient,
|
||||
type CreateClientOptions,
|
||||
type CreateAuthClientOptions,
|
||||
} from "./factory.js";
|
||||
|
||||
// 2. 统一浏览器指纹与防爬请求头
|
||||
export {
|
||||
getBrowserFingerprintHeaders,
|
||||
DEFAULT_USER_AGENT,
|
||||
DEFAULT_REFERER,
|
||||
DEFAULT_ORIGIN,
|
||||
type BrowserFingerprintOptions,
|
||||
} from "./fingerprint.js";
|
||||
|
||||
// 3. 闭合用户会话客户端 (Session Client)
|
||||
export {
|
||||
createSessionClient,
|
||||
getSessionHeaders,
|
||||
type CreateSessionClientOptions,
|
||||
} from "./session-client.js";
|
||||
|
||||
// 4. 开放平台 OpenAPI 客户端 (OpenAPI Client)
|
||||
export {
|
||||
createOpenApiClient,
|
||||
fetchOpenApiToken,
|
||||
getOpenApiHeaders,
|
||||
type OpenApiAuthConfig,
|
||||
type CreateOpenApiClientOptions,
|
||||
} from "./openapi-client.js";
|
||||
|
||||
// 5. 应用中心与集群寻址客户端 (Unity Client)
|
||||
export {
|
||||
getUnityClient,
|
||||
getEasoClient,
|
||||
resolveCorpCluster,
|
||||
fetchUnityJwt,
|
||||
fetchHoseToken,
|
||||
} from "./unity-client.js";
|
||||
|
||||
// 6. 工作流脚本调试引擎客户端 (Script Engine Client)
|
||||
export {
|
||||
getScriptEngineClient,
|
||||
fetchEasoJwt,
|
||||
} from "./script-engine-client.js";
|
||||
@@ -0,0 +1,133 @@
|
||||
import ky, { type KyInstance } from "ky";
|
||||
import { createAuthClient, createClient } from "./factory.js";
|
||||
import {
|
||||
getBrowserFingerprintHeaders,
|
||||
type BrowserFingerprintOptions,
|
||||
} from "./fingerprint.js";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
|
||||
export interface OpenApiAuthConfig {
|
||||
/** 开放应用 AppKey */
|
||||
appKey: string;
|
||||
/** 开放应用 AppSecurity / AppSecret */
|
||||
appSecurity: string;
|
||||
/** 自定义网关基准地址 (默认 https://app.ekuaibao.com) */
|
||||
baseUrl?: string;
|
||||
}
|
||||
|
||||
export interface CreateOpenApiClientOptions {
|
||||
/** 开放平台应用认证凭据 */
|
||||
auth?: OpenApiAuthConfig;
|
||||
/** 直接传入已知且有效的 app-token */
|
||||
appToken?: string;
|
||||
/** 基础 API URL (默认 https://app.ekuaibao.com) */
|
||||
baseUrl?: string;
|
||||
/** 请求超时 (默认 30000ms) */
|
||||
timeout?: number | false;
|
||||
/** 浏览器与网络指纹配置 */
|
||||
fingerprint?: BrowserFingerprintOptions;
|
||||
}
|
||||
|
||||
// 内存缓存:OpenAPI Token 缓存表
|
||||
const openApiTokenCache = new Map<string, { token: string; expiresAt: number }>();
|
||||
|
||||
/**
|
||||
* 通过开放平台应用凭据 (appKey + appSecurity) 获取 app-token
|
||||
*/
|
||||
export async function fetchOpenApiToken(
|
||||
auth: OpenApiAuthConfig
|
||||
): Promise<string> {
|
||||
const baseUrl = auth.baseUrl || "https://app.ekuaibao.com";
|
||||
const cacheKey = `${auth.appKey}:${baseUrl}`;
|
||||
|
||||
const cached = openApiTokenCache.get(cacheKey);
|
||||
if (cached && Date.now() < cached.expiresAt - 300 * 1000) {
|
||||
return cached.token;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await ky
|
||||
.post(`${baseUrl}/api/openapi/v2/auth/token`, {
|
||||
json: {
|
||||
appKey: auth.appKey,
|
||||
appSecurity: auth.appSecurity,
|
||||
},
|
||||
timeout: 15000,
|
||||
})
|
||||
.json<{ value?: string; token?: string; accessToken?: string }>();
|
||||
|
||||
const token = response.value || response.token || response.accessToken;
|
||||
if (!token) {
|
||||
throw new AuthenticationError("获取 OpenAPI app-token 失败: 返回值缺少 token");
|
||||
}
|
||||
|
||||
// 默认缓存 110 分钟 (标准有效期通常为 2 小时)
|
||||
openApiTokenCache.set(cacheKey, {
|
||||
token,
|
||||
expiresAt: Date.now() + 110 * 60 * 1000,
|
||||
});
|
||||
|
||||
return token;
|
||||
} catch (error: any) {
|
||||
if (error instanceof AuthenticationError) throw error;
|
||||
throw new AuthenticationError(
|
||||
`OpenAPI 换票失败 (${auth.appKey}): ${error?.message || String(error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装 OpenAPI 专属请求头
|
||||
*/
|
||||
export function getOpenApiHeaders(
|
||||
appToken?: string,
|
||||
options?: BrowserFingerprintOptions
|
||||
): Record<string, string> {
|
||||
const headers = getBrowserFingerprintHeaders(options);
|
||||
if (appToken) {
|
||||
headers["app-token"] = appToken;
|
||||
headers["Authorization"] = `Bearer ${appToken}`;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建合思开放平台客户端 (OpenAPI Client)
|
||||
* 适用于自建应用、OpenAPI 接口调用与机器系统对接
|
||||
*/
|
||||
export async function createOpenApiClient(
|
||||
options: CreateOpenApiClientOptions
|
||||
): Promise<KyInstance> {
|
||||
const baseUrl = options.baseUrl || options.auth?.baseUrl || "https://app.ekuaibao.com";
|
||||
|
||||
// 若直接提供静态 token 且无自动换票凭据
|
||||
if (options.appToken && !options.auth) {
|
||||
const staticToken = options.appToken;
|
||||
return createClient({
|
||||
prefixUrl: baseUrl,
|
||||
headers: getOpenApiHeaders(staticToken, options.fingerprint),
|
||||
timeout: options.timeout,
|
||||
});
|
||||
}
|
||||
|
||||
// 若提供 appKey / appSecurity,则构建支持 401 自动换票重试的 Client
|
||||
if (options.auth) {
|
||||
const authConfig = options.auth;
|
||||
let currentToken = options.appToken || (await fetchOpenApiToken(authConfig));
|
||||
|
||||
return createAuthClient({
|
||||
prefixUrl: baseUrl,
|
||||
timeout: options.timeout,
|
||||
getHeaders: () => getOpenApiHeaders(currentToken, options.fingerprint),
|
||||
retryUnauthorized: true,
|
||||
onUnauthorized: async () => {
|
||||
const cacheKey = `${authConfig.appKey}:${authConfig.baseUrl || baseUrl}`;
|
||||
openApiTokenCache.delete(cacheKey);
|
||||
currentToken = await fetchOpenApiToken(authConfig);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 既无 token 又无 auth,抛出参数异常
|
||||
throw new AuthenticationError("创建 OpenAPI 客户端失败: 必须提供 auth 凭据或 appToken");
|
||||
}
|
||||
@@ -1,15 +1,20 @@
|
||||
import ky from "ky";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
import { createAuthClient } from "../../core/http/factory.js";
|
||||
import { AuthenticationError } from "../../core/errors.js";
|
||||
import { resolveCorpCluster } from "./easo.js";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
import { createAuthClient } from "./factory.js";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
import {
|
||||
resolveCorpCluster,
|
||||
fetchHoseToken,
|
||||
EKB_BASE_URL,
|
||||
} from "./unity-client.js";
|
||||
|
||||
const PIPER_BASE_URL = "https://piper.ekuaibao.com";
|
||||
const BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com";
|
||||
const EKB_BASE_URL = "https://app.ekuaibao.com";
|
||||
export const SCRIPT_ENGINE_BASE_URL = "https://piper.ekuaibao.com";
|
||||
|
||||
// 兼容历史常量名
|
||||
export const PIPER_BASE_URL = SCRIPT_ENGINE_BASE_URL;
|
||||
|
||||
// 内存缓存
|
||||
const piperMemoryCache = new Map<
|
||||
const scriptEngineMemoryCache = new Map<
|
||||
string,
|
||||
{ jwt: string; hoseToken: string; expiresAt: number }
|
||||
>();
|
||||
@@ -18,27 +23,7 @@ function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
|
||||
return Date.now() >= entry.expiresAt - refreshTtl * 1000;
|
||||
}
|
||||
|
||||
async function fetchHoseToken(
|
||||
accessToken: string,
|
||||
corpId: string,
|
||||
environment: string = "app"
|
||||
): Promise<string> {
|
||||
const response = await ky
|
||||
.get(`${BUSINESS_CENTER_URL}/auth/oauth2/grant/ekb/accessToken`, {
|
||||
searchParams: {
|
||||
corpId,
|
||||
ekbAccessToken: accessToken,
|
||||
environment,
|
||||
},
|
||||
})
|
||||
.json<{ data: string }>();
|
||||
if (!response.data) {
|
||||
throw new AuthenticationError("Failed to fetch hose-access-token");
|
||||
}
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async function fetchEasoJwt(
|
||||
export async function fetchEasoJwt(
|
||||
accessToken: string,
|
||||
corpId: string,
|
||||
staffId: string,
|
||||
@@ -61,24 +46,28 @@ async function fetchEasoJwt(
|
||||
return token;
|
||||
}
|
||||
|
||||
export async function getPiperClient(
|
||||
/**
|
||||
* 获取工作流脚本执行引擎客户端 (Workflow Script Engine Client / Piper Client)
|
||||
* 适用于 MVEL、Python 等工作流代码节点的在线执行与调试
|
||||
*/
|
||||
export async function getScriptEngineClient(
|
||||
corp: CorpConfig,
|
||||
platformId: string
|
||||
): Promise<ReturnType<typeof createAuthClient>> {
|
||||
const refreshTtl = corp.auth?.refreshTtl ?? 300;
|
||||
const cacheKey = `${corp.id}:${platformId}:piper`;
|
||||
const cacheKey = `${corp.id}:${platformId}:script-engine`;
|
||||
|
||||
// 检查内存缓存
|
||||
const mem = piperMemoryCache.get(cacheKey);
|
||||
const mem = scriptEngineMemoryCache.get(cacheKey);
|
||||
if (mem && !isExpired(mem, refreshTtl)) {
|
||||
return createAuthClient({
|
||||
prefixUrl: PIPER_BASE_URL,
|
||||
prefixUrl: SCRIPT_ENGINE_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${mem.jwt}`,
|
||||
platformid: platformId,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
piperMemoryCache.delete(cacheKey);
|
||||
scriptEngineMemoryCache.delete(cacheKey);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -107,17 +96,17 @@ export async function getPiperClient(
|
||||
expiresAt: Date.now() + 2 * 60 * 60 * 1000, // 2小时
|
||||
};
|
||||
|
||||
piperMemoryCache.set(cacheKey, entry);
|
||||
scriptEngineMemoryCache.set(cacheKey, entry);
|
||||
|
||||
return createAuthClient({
|
||||
prefixUrl: PIPER_BASE_URL,
|
||||
prefixUrl: SCRIPT_ENGINE_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${easoJwt}`,
|
||||
platformid: platformId,
|
||||
hoseaccesstoken: hoseToken,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
piperMemoryCache.delete(cacheKey);
|
||||
scriptEngineMemoryCache.delete(cacheKey);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
canRefreshCorpAccessToken,
|
||||
getCorpProvisionalAuthLink,
|
||||
hasOpenApiPersistentCredentials,
|
||||
resolveLinkExpiresAt,
|
||||
selectOpenApiKey,
|
||||
} from "../auth/login.js";
|
||||
import { createSessionClient } from "./session-client.js";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
|
||||
function corp(overrides: Partial<CorpConfig> = {}): CorpConfig {
|
||||
return {
|
||||
id: "corp-1",
|
||||
name: "测试企业",
|
||||
source: "link",
|
||||
credentials: { accessToken: "token", corpId: "corp-1", staffId: "corp-1:staff-1" },
|
||||
...overrides,
|
||||
baseUrl: overrides.baseUrl ?? "https://app.ekuaibao.com",
|
||||
};
|
||||
}
|
||||
|
||||
describe("core/http/session-client refresh policy", () => {
|
||||
it("allows refresh for account credentials or OpenAPI persistent credentials", () => {
|
||||
expect(canRefreshCorpAccessToken(corp())).toBe(false);
|
||||
expect(canRefreshCorpAccessToken(corp({ source: "browser", accountId: "86-1" }))).toBe(false);
|
||||
expect(canRefreshCorpAccessToken(corp({ source: "account" }))).toBe(false);
|
||||
expect(canRefreshCorpAccessToken(corp({ source: "account", accountId: "86-1" }))).toBe(true);
|
||||
expect(canRefreshCorpAccessToken(corp({ source: "account", accountId: "86-1", session: { isShortTermToken: true } }))).toBe(false);
|
||||
|
||||
const openApiCorp = corp({
|
||||
source: "link",
|
||||
credentials: {
|
||||
accessToken: "token",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
appKey: "key-123",
|
||||
appSecurity: "sec-456",
|
||||
},
|
||||
});
|
||||
expect(hasOpenApiPersistentCredentials(openApiCorp)).toBe(true);
|
||||
expect(canRefreshCorpAccessToken(openApiCorp)).toBe(true);
|
||||
});
|
||||
|
||||
it("fails expired temporary credentials without retrying or refreshing", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
let calls = 0;
|
||||
globalThis.fetch = (async () => {
|
||||
calls += 1;
|
||||
return new Response("expired", { status: 401 });
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
try {
|
||||
const client = await createSessionClient(corp());
|
||||
await expect(client.get("api/test")).rejects.toThrow("临时凭证已过期,请使用 hose-use corps add-link 重新导入");
|
||||
expect(calls).toBe(1);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
it("automatically refreshes expired token via OpenAPI getProvisionalAuth when appKey/appSecurity are present", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "hose-use-test-"));
|
||||
const prevEnv = process.env.HOSE_ENTERPRISES_DIR;
|
||||
process.env.HOSE_ENTERPRISES_DIR = tempDir;
|
||||
|
||||
const seenUrls: string[] = [];
|
||||
globalThis.fetch = (async (input: string | URL | Request) => {
|
||||
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
||||
seenUrls.push(url);
|
||||
if (url.includes("/api/openapi/v1/auth/getAccessToken")) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
value: {
|
||||
accessToken: "openapi-token-xyz",
|
||||
corporationId: "corp-1",
|
||||
expireTime: Date.now() + 7200_000,
|
||||
},
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } }
|
||||
);
|
||||
}
|
||||
if (url.includes("/api/openapi/v1.1/provisional/getProvisionalAuth")) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
value: {
|
||||
message:
|
||||
"https://app.ekuaibao.com/web/thirdparty.html?accessToken=fresh-session-token-999&ekbCorpId=corp-1",
|
||||
},
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } }
|
||||
);
|
||||
}
|
||||
return new Response(JSON.stringify({ value: { ok: true } }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
try {
|
||||
const persistentCorp = corp({
|
||||
source: "openapi",
|
||||
credentials: {
|
||||
accessToken: "",
|
||||
corpId: "corp-1",
|
||||
staffId: "corp-1:staff-1",
|
||||
appKey: "test-app-key",
|
||||
appSecurity: "test-app-security",
|
||||
},
|
||||
auth: {
|
||||
refreshTtl: 300,
|
||||
expiresAt: Date.now() - 10_000,
|
||||
},
|
||||
});
|
||||
|
||||
const client = await createSessionClient(persistentCorp);
|
||||
expect(persistentCorp.credentials.accessToken).toBe("fresh-session-token-999");
|
||||
|
||||
const linkRes = await getCorpProvisionalAuthLink(persistentCorp, { enterprisesDir: tempDir });
|
||||
expect(linkRes.method).toBe("provisional-openapi");
|
||||
expect(linkRes.url).toContain("accessToken=fresh-session-token-999");
|
||||
expect(client).toBeDefined();
|
||||
expect(seenUrls.some((u) => u.includes("getProvisionalAuth"))).toBe(true);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
if (prevEnv === undefined) delete process.env.HOSE_ENTERPRISES_DIR;
|
||||
else process.env.HOSE_ENTERPRISES_DIR = prevEnv;
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("core/auth/login > selectOpenApiKey", () => {
|
||||
const sampleKeys = [
|
||||
{ id: "k1", name: "停用密钥", appKey: "ak-1", appSecurity: "sec-1", active: false },
|
||||
{ id: "k2", name: "启用密钥A", appKey: "ak-2", appSecurity: "sec-2", active: true },
|
||||
{ id: "k3", name: "启用密钥B", appKey: "ak-3", appSecurity: "sec-3", active: true },
|
||||
];
|
||||
|
||||
it("auto-selects when only one active key exists", () => {
|
||||
const picked = selectOpenApiKey([sampleKeys[0]!, sampleKeys[1]!], "corp-1");
|
||||
expect(picked.appKey).toBe("ak-2");
|
||||
});
|
||||
|
||||
it("requires explicit selection or --force when multiple active keys exist", () => {
|
||||
expect(() => selectOpenApiKey(sampleKeys, "corp-1")).toThrow("存在多套");
|
||||
expect(selectOpenApiKey(sampleKeys, "corp-1", { force: true }).appKey).toBe("ak-2");
|
||||
expect(selectOpenApiKey(sampleKeys, "corp-1", { appKey: "ak-3" }).appKey).toBe("ak-3");
|
||||
});
|
||||
});
|
||||
|
||||
describe("core/auth/login link expiry", () => {
|
||||
it("parses explicit ttl and expires durations", () => {
|
||||
const base = 1_700_000_000_000;
|
||||
expect(resolveLinkExpiresAt({ ttl: "72h" }, base)).toBe(base + 72 * 60 * 60 * 1000);
|
||||
expect(resolveLinkExpiresAt({ ttl: "3d" }, base)).toBe(base + 3 * 24 * 60 * 60 * 1000);
|
||||
expect(resolveLinkExpiresAt({ expires: "3" }, base)).toBe(base + 3 * 24 * 60 * 60 * 1000);
|
||||
expect(resolveLinkExpiresAt({}, base)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
import { createAuthClient } from "./factory.js";
|
||||
import {
|
||||
getBrowserFingerprintHeaders,
|
||||
type BrowserFingerprintOptions,
|
||||
} from "./fingerprint.js";
|
||||
import {
|
||||
canRefreshCorpAccessToken,
|
||||
refreshSingleCorpAccessToken,
|
||||
} from "../auth/login.js";
|
||||
|
||||
export interface CreateSessionClientOptions {
|
||||
/** 额外的指纹或请求头配置 */
|
||||
fingerprint?: BrowserFingerprintOptions;
|
||||
/** 超时毫秒数 (默认 30000) */
|
||||
timeout?: number | false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取闭合用户会话所必需的认证请求头与浏览器指纹
|
||||
*/
|
||||
export function getSessionHeaders(
|
||||
corp: CorpConfig,
|
||||
fingerprintOptions?: BrowserFingerprintOptions
|
||||
): Record<string, string> {
|
||||
const baseHeaders = getBrowserFingerprintHeaders(fingerprintOptions);
|
||||
|
||||
return {
|
||||
...baseHeaders,
|
||||
accesstoken: corp.credentials.accessToken,
|
||||
corpid: corp.corpId || corp.credentials.corpId,
|
||||
staffid: corp.staffId || corp.credentials.staffId,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建合思闭合用户会话客户端 (Session Client)
|
||||
* 适用于内部单据台账、审批流、员工角色、配置等闭环操作
|
||||
*/
|
||||
export async function createSessionClient(
|
||||
corp: CorpConfig,
|
||||
options: CreateSessionClientOptions = {}
|
||||
) {
|
||||
const canRefresh = canRefreshCorpAccessToken(corp);
|
||||
|
||||
// 1. 预检:若 Token 缺失或即将过期 (提前 refreshTtl 秒),静默无感自动续杯
|
||||
if (canRefresh) {
|
||||
const ttlMs = (corp.auth?.refreshTtl || 300) * 1000;
|
||||
const expiresAt = corp.auth?.expiresAt || corp.session?.expTime;
|
||||
if (!corp.credentials.accessToken || (expiresAt && Date.now() >= expiresAt - ttlMs)) {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 具备续期能力(主账号或 OpenAPI 持久化密钥)时启用 401 自动重试与换票;临时凭证直接给出可操作错误
|
||||
return createAuthClient({
|
||||
prefixUrl: corp.baseUrl || "https://app.ekuaibao.com",
|
||||
getHeaders: () => getSessionHeaders(corp, options.fingerprint),
|
||||
timeout: options.timeout,
|
||||
retryUnauthorized: canRefresh,
|
||||
...(canRefresh
|
||||
? {
|
||||
onUnauthorized: async () => {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
},
|
||||
}
|
||||
: {
|
||||
onAuthFailure: () =>
|
||||
new AuthenticationError("临时凭证已过期,请使用 hose-use corps add-link 重新导入"),
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -1,12 +1,19 @@
|
||||
import ky from "ky";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
import { createAuthClient } from "../../core/http/factory.js";
|
||||
import { AuthenticationError } from "../../core/errors.js";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
import { createAuthClient } from "./factory.js";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
import {
|
||||
canRefreshCorpAccessToken,
|
||||
refreshSingleCorpAccessToken,
|
||||
} from "../auth/login.js";
|
||||
|
||||
const EASO_BASE_URL = "https://unity.ekuaibao.com";
|
||||
const BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com";
|
||||
const EKB_BASE_URL = "https://app.ekuaibao.com";
|
||||
export const EASO_BASE_URL = "https://unity.ekuaibao.com";
|
||||
export const BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com";
|
||||
export const EKB_BASE_URL = "https://app.ekuaibao.com";
|
||||
|
||||
/**
|
||||
* 根据企业配置动态解析部署集群 (如 app, wx2, shanghai 等)
|
||||
*/
|
||||
export function resolveCorpCluster(corp: { cluster?: string; baseUrl?: string }): string {
|
||||
if (corp.cluster && corp.cluster.trim()) {
|
||||
return corp.cluster.trim();
|
||||
@@ -38,7 +45,7 @@ function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
|
||||
return Date.now() >= entry.expiresAt - refreshTtl * 1000;
|
||||
}
|
||||
|
||||
async function fetchHoseToken(
|
||||
export async function fetchHoseToken(
|
||||
accessToken: string,
|
||||
corpId: string,
|
||||
environment: string = "app"
|
||||
@@ -81,7 +88,7 @@ export async function fetchUnityJwt(
|
||||
return token;
|
||||
}
|
||||
|
||||
async function fetchEasoRealmToken(
|
||||
export async function fetchEasoRealmToken(
|
||||
corpId: string,
|
||||
unityJwt: string,
|
||||
hoseToken: string
|
||||
@@ -102,6 +109,9 @@ async function fetchEasoRealmToken(
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 EASO 授权客户端 (用于请求 EASO 体系资源)
|
||||
*/
|
||||
export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
client: ReturnType<typeof createAuthClient>;
|
||||
}> {
|
||||
@@ -127,6 +137,13 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
};
|
||||
}
|
||||
|
||||
if (canRefreshCorpAccessToken(corp)) {
|
||||
const expiresAt = corp.auth?.expiresAt || corp.session?.expTime;
|
||||
if (!corp.credentials.accessToken || (expiresAt && Date.now() >= expiresAt - refreshTtl * 1000)) {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
}
|
||||
}
|
||||
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const staffId = corp.staffId || corp.credentials.staffId;
|
||||
const environment = resolveCorpCluster(corp);
|
||||
@@ -174,6 +191,10 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 Unity 应用中心与开放微服务集群客户端 (Unity Client)
|
||||
* 适用于应用商店、已购应用查询等场景
|
||||
*/
|
||||
export async function getUnityClient(corp: CorpConfig): Promise<{
|
||||
client: ReturnType<typeof createAuthClient>;
|
||||
unityJwt: string;
|
||||
@@ -197,6 +218,13 @@ export async function getUnityClient(corp: CorpConfig): Promise<{
|
||||
};
|
||||
}
|
||||
|
||||
if (canRefreshCorpAccessToken(corp)) {
|
||||
const expiresAt = corp.auth?.expiresAt || corp.session?.expTime;
|
||||
if (!corp.credentials.accessToken || (expiresAt && Date.now() >= expiresAt - refreshTtl * 1000)) {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
}
|
||||
}
|
||||
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const staffId = corp.staffId || corp.credentials.staffId;
|
||||
const baseUrl = corp.baseUrl || EKB_BASE_URL;
|
||||
@@ -227,4 +255,3 @@ export async function getUnityClient(corp: CorpConfig): Promise<{
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -17,7 +17,13 @@ src/domains/bill/
|
||||
|
||||
1. **单据检索与分页 (`searchAndFormatBills`)**:
|
||||
- 跨单据池查询费用明细、报销单、借款单与发票。
|
||||
- 支持按单号(`code`)、阶段(`stage`)、状态(`state`)、关键字(`keyword`)过滤。
|
||||
- 原生支持合思服务端 `filterBy` 索引检索(杜绝全表拉取与大租户超时):
|
||||
- 时间范围(`since`、`startDate`、`endDate`、`from`、`to`);
|
||||
- 单号服务端索引匹配(`code`,使用 `.in(...)` 语法避免 WAF 拦截);
|
||||
- 名称与标题关键字跨字段复合匹配(`keyword` 与 `searchFields`,默认跨 `name,code,form` 服务端 `INSTR(...) > 0` 复合 OR 检索,支持单字段或自定义字段集);
|
||||
- 状态与软删除过滤(`active.in(true)`);
|
||||
- 服务端 `orderBy: [{ value: "createTime", order: "DESC" }]` 排序与精简 `select` 字段;
|
||||
- 客户端辅助精确二次过滤:阶段(`stage`)、状态(`state`)。
|
||||
2. **按单号/ID 精确查询 (`getBillByCodeOrId`)**:
|
||||
- 根据业务单号(如 `n0GMIM0dkQmKbS`)或单据 ID(如 `ID01TRzg7HMLcb`)查询单据。
|
||||
3. **DataLink 字段元数据字典 (`getFieldDictionary`)**:
|
||||
|
||||
+43
-8
@@ -310,19 +310,54 @@ export async function getRawBillRisk(
|
||||
|
||||
// ── 原始单据检索 API ──────────────────────────────────────────────────────────
|
||||
|
||||
export interface RawBillSearchOptions {
|
||||
start?: number;
|
||||
count?: number;
|
||||
timeout?: number | false;
|
||||
filterBy?: string;
|
||||
orderBy?: Array<{ value: string; order: "ASC" | "DESC" }>;
|
||||
select?: string;
|
||||
distinct?: boolean;
|
||||
join?: string | string[];
|
||||
}
|
||||
|
||||
export async function searchRawBills(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: { start?: number; count?: number } = {}
|
||||
options: RawBillSearchOptions = {}
|
||||
): Promise<RawBillSearchResponse> {
|
||||
const response = await client.post("api/v2/invoice/search", {
|
||||
searchParams: { corporationId: corpId, corpId },
|
||||
json: {
|
||||
limit: {
|
||||
start: options.start ?? 0,
|
||||
count: options.count ?? 50,
|
||||
},
|
||||
const jsonBody: Record<string, unknown> = {
|
||||
limit: {
|
||||
start: options.start ?? 0,
|
||||
count: options.count ?? 50,
|
||||
},
|
||||
};
|
||||
|
||||
if (options.filterBy) {
|
||||
jsonBody.filterBy = options.filterBy;
|
||||
}
|
||||
if (options.orderBy && options.orderBy.length > 0) {
|
||||
jsonBody.orderBy = options.orderBy;
|
||||
}
|
||||
if (options.select) {
|
||||
jsonBody.select = options.select;
|
||||
}
|
||||
if (options.distinct !== undefined) {
|
||||
jsonBody.distinct = options.distinct;
|
||||
}
|
||||
|
||||
const searchParams: Record<string, string> = {
|
||||
corporationId: corpId,
|
||||
corpId,
|
||||
};
|
||||
if (options.join) {
|
||||
searchParams.join = Array.isArray(options.join) ? options.join.join(";") : options.join;
|
||||
}
|
||||
|
||||
const response = await client.post("api/v2/invoice/search", {
|
||||
searchParams,
|
||||
timeout: options.timeout ?? 30000,
|
||||
json: jsonBody,
|
||||
});
|
||||
|
||||
const json = await response.json();
|
||||
|
||||
@@ -1,5 +1,23 @@
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import { formatSingleBill, getBillReferences, getBillRelations, getBillAttachments, getBillRisk, getBillFlow, approveBill, rejectBill, transferBill, addNodeBill, commentBill, resolveBillStaffIds } from "./tools.js";
|
||||
import {
|
||||
formatSingleBill,
|
||||
getBillReferences,
|
||||
getBillRelations,
|
||||
getBillAttachments,
|
||||
getBillRisk,
|
||||
getBillFlow,
|
||||
approveBill,
|
||||
rejectBill,
|
||||
transferBill,
|
||||
addNodeBill,
|
||||
commentBill,
|
||||
resolveBillStaffIds,
|
||||
parseDateFilter,
|
||||
parseSinceDuration,
|
||||
normalizeSearchFields,
|
||||
buildServerBillFilterBy,
|
||||
searchAndFormatBills,
|
||||
} from "./tools.js";
|
||||
import { RawBillItemSchema, EntitySchema } from "./types.js";
|
||||
|
||||
describe("Bill Domain", () => {
|
||||
@@ -539,4 +557,160 @@ describe("Bill Domain", () => {
|
||||
expect(md).toContain("1. `18-1-服务框架协议书.pdf` (fileId=\"ID01TvInwhsEwf\")");
|
||||
expect(md).toContain("2. `钰泰账单.pdf` (fileId=\"ID01VWUmNcRryf\")");
|
||||
});
|
||||
|
||||
describe("Server-Side Filter & Date Helpers", () => {
|
||||
it("parses relative since durations accurately", () => {
|
||||
expect(parseSinceDuration("1h")).toBe(3600 * 1000);
|
||||
expect(parseSinceDuration("7d")).toBe(7 * 86400 * 1000);
|
||||
expect(parseSinceDuration("30d")).toBe(30 * 86400 * 1000);
|
||||
expect(parseSinceDuration("2w")).toBe(14 * 86400 * 1000);
|
||||
expect(parseSinceDuration("invalid")).toBeUndefined();
|
||||
expect(parseSinceDuration(undefined)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("parses date filter strings and end-of-day offsets", () => {
|
||||
expect(parseDateFilter("1788220800000")).toBe(1788220800000);
|
||||
expect(parseDateFilter(1788220800000)).toBe(1788220800000);
|
||||
const startMs = parseDateFilter("2026-09-01");
|
||||
expect(typeof startMs).toBe("number");
|
||||
|
||||
const endMs = parseDateFilter("2026-09-01", true);
|
||||
expect(typeof endMs).toBe("number");
|
||||
expect((endMs ?? 0) > (startMs ?? 0)).toBe(true);
|
||||
});
|
||||
|
||||
it("builds WAF-safe server filterBy expressions with .in() pattern", () => {
|
||||
const empty = buildServerBillFilterBy({});
|
||||
expect(empty).toBe("(active.in(true))");
|
||||
|
||||
const codeFilter = buildServerBillFilterBy({ code: "n140LKxUbHkGUU" });
|
||||
expect(codeFilter).toContain('(code.in("n140LKxUbHkGUU"))');
|
||||
expect(codeFilter).toContain("(active.in(true))");
|
||||
|
||||
const keywordFilter = buildServerBillFilterBy({ keyword: "打车" });
|
||||
expect(keywordFilter).toContain('INSTR(name, "打车") > 0');
|
||||
expect(keywordFilter).toContain('INSTR(code, "打车") > 0');
|
||||
expect(keywordFilter).toContain('INSTR(form, "打车") > 0');
|
||||
|
||||
const timeFilter = buildServerBillFilterBy({ since: "7d" });
|
||||
expect(timeFilter).toContain("createTime >");
|
||||
|
||||
const inactiveFilter = buildServerBillFilterBy({ active: false });
|
||||
expect(inactiveFilter).toBe("(active.in(false))");
|
||||
});
|
||||
|
||||
it("normalizes searchFields parameter correctly", () => {
|
||||
expect(normalizeSearchFields()).toEqual(["name", "code", "form"]);
|
||||
expect(normalizeSearchFields(undefined)).toEqual(["name", "code", "form"]);
|
||||
expect(normalizeSearchFields("")).toEqual(["name", "code", "form"]);
|
||||
expect(normalizeSearchFields("name,code")).toEqual(["name", "code"]);
|
||||
expect(normalizeSearchFields(" name , code , form ")).toEqual(["name", "code", "form"]);
|
||||
expect(normalizeSearchFields(["name", "form"])).toEqual(["name", "form"]);
|
||||
expect(normalizeSearchFields([" ", "code"])).toEqual(["code"]);
|
||||
expect(normalizeSearchFields([])).toEqual(["name", "code", "form"]);
|
||||
});
|
||||
|
||||
it("builds multi-field composite OR and single-field RQL based on searchFields", () => {
|
||||
// Default: name, code, form composite OR
|
||||
const defaultFilter = buildServerBillFilterBy({ keyword: "差旅" });
|
||||
expect(defaultFilter).toContain(
|
||||
'((INSTR(name, "差旅") > 0) || (INSTR(code, "差旅") > 0) || (INSTR(form, "差旅") > 0))'
|
||||
);
|
||||
|
||||
// Single field: direct INSTR without outer ||
|
||||
const singleFieldFilter = buildServerBillFilterBy({
|
||||
keyword: "差旅",
|
||||
searchFields: "name",
|
||||
});
|
||||
expect(singleFieldFilter).toContain('(INSTR(name, "差旅") > 0)');
|
||||
expect(singleFieldFilter).not.toContain("||");
|
||||
|
||||
// Multiple explicit fields array: composite OR
|
||||
const multiArrayFilter = buildServerBillFilterBy({
|
||||
keyword: "差旅",
|
||||
searchFields: ["code", "form"],
|
||||
});
|
||||
expect(multiArrayFilter).toContain(
|
||||
'((INSTR(code, "差旅") > 0) || (INSTR(form, "差旅") > 0))'
|
||||
);
|
||||
expect(multiArrayFilter).not.toContain("INSTR(name,");
|
||||
|
||||
// Multiple comma-separated string fields: composite OR
|
||||
const multiStringFilter = buildServerBillFilterBy({
|
||||
keyword: "差旅",
|
||||
searchFields: "name,code",
|
||||
});
|
||||
expect(multiStringFilter).toContain(
|
||||
'((INSTR(name, "差旅") > 0) || (INSTR(code, "差旅") > 0))'
|
||||
);
|
||||
expect(multiStringFilter).not.toContain("INSTR(form,");
|
||||
});
|
||||
|
||||
it("filters bills in memory accurately based on searchFields", async () => {
|
||||
const mockRawBills = [
|
||||
{
|
||||
id: "bill-1",
|
||||
code: "CODE-TAXI",
|
||||
name: "办公用品采购",
|
||||
form: {},
|
||||
createTime: 1000,
|
||||
updateTime: 1000,
|
||||
},
|
||||
{
|
||||
id: "bill-2",
|
||||
code: "CODE-OFFICE",
|
||||
name: "打车报销",
|
||||
form: {},
|
||||
createTime: 2000,
|
||||
updateTime: 2000,
|
||||
},
|
||||
{
|
||||
id: "bill-3",
|
||||
code: "CODE-MEAL",
|
||||
name: "餐饮费用",
|
||||
form: { description: "打车去餐厅" },
|
||||
createTime: 3000,
|
||||
updateTime: 3000,
|
||||
},
|
||||
];
|
||||
|
||||
const client = {
|
||||
get: async (path: string) => {
|
||||
if (path.includes("entities")) {
|
||||
return new Response(JSON.stringify({ items: [] }));
|
||||
}
|
||||
return new Response(JSON.stringify({}));
|
||||
},
|
||||
post: async () => new Response(JSON.stringify({ count: 3, items: mockRawBills })),
|
||||
} as any;
|
||||
|
||||
// 1. Search only 'name': only bill-2 matches
|
||||
const resName = await searchAndFormatBills(client, "test-corp", {
|
||||
keyword: "打车",
|
||||
searchFields: "name",
|
||||
});
|
||||
expect(resName.items.map((b) => b.billId)).toEqual(["bill-2"]);
|
||||
|
||||
// 2. Search only 'code': only bill-1 matches (CODE-TAXI)
|
||||
const resCode = await searchAndFormatBills(client, "test-corp", {
|
||||
keyword: "TAXI",
|
||||
searchFields: "code",
|
||||
});
|
||||
expect(resCode.items.map((b) => b.billId)).toEqual(["bill-1"]);
|
||||
|
||||
// 3. Search 'form': only bill-3 matches
|
||||
const resForm = await searchAndFormatBills(client, "test-corp", {
|
||||
keyword: "餐厅",
|
||||
searchFields: "form",
|
||||
});
|
||||
expect(resForm.items.map((b) => b.billId)).toEqual(["bill-3"]);
|
||||
|
||||
// 4. Search default (name, code, form): bill-2 and bill-3 match '打车'
|
||||
const resDefault = await searchAndFormatBills(client, "test-corp", {
|
||||
keyword: "打车",
|
||||
});
|
||||
expect(resDefault.items.map((b) => b.billId)).toEqual(["bill-2", "bill-3"]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
+160
-14
@@ -32,6 +32,7 @@ import {
|
||||
} from "./translator.js";
|
||||
import {
|
||||
type RawBillItem,
|
||||
type RawBillSearchResponse,
|
||||
type FormattedBill,
|
||||
type BillPageResult,
|
||||
type EntityMeta,
|
||||
@@ -49,7 +50,7 @@ import {
|
||||
type BillAttachmentReport,
|
||||
} from "./types.js";
|
||||
import { CorpContext } from "../../core/config/manager.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
import { resolveDimension } from "../dimension/tools.js";
|
||||
|
||||
// ── 通用内置字段中文 Label 字典 ───────────────────────────────────────────────
|
||||
@@ -1139,16 +1140,144 @@ export async function getBillRisk(
|
||||
|
||||
// ── 业务操作:多条件搜索与分页单据 ─────────────────────────────────────────────
|
||||
|
||||
export function parseDateFilter(value: string | number | undefined, isEnd = false): number | undefined {
|
||||
if (value === undefined || value === "") return undefined;
|
||||
if (typeof value === "number") return value;
|
||||
const trimmed = String(value).trim();
|
||||
if (!trimmed) return undefined;
|
||||
if (/^\d+$/.test(trimmed)) return Number(trimmed);
|
||||
const parsed = Date.parse(trimmed);
|
||||
if (!Number.isNaN(parsed)) {
|
||||
if (isEnd && /^\d{4}-\d{2}-\d{2}$/.test(trimmed)) {
|
||||
const d = new Date(parsed);
|
||||
d.setHours(23, 59, 59, 999);
|
||||
return d.getTime();
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function parseSinceDuration(since: string | undefined): number | undefined {
|
||||
if (!since) return undefined;
|
||||
const match = /^(\d+)([dhmyw])$/i.exec(since.trim());
|
||||
if (!match) return undefined;
|
||||
const count = Number(match[1]);
|
||||
const unit = match[2].toLowerCase();
|
||||
const MS_PER_HOUR = 3600 * 1000;
|
||||
const MS_PER_DAY = 24 * MS_PER_HOUR;
|
||||
switch (unit) {
|
||||
case "h": return count * MS_PER_HOUR;
|
||||
case "d": return count * MS_PER_DAY;
|
||||
case "w": return count * 7 * MS_PER_DAY;
|
||||
case "m": return count * 30 * MS_PER_DAY;
|
||||
case "y": return count * 365 * MS_PER_DAY;
|
||||
default: return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeSearchFields(fields?: string[] | string): string[] {
|
||||
if (!fields) return ["name", "code", "form"];
|
||||
if (Array.isArray(fields)) {
|
||||
const list = fields.map((f) => f.trim()).filter(Boolean);
|
||||
return list.length > 0 ? list : ["name", "code", "form"];
|
||||
}
|
||||
const list = fields.split(",").map((f) => f.trim()).filter(Boolean);
|
||||
return list.length > 0 ? list : ["name", "code", "form"];
|
||||
}
|
||||
|
||||
export function buildServerBillFilterBy(params: BillQueryParams): string | undefined {
|
||||
if (params.filterBy && params.filterBy.trim()) {
|
||||
return params.filterBy.trim();
|
||||
}
|
||||
|
||||
const parts: string[] = [];
|
||||
|
||||
// 1. active 软删除过滤 (使用 .in 避免 CloudWAF 误拦截)
|
||||
if (params.active !== false) {
|
||||
parts.push("(active.in(true))");
|
||||
} else if (params.active === false) {
|
||||
parts.push("(active.in(false))");
|
||||
}
|
||||
|
||||
// 2. 时间范围过滤
|
||||
let fromTime = params.from ?? parseDateFilter(params.startDate);
|
||||
if (params.since) {
|
||||
const duration = parseSinceDuration(params.since);
|
||||
if (duration !== undefined) {
|
||||
fromTime = Math.max(fromTime ?? 0, Date.now() - duration);
|
||||
}
|
||||
}
|
||||
const toTime = params.to ?? parseDateFilter(params.endDate, true);
|
||||
|
||||
if (fromTime !== undefined) {
|
||||
parts.push(`(createTime > ${fromTime})`);
|
||||
}
|
||||
if (toTime !== undefined) {
|
||||
parts.push(`(createTime < ${toTime})`);
|
||||
}
|
||||
|
||||
// 3. 单号服务端过滤 (使用 .in 避免 CloudWAF 误拦截)
|
||||
if (params.code && params.code.trim()) {
|
||||
parts.push(`(code.in(${JSON.stringify(params.code.trim())}))`);
|
||||
}
|
||||
|
||||
// 4. 关键字跨字段检索 (支持通过 searchFields 指定单字段或多字段联合 RQL)
|
||||
if (params.keyword && params.keyword.trim()) {
|
||||
const kw = params.keyword.trim();
|
||||
const fields = normalizeSearchFields(params.searchFields);
|
||||
if (fields.length === 1) {
|
||||
parts.push(`(INSTR(${fields[0]}, ${JSON.stringify(kw)}) > 0)`);
|
||||
} else {
|
||||
const fieldParts = fields.map(
|
||||
(f) => `(INSTR(${f}, ${JSON.stringify(kw)}) > 0)`
|
||||
);
|
||||
parts.push(`(${fieldParts.join(" || ")})`);
|
||||
}
|
||||
}
|
||||
|
||||
if (parts.length === 0) return undefined;
|
||||
if (parts.length === 1) return parts[0];
|
||||
return `(${parts.join(" && ")})`;
|
||||
}
|
||||
|
||||
export async function searchAndFormatBills(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
params: BillQueryParams = {}
|
||||
): Promise<BillPageResult> {
|
||||
const { dictionary } = await getFieldDictionary(client, corpId);
|
||||
const searchRes = await searchRawBills(client, corpId, {
|
||||
start: params.start ?? 0,
|
||||
count: params.count ?? 50,
|
||||
});
|
||||
|
||||
const filterBy = buildServerBillFilterBy(params);
|
||||
const sortDirection = (params.order || "DESC").toUpperCase() as "ASC" | "DESC";
|
||||
const orderBy = params.orderBy && params.orderBy.length > 0
|
||||
? params.orderBy
|
||||
: [{ value: "createTime", order: sortDirection }];
|
||||
|
||||
let searchRes: RawBillSearchResponse;
|
||||
try {
|
||||
searchRes = await searchRawBills(client, corpId, {
|
||||
start: params.start ?? 0,
|
||||
count: params.count ?? 20,
|
||||
filterBy,
|
||||
orderBy,
|
||||
select: params.select || "id,code,name,createTime,updateTime,form,active",
|
||||
distinct: params.distinct,
|
||||
join: params.join,
|
||||
});
|
||||
} catch (err) {
|
||||
if (String(err).includes("timed out") || (err as any)?.name === "TimeoutError") {
|
||||
throw new Error(
|
||||
`全局单据台账检索超时。在大企业或海量单据租户中,建议指定时间范围或单号筛选:\n` +
|
||||
`建议:\n` +
|
||||
` - 指定时间范围:hose-use bill list --since=7d 或 --start-date=2026-09-01\n` +
|
||||
` - 查看当前员工发起的单据:hose-use task submitted 或 hose-use bill list --mine\n` +
|
||||
` - 查看待我审批单据:hose-use task todo\n` +
|
||||
` - 按单号精确查询:hose-use bill get <单号>`
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
let filtered = searchRes.items;
|
||||
|
||||
@@ -1192,11 +1321,20 @@ export async function searchAndFormatBills(
|
||||
|
||||
if (params.keyword) {
|
||||
const kw = params.keyword.trim().toLowerCase();
|
||||
const fields = normalizeSearchFields(params.searchFields);
|
||||
filtered = filtered.filter((it) => {
|
||||
if (it.name?.toLowerCase().includes(kw)) return true;
|
||||
if (it.code?.toLowerCase().includes(kw)) return true;
|
||||
for (const v of Object.values(it.form || {})) {
|
||||
if (typeof v === "string" && v.toLowerCase().includes(kw)) return true;
|
||||
if (fields.includes("name") && it.name?.toLowerCase().includes(kw)) return true;
|
||||
if (fields.includes("code") && it.code?.toLowerCase().includes(kw)) return true;
|
||||
if (fields.includes("form")) {
|
||||
for (const v of Object.values(it.form || {})) {
|
||||
if (typeof v === "string" && v.toLowerCase().includes(kw)) return true;
|
||||
}
|
||||
}
|
||||
for (const field of fields) {
|
||||
if (field !== "name" && field !== "code" && field !== "form") {
|
||||
const val = (it as any)[field] ?? (it.form as any)?.[field];
|
||||
if (typeof val === "string" && val.toLowerCase().includes(kw)) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
@@ -1216,23 +1354,31 @@ export async function searchAndFormatBills(
|
||||
export const billTools = [
|
||||
{
|
||||
name: "bill_search",
|
||||
description: "检索企业名下的费用单据、报销单、借款单与发票列表(已自动将字段代码还原为可读业务名称)",
|
||||
description: "检索企业名下的费用单据、报销单、借款单与发票列表(已自动将字段代码还原为可读业务名称,原生支持服务端时间与单号过滤)",
|
||||
parameters: z.object({
|
||||
code: z.string().optional().describe("按单据编号/单号过滤(如 jO1it3cIufDjNS)"),
|
||||
keyword: z.string().optional().describe("按关键字模糊搜索标题、名称或内容"),
|
||||
searchFields: z.union([z.array(z.string()), z.string()]).optional().describe("指定 keyword 检索匹配的字段列表,默认 ['name', 'code', 'form'],可传入 ['name'] 或 'name,code' 等"),
|
||||
since: z.string().optional().describe("相对时间范围,如 7d (7天), 30d (30天), 90d, 1y"),
|
||||
startDate: z.string().optional().describe("起始时间 (YYYY-MM-DD 或毫秒时间戳)"),
|
||||
endDate: z.string().optional().describe("截止时间 (YYYY-MM-DD 或毫秒时间戳)"),
|
||||
filterBy: z.string().optional().describe("原始合思 RQL 检索表达式,如 ((createTime > 1780000000000) && (code.in('BX-001')))"),
|
||||
select: z.string().optional().describe("按需返回字段(逗号分隔),如 id,code,name,createTime,updateTime,form"),
|
||||
distinct: z.boolean().optional().describe("是否对单据结果去重"),
|
||||
stage: z.string().optional().describe("按阶段过滤(如 expense 报销, loan 借款, payment 付款)"),
|
||||
state: z.string().optional().describe("按审批/支付状态过滤(如 paid 已支付, approving 审批中, draft 草稿)"),
|
||||
count: z.number().optional().default(20).describe("拉取记录数"),
|
||||
order: z.enum(["ASC", "DESC", "asc", "desc"]).optional().default("DESC").describe("排序方向,默认 DESC 最新在前"),
|
||||
}),
|
||||
handler: async (
|
||||
{ corpContext }: { corpContext: CorpContext },
|
||||
params: { code?: string; keyword?: string; stage?: string; state?: string; count?: number }
|
||||
params: BillQueryParams
|
||||
) => {
|
||||
const corp = corpContext.getCurrent();
|
||||
if (!corp) {
|
||||
throw new Error("未配置活跃企业上下文");
|
||||
}
|
||||
const client = await createEkbClient(corp);
|
||||
const client = await createSessionClient(corp);
|
||||
const result = await searchAndFormatBills(client, corp.corpId || corp.id, params);
|
||||
return {
|
||||
corpId: corp.corpId || corp.id,
|
||||
@@ -1255,7 +1401,7 @@ export const billTools = [
|
||||
if (!corp) {
|
||||
throw new Error("未配置活跃企业上下文");
|
||||
}
|
||||
const client = await createEkbClient(corp);
|
||||
const client = await createSessionClient(corp);
|
||||
const bills = await getBillByCodeOrId(client, corp.corpId || corp.id, params.code);
|
||||
if (bills.length === 0) {
|
||||
return {
|
||||
@@ -1280,7 +1426,7 @@ export const billTools = [
|
||||
if (!corp) {
|
||||
throw new Error("未配置活跃企业上下文");
|
||||
}
|
||||
const client = await createEkbClient(corp);
|
||||
const client = await createSessionClient(corp);
|
||||
const { entities } = await getFieldDictionary(client, corp.corpId || corp.id, true);
|
||||
return {
|
||||
corpId: corp.corpId || corp.id,
|
||||
|
||||
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user