Compare commits

..
14 Commits
Author SHA1 Message Date
yunyingk c72f07f582 Merge pull request #85 from yunyingk/release/v0.8.8
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
chore(release): v0.8.8
2026-09-17 16:03:07 +08:00
gitea edeb2a56f8 chore(release): bump version to v0.8.8 and update docs/skill 2026-09-17 16:02:48 +08:00
yunyingk 28eab40145 Merge pull request #84 from yunyingk/feat/bill-search-fields
feat(bill): 支持服务端跨字段检索与 --search-fields 参数
2026-09-17 16:00:18 +08:00
gitea bcb77feabb feat(bill): 支持服务端跨字段检索与 --search-fields 参数 2026-09-17 15:59:56 +08:00
yunyingk 7e16a6a312 Merge pull request #83 from yunyingk/refactor/complete-semantic-cleanup
refactor(core): 全量语义化客户端迁移并移除历史兼容桥接层
2026-09-17 15:44:45 +08:00
gitea d0f3d2738a refactor(core): 全量语义化客户端迁移并移除历史兼容桥接层 2026-09-17 15:44:25 +08:00
yunyingk 29ac24248e Merge pull request #82 from yunyingk/refactor/semantic-http-clients
refactor(core): 抽象语义化 HTTP 客户端与统一防爬指纹管理
2026-09-17 15:33:35 +08:00
gitea aa69b50e6e refactor(core): 抽象语义化 HTTP 客户端与统一防爬指纹管理 2026-09-17 15:32:56 +08:00
yunyingk 1322e2eab9 Merge pull request #81 from yunyingk/feat/bill-server-filtering
feat(bill): add server-side filterBy support and clarify status skill rules
2026-09-17 15:26:09 +08:00
gitea 139e50395d feat(bill): expose raw filterBy, select, distinct, and join in search API and CLI 2026-09-17 15:08:38 +08:00
gitea ca713cfafc feat(bill): add server-side filterBy support and clarify status skill rules 2026-09-17 14:58:02 +08:00
yunyingk 4b75132b43 feat(agents): add .agents modular rules with manual trigger (keep .agents, omit .agent) (#80)
- Match seal-use repository layout with .agents/rules and skills.json
- Ensure no .agent singular directory or symlink exists
- Set trigger: 'manual' on all rules to prevent automatic prompt injection
- Track .agents/ in git by updating .gitignore
2026-09-17 10:20:10 +08:00
yunyingk 240ec92931 Revert "feat(agents): add .agents modular rules with manual trigger and .agent symlink (#78)" (#79)
This reverts commit 1855815aeb.
2026-09-17 10:17:40 +08:00
yunyingk 1855815aeb feat(agents): add .agents modular rules with manual trigger and .agent symlink (#78)
- Match seal-use repository layout with .agents/rules and skills.json
- Create symlink .agent -> .agents for backward and naming compatibility
- Configure trigger: 'manual' on all rules to avoid prompt bloat
- Add production-safety.md, tenant-and-credential.md, cli-protocol.md, testing-and-dev-hygiene.md, typescript-style.md
- Remove .agents/ ignore from .gitignore to track rules in git
2026-09-17 10:13:55 +08:00
56 changed files with 1734 additions and 697 deletions

No files matched your search

+60
View File
@@ -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).
+26
View File
@@ -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()`,应抛出带有结构化语义的错误,由外层统一捕获和分配退出码。
+27
View File
@@ -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 默认输出必须进行严格掩码脱敏。
+24
View File
@@ -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`。
+31
View File
@@ -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`)。
+31
View File
@@ -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.
+16
View File
@@ -0,0 +1,16 @@
{
"entries": [
{
"path": "~/.agents/skills",
"exclude": [
"^\\..*",
".*-(deprecated|draft|backup|bak|old|test|tmp)$",
"^lark.*",
"^dingtalk.*",
"^dws.*",
"^seal.*",
"^yingqing.*"
]
}
]
}
-2
View File
@@ -46,5 +46,3 @@ data/
# Local roadmaps & scratch notes
*.local.md
.agents/
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.8.7",
"version": "0.8.8",
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
"author": {
"name": "yingqing"
+3 -1
View File
@@ -1,4 +1,4 @@
# hose-use (v0.8.7)
# hose-use (v0.8.8)
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
@@ -70,6 +70,8 @@ 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 查询单据结构化详情
+507 -487
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "hose-use API & MCP Tools Specification",
"version": "0.8.7",
"version": "0.8.8",
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
},
"servers": [
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: hose-use API & MCP Tools Specification
version: 0.8.7
version: 0.8.8
description: >-
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
servers:
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.8.7",
"version": "0.8.8",
"module": "src/server.ts",
"type": "module",
"bin": {
+22 -4
View File
@@ -2,11 +2,11 @@
name: hose-use
description: "合思/易快报(Ekuaibao)企业级 SaaS 一站式能力:hose-use CLI/SDK 多账号登录、租户切换、单据检索与审批动作、自建应用与工作流扫描、密钥与应用中心、常驻守护进程与 HTTP 文档/OpenAPI,以及工作流 MVEL 代码节点脚本生成调试、节点批量开通。用于一切合思/易快报相关请求。"
metadata:
version: 0.8.7
version: 0.8.8
short-description: 合思/易快报 企业级 CLI 与工作流 skill 套件(含 MVEL 代码节点)
---
# hose-use (v0.8.7)
# hose-use (v0.8.8)
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
@@ -38,6 +38,20 @@ metadata:
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`)。
---
@@ -54,7 +68,7 @@ metadata:
| 第三方免密/协助链接一键秒级导入 | `hose-use corps add-link <url>`, `hose-use auth add-link <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) |
@@ -115,7 +129,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 # 精准查询单据详情 (中文字段映射)
+23 -7
View File
@@ -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
```
---
+3 -3
View File
@@ -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,
@@ -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++) {
@@ -69,7 +69,7 @@ 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 };
};
+2 -2
View File
@@ -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();
+2 -2
View File
@@ -14,7 +14,7 @@ import {
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";
@@ -166,7 +166,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;
+32 -4
View File
@@ -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,
@@ -35,9 +35,9 @@ export async function handleBillCommand(
const action = parsed.action?.toLowerCase();
const corpId = corp.corpId || corp.id;
let client: Awaited<ReturnType<typeof createEkbClient>> | undefined;
let client: Awaited<ReturnType<typeof createSessionClient>> | undefined;
const getClient = async () => {
client ??= await createEkbClient(corp);
client ??= await createSessionClient(corp);
return client;
};
@@ -164,16 +164,33 @@ export async function handleBillCommand(
const code = stringOption(parsed.options, ["code", "c"]);
const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"]);
const searchFields = stringOption(parsed.options, ["search-fields", "searchFields", "search-field", "sf"]);
const stage = stringOption(parsed.options, ["stage"]);
const state = stringOption(parsed.options, ["state", "s"]);
const count = numberOption(parsed.options, ["count", "limit", "n"], 20);
const since = stringOption(parsed.options, ["since", "days", "d"]);
const startDate = stringOption(parsed.options, ["start-date", "startDate", "from", "start"]);
const endDate = stringOption(parsed.options, ["end-date", "endDate", "to", "end"]);
const rawOrder = stringOption(parsed.options, ["order", "sort", "direction"]);
const order = rawOrder && /asc/i.test(rawOrder) ? "ASC" : "DESC";
const filterBy = stringOption(parsed.options, ["filter-by", "filterBy", "filter"]);
const select = stringOption(parsed.options, ["select", "fields"]);
const distinct = booleanOption(parsed.options, ["distinct"]);
const result = await searchAndFormatBills(await getClient(), corpId, {
code,
keyword,
searchFields,
stage,
state,
count,
since,
startDate,
endDate,
order,
filterBy,
select,
distinct,
});
if (runtime.jsonMode) {
@@ -204,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 {
+2 -2
View File
@@ -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");
});
+2 -2
View File
@@ -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)) {
+3 -3
View File
@@ -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,
@@ -68,9 +68,9 @@ export async function handleFeeTypeCommand(
const corpId = corp.corpId || corp.id;
const action = (parsed.action?.toLowerCase() || "list").trim();
let client: Awaited<ReturnType<typeof createEkbClient>> | undefined;
let client: Awaited<ReturnType<typeof createSessionClient>> | undefined;
const getClient = async () => {
client ??= await createEkbClient(corp);
client ??= await createSessionClient(corp);
return client;
};
+5 -5
View File
@@ -1,7 +1,7 @@
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";
@@ -30,7 +30,7 @@ export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRu
const corpId = corp.corpId || corp.id;
if (action === "count" || action === "unread") {
const client = await createEkbClient(corp);
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 };
@@ -43,7 +43,7 @@ export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRu
return mutationPreview(parsed, runtime, "标记消息为已读", messageId, { read: true });
}
requireMutationConfirmation(parsed, runtime, "标记消息为已读", `hose-use message read ${messageId} --yes`);
const client = await createEkbClient(corp);
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 };
@@ -54,7 +54,7 @@ export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRu
return mutationPreview(parsed, runtime, "批量标记未读消息为已读", `corp:${corpId}`, { read: true, allUnread: true });
}
requireMutationConfirmation(parsed, runtime, "批量标记未读消息为已读", "hose-use message read-all --yes");
const client = await createEkbClient(corp);
const client = await createSessionClient(corp);
const ids: string[] = [];
let start = 0;
let total = 0;
@@ -74,7 +74,7 @@ export async function handleMessageCommand(parsed: CliParsedArgs, runtime: CliRu
return { stdout: "", stderr: `未知消息子命令: ${action}。支持: list, count, read <messageId>, read-all\n`, exitCode: 1 };
}
const client = await createEkbClient(corp);
const client = await createSessionClient(corp);
const read = booleanOption(parsed.options, ["read"]);
const unread = booleanOption(parsed.options, ["unread"]);
+2 -2
View File
@@ -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 ? "启用" : "停用"]);
+6 -7
View File
@@ -1,5 +1,4 @@
import { createEkbClient } from "../../core/auth/ekb.js";
import { getEasoClient } from "../../core/auth/easo.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";
@@ -32,10 +31,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 +53,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,
+2 -2
View File
@@ -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];
+2 -2
View File
@@ -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);
+2 -2
View File
@@ -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 };
+15 -9
View File
@@ -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(
@@ -60,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,
+1
View File
@@ -195,6 +195,7 @@ export function printHelp(target: string[] = []): 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 # 二级解析提交人、部门、法人实体与费用类型引用
+10 -7
View File
@@ -6,15 +6,20 @@ Core 层负责基础设施:企业配置管理、认证 Token 获取与缓存
```text
src/core/
├── auth/ # 登录认证与 Token 获取、刷新、缓存
├── auth/ # 登录认证协议与凭证存储(纯凭据层)
│ ├── login.ts # 登录四矩阵(RSA账密登录、短信验证码、F12/cURL凭证导入、浏览器同步)
│ ├── account-store.ts # 多账号持久化存储 (~/.cache/ekb-mcp/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 与历史路径)
│ └── types.ts
├── http/ # 统一 HTTP 客户端装配与网络传输(语义化客户端)
│ ├── factory.ts # Ky 底层客户端工厂(超时、重试、错误钩子)
│ ├── fingerprint.ts # 统一浏览器指纹、User-Agent、Cookie 与 WAF 策略头
│ ├── session-client.ts # 闭合用户会话客户端(三 Header + 指纹 + 401 续杯)
│ ├── openapi-client.ts # 开放平台应用客户端(appKey 换票与签名机制)
│ ├── unity-client.ts # 应用中心与动态集群寻址客户端
│ ├── 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/` 提供的多级缓存门面
-40
View File
@@ -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 重新导入"),
}),
});
}
+1 -1
View File
@@ -5,7 +5,7 @@ import { join } from "node:path";
import { AuthenticationError } from "../errors.js";
import { CorpConfig } from "../config/types.js";
import { saveCorpConfig, saveMultipleCorpConfigs, resolveWritableEnterprisesDir } from "../config/loader.js";
import { resolveCorpCluster } from "./easo.js";
import { resolveCorpCluster } from "../http/unity-client.js";
import {
saveAccount,
getAccount,
+2 -2
View File
@@ -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;
+112
View File
@@ -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();
});
});
+48
View File
@@ -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;
}
+52
View File
@@ -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";
+133
View File
@@ -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);
},
});
}
@@ -1,6 +1,6 @@
import { describe, expect, it } from "bun:test";
import { canRefreshCorpAccessToken, resolveLinkExpiresAt } from "./login.js";
import { createEkbClient } from "./ekb.js";
import { canRefreshCorpAccessToken, resolveLinkExpiresAt } from "../auth/login.js";
import { createSessionClient } from "./session-client.js";
import type { CorpConfig } from "../config/types.js";
function corp(overrides: Partial<CorpConfig> = {}): CorpConfig {
@@ -14,7 +14,7 @@ function corp(overrides: Partial<CorpConfig> = {}): CorpConfig {
};
}
describe("core/auth/ekb refresh policy", () => {
describe("core/http/session-client 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);
@@ -32,7 +32,7 @@ describe("core/auth/ekb refresh policy", () => {
}) as unknown as typeof fetch;
try {
const client = await createEkbClient(corp());
const client = await createSessionClient(corp());
await expect(client.get("api/test")).rejects.toThrow("临时凭证已过期,请使用 hose-use corps add-link 重新导入");
expect(calls).toBe(1);
} finally {
+72
View File
@@ -0,0 +1,72 @@
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 && 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: () => 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,15 @@
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";
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 +41,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 +84,7 @@ export async function fetchUnityJwt(
return token;
}
async function fetchEasoRealmToken(
export async function fetchEasoRealmToken(
corpId: string,
unityJwt: string,
hoseToken: string
@@ -102,6 +105,9 @@ async function fetchEasoRealmToken(
return token;
}
/**
* 获取 EASO 授权客户端 (用于请求 EASO 体系资源)
*/
export async function getEasoClient(corp: CorpConfig): Promise<{
client: ReturnType<typeof createAuthClient>;
}> {
@@ -174,6 +180,10 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
};
}
/**
* 获取 Unity 应用中心与开放微服务集群客户端 (Unity Client)
* 适用于应用商店、已购应用查询等场景
*/
export async function getUnityClient(corp: CorpConfig): Promise<{
client: ReturnType<typeof createAuthClient>;
unityJwt: string;
@@ -227,4 +237,3 @@ export async function getUnityClient(corp: CorpConfig): Promise<{
}),
};
}
+7 -1
View File
@@ -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 -9
View File
@@ -310,20 +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; timeout?: number | false } = {}
options: RawBillSearchOptions = {}
): Promise<RawBillSearchResponse> {
const response = await client.post("api/v2/invoice/search", {
searchParams: { corporationId: corpId, corpId },
timeout: options.timeout ?? 30000,
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();
+175 -1
View File
@@ -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"]);
});
});
});
+143 -12
View File
@@ -50,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 字典 ───────────────────────────────────────────────
@@ -1140,23 +1140,137 @@ 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 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 ?? 50,
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` +
`建议:\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 <单号>`
@@ -1207,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;
});
@@ -1231,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,
@@ -1270,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 {
@@ -1295,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,
+13
View File
@@ -98,10 +98,23 @@ export interface BillQueryParams {
code?: string;
id?: string;
keyword?: string;
searchFields?: string[] | string;
stage?: string;
state?: string;
start?: number;
count?: number;
since?: string;
from?: number;
to?: number;
startDate?: string;
endDate?: string;
active?: boolean;
order?: "ASC" | "DESC" | "asc" | "desc";
orderBy?: Array<{ value: string; order: "ASC" | "DESC" }>;
filterBy?: string;
select?: string;
distinct?: boolean;
join?: string | string[];
}
export interface BillFlowEntry {
+1 -1
View File
@@ -1,5 +1,5 @@
import { z } from "zod";
import { getEasoClient } from "../../core/auth/easo.js";
import { getEasoClient } from "../../core/http/unity-client.js";
import type { CorpConfig } from "../../core/config/types.js";
import { fetchStaffs } from "./api.js";
import type { ContactListResult, ContactSearchOptions, Staff } from "./types.js";
+1 -1
View File
@@ -63,7 +63,7 @@ export const dimensionTools = [
const corp = corpContext.getCurrent();
if (!corp) throw new Error("未配置活跃企业上下文");
const items = await searchDimensions(
await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp)),
await import("../../core/http/session-client.js").then((m) => m.createSessionClient(corp)),
corp.corpId || corp.id,
{ name: params.keyword }
);
+1 -1
View File
@@ -17,7 +17,7 @@ domains/feetype/tools.ts (业务编排:树展开、路径计算、字段规
domains/feetype/api.ts (HTTP 传输层:直连 /api/v1/form/feeTypes 与 /api/form/v2/specifications)
│
▼
core/auth/ekb.ts (企业身份认证与凭证管理)
core/http/session-client.ts (企业会话客户端与凭证注入)
```
## 接口路由映射
+4 -4
View File
@@ -1,4 +1,4 @@
import { createEkbClient } from "../../core/auth/ekb.js";
import { createSessionClient } from "../../core/http/session-client.js";
import type { CorpConfig } from "../../core/config/types.js";
import {
fetchDesktopMenuTree,
@@ -11,7 +11,7 @@ import type { MenuItem, WorkbenchApp } from "./types.js";
export async function fetchWorkbenchAppsList(
corp: CorpConfig
): Promise<WorkbenchApp[]> {
const client = await createEkbClient(corp);
const client = await createSessionClient(corp);
const corpId = corp.corpId || corp.credentials.corpId;
return fetchWorkbenchApps(client, corpId);
}
@@ -20,7 +20,7 @@ export async function fetchWorkbenchAppsList(
export async function fetchDesktopMenus(
corp: CorpConfig
): Promise<MenuItem[]> {
const client = await createEkbClient(corp);
const client = await createSessionClient(corp);
const corpId = corp.corpId || corp.credentials.corpId;
return fetchDesktopMenuTree(client, corpId);
}
@@ -29,7 +29,7 @@ export async function fetchDesktopMenus(
export async function fetchAppCenterSubMenus(
corp: CorpConfig
): Promise<MenuItem[]> {
const client = await createEkbClient(corp);
const client = await createSessionClient(corp);
const corpId = corp.corpId || corp.credentials.corpId;
return fetchAppCenterMenus(client, corpId);
}
+1 -1
View File
@@ -10,7 +10,7 @@ export const permissionTools = [{
parameters: z.object({}),
handler: async ({ corpContext }: any) => {
const corp = corpContext.getCurrent(); if (!corp) throw new Error("未配置活跃企业上下文");
const client = await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp));
const client = await import("../../core/http/session-client.js").then((m) => m.createSessionClient(corp));
return getPermissions(client, corp.corpId || corp.id);
},
}];
+1 -1
View File
@@ -73,7 +73,7 @@ export const roleTools = [
handler: async ({ corpContext }: any, params: { keyword?: string; count?: number }) => {
const corp = corpContext.getCurrent();
if (!corp) throw new Error("未配置活跃企业上下文");
const client = await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp));
const client = await import("../../core/http/session-client.js").then((m) => m.createSessionClient(corp));
const roles = await searchRoles(client, corp.corpId || corp.id, { keyword: params.keyword });
return { count: roles.length, roles: roles.slice(0, params.count ?? 100) };
},
+5 -6
View File
@@ -1,5 +1,4 @@
import { createEkbClient } from "../../core/auth/ekb.js";
import { getUnityClient } from "../../core/auth/easo.js";
import { createSessionClient, getUnityClient } from "../../core/http/index.js";
import type { CorpConfig } from "../../core/config/types.js";
import {
listOpenApiKeys,
@@ -17,15 +16,15 @@ import type {
} from "./types.js";
export async function fetchOpenApiKeys(corp: CorpConfig): Promise<OpenApiKey[]> {
const ekbClient = await createEkbClient(corp);
const sessionClient = await createSessionClient(corp);
const corpId = corp.corpId || corp.credentials.corpId;
return listOpenApiKeys(ekbClient, corpId);
return listOpenApiKeys(sessionClient, corpId);
}
export async function fetchOpenConfig(corp: CorpConfig): Promise<OpenConfig> {
const ekbClient = await createEkbClient(corp);
const sessionClient = await createSessionClient(corp);
const corpId = corp.corpId || corp.credentials.corpId;
return getOpenConfig(ekbClient, corpId);
return getOpenConfig(sessionClient, corpId);
}
export async function fetchClientGoods(
+6 -7
View File
@@ -5,8 +5,7 @@ import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { loadCorpConfigs } from "./core/config/loader.js";
import { CorpContext } from "./core/config/manager.js";
import { createEkbClient } from "./core/auth/ekb.js";
import { getEasoClient } from "./core/auth/easo.js";
import { createSessionClient, getUnityClient } from "./core/http/index.js";
import { AuthenticationError, EkbError, NotLoggedInError } from "./core/errors.js";
import { authTools } from "./core/auth/tools.js";
import { platformTools } from "./domains/platform/tools.js";
@@ -344,10 +343,10 @@ export function createServer(options: { mode?: HoseMcpMode; enabled?: boolean }
isError: true,
};
}
const ekbClient = await createEkbClient(currentCorp);
const { client: easoClient } = await getEasoClient(currentCorp);
const sessionClient = await createSessionClient(currentCorp);
const { client: unityClient } = await getUnityClient(currentCorp);
const result = await platformTool.handler(
{ corp: currentCorp, ekbClient, easoClient },
{ corp: currentCorp, ekbClient: sessionClient, easoClient: unityClient },
parsed.data as never
);
return {
@@ -370,9 +369,9 @@ export function createServer(options: { mode?: HoseMcpMode; enabled?: boolean }
isError: true,
};
}
const ekbClient = await createEkbClient(currentCorp);
const sessionClient = await createSessionClient(currentCorp);
const result = await datalinkTool.handler(
{ corp: currentCorp, ekbClient },
{ corp: currentCorp, ekbClient: sessionClient },
parsed.data as never
);
return {