Compare commits

...
13 Commits
Author SHA1 Message Date
gitea 68d570022d feat: release v0.5.2 with protected contact domain and bill web link
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 15:58:20 +08:00
gitea 188a0fb5dc feat: release v0.5.1 with multi-file skill system and IDE plugin manifest
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 15:32:01 +08:00
gitea c1dc9f1616 feat: release v0.5.0 with embedded HTTP server and resident daemon service
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 15:19:12 +08:00
gitea 07b4e14e59 fix(test): 增强 server.test.ts 在无凭证全新 CI 容器环境下的兼容断言
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 11:41:10 +08:00
gitea ba30c1a6cb feat(cli): 支持大输出防爆保护、本地文件转储与敏感凭证全链路脱敏并发布 v0.4.2
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 11:40:32 +08:00
gitea cf44c7dcdf feat(config): 支持多层级企业配置发现、读写分离安全落盘与路径诊断并发布 v0.4.1
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 11:34:29 +08:00
gitea 9e20caf4a3 feat(mcp): 引入 MCP 单工具网关模式 (hose_cli) 与并发流调度并发布 v0.4.0
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 11:28:41 +08:00
gitea 4f510efc1b feat(auth): 支持代客协助平台凭证智能识别、Token过期感知与单据字典增强并发布 v0.3.1
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-03 11:08:47 +08:00
gitea 5cf6c9e014 feat(bill): 引入费控单据与费用明细检索(支持按单号精准查询与 DataLink 字典自动还原)并发布 v0.3.0
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-08-27 11:48:20 +08:00
gitea 0372698ff9 ci: 添加 openapi:all 构建步骤并集成 GitHub 与 Gitea 自动双发布
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-08-27 11:33:45 +08:00
gitea b13959451a feat(openapi): 引入双层 OpenAPI 规范管理 (原始下游 & 包装层工具) 并升级版本至 v0.2.2
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-08-27 11:29:32 +08:00
gitea 2dfcf67b00 feat(update): 实现多镜像源自更新机制 (update/upgrade) 并升级版本至 v0.2.1
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-08-27 11:19:13 +08:00
gitea 6e73de697b docs: 更新仓库名称与一键安装链接至 yunyingk/hose-use 2026-08-27 11:10:06 +08:00
79 changed files with 10192 additions and 230 deletions

No files matched your search

+61
View File
@@ -25,9 +25,15 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Generate & bundle OpenAPI
run: bun run openapi:all
- name: Type-check
run: bun run check
- name: Test
run: bun test
- name: Compile multi-target binaries
run: |
mkdir -p dist/bin
@@ -54,3 +60,58 @@ jobs:
gh release view "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1 || gh release create "${GITHUB_REF_NAME}" --repo "${GITHUB_REPOSITORY}" --title "${GITHUB_REF_NAME}" --generate-notes
fi
gh release upload "${GITHUB_REF_NAME}" dist/bin/hose-use-* --repo "${GITHUB_REPOSITORY}" --clobber
- name: Publish Gitea Release
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_HOST: "https://git.ying-qing.cn"
GITEA_REPO: "gitea/hose-use"
run: |
if [ -z "$GITEA_TOKEN" ]; then
echo "::notice::GITEA_TOKEN secret not configured, skipping Gitea upload."
exit 0
fi
TAG_NAME="${GITHUB_REF_NAME}"
TAG_MSG=$(git tag -l --format='%(contents)' "${TAG_NAME}" | sed '/^$/d')
NOTES="${TAG_MSG:-Automated release for ${TAG_NAME}}"
echo "==> Creating release on Gitea for ${TAG_NAME}..."
RELEASE_RESP=$(curl -s -X POST "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases" \
-H "Authorization: token ${GITEA_TOKEN}" \
-H "Content-Type: application/json" \
-d "{\"tag_name\":\"${TAG_NAME}\",\"name\":\"${TAG_NAME}\",\"body\":$(echo "$NOTES" | jq -Rsa .),\"draft\":false,\"prerelease\":false}")
RELEASE_ID=$(echo "$RELEASE_RESP" | jq -r '.id // empty')
if [ -z "$RELEASE_ID" ]; then
RELEASE_ID=$(curl -s -H "Authorization: token ${GITEA_TOKEN}" "${GITEA_HOST}/api/v1/repos/${GITEA_REPO}/releases/tags/${TAG_NAME}" | jq -r '.id // empty')
fi
if [ -z "$RELEASE_ID" ]; then
echo "::warning::Failed to create or find Gitea release ID. Response: $RELEASE_RESP"
exit 0
fi
echo "==> Uploading assets to Gitea release ID ${RELEASE_ID}..."
upload_asset() {
local file="$1"
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}" \
-H "Authorization: token ${GITEA_TOKEN}" \
-F "attachment=@${file}")
STATUS=$(echo "$RESP" | tail -n 1)
echo " [done] ${filename} -> ${STATUS}"
}
pids=()
for file in dist/bin/hose-use-*; do
upload_asset "$file" &
pids+=($!)
done
for pid in "${pids[@]}"; do
wait "$pid" || true
done
echo "✓ Successfully published release assets to Gitea!"
+4 -4
View File
@@ -3,7 +3,8 @@ node_modules
# output
out
dist
dist/bin/
dist/hose-use-*
*.tgz
# code coverage
@@ -43,6 +44,5 @@ data/
*.db
*.sqlite
# 环境变量
.env
.env.local
# Local roadmaps & scratch notes
*.local.md
+15
View File
@@ -0,0 +1,15 @@
{
"mcpServers": {
"hose-use": {
"type": "stdio",
"command": "node",
"args": [
"${CLAUDE_PLUGIN_ROOT}/dist/mcp/server.js"
],
"env": {
"HOSE_USE_MCP_ENABLED": "${user_config.enable_mcp}"
},
"timeoutMs": 120000
}
}
}
+19
View File
@@ -0,0 +1,19 @@
{
"name": "hose-use",
"version": "0.5.2",
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
"author": {
"name": "yingqing"
},
"license": "MIT",
"skills": "skills",
"mcpServers": "./.mcp.json",
"userConfig": {
"enable_mcp": {
"type": "boolean",
"title": "启用 MCP 服务",
"description": "开启后向 Agent 暴露 hose_cli 单工具网关;默认关闭。保存后重新连接该插件的 MCP 服务。",
"default": false
}
}
}
+44 -5
View File
@@ -1,4 +1,4 @@
# hose-use (v0.2.0)
# hose-use (v0.5.2)
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
@@ -7,7 +7,7 @@
### 方式一:一键脚本安装独立二进制(推荐)
```bash
curl -fsSL https://raw.githubusercontent.com/yunyingk/hose-serve-tool/main/scripts/install.sh | bash
curl -fsSL https://raw.githubusercontent.com/yunyingk/hose-use/main/scripts/install.sh | bash
```
### 方式二:本地 Bun 源码开发
@@ -32,8 +32,9 @@ hose-use corps list # 列出名下所有已配置企
hose-use corps switch <corpId> # 切换工作企业
hose-use corps current # 查看当前激活企业
# 3. 运行模式管理 (有状态 vs 无状态)
hose-use config show # 查看当前运行模式
# 3. 运行模式与多级配置路径管理 (有状态 vs 无状态)
hose-use config show # 查看当前运行模式与默认企业
hose-use config paths # 查看多级企业目录发现链与配置文件位置
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
hose-use config mode stateful # 切换为有状态模式 (记忆默认企业)
@@ -44,11 +45,49 @@ hose-use workflow find --task=code-js2 # 搜索包含特定节点类型
hose-use workflow toggle <pipelineId> --state=1 # 启用/停用工作流
hose-use platform list # 查看企业下所有启用的自建应用
# 5. Agent Skill 与连通性诊断
# 5. 单据与费用明细管理 (DataLink 字典自动还原 & 200KB 防爆拦截)
hose-use bill list # 查看当前企业单据与报销列表 (支持分页/阶段/状态过滤)
hose-use bill list --json -o /tmp/bills.json # 自动转储大报文至本地文件,防止打爆上下文
hose-use bill list --json --full # 确需完整原始数据时跳过 200KB 限制
hose-use bill get <单号|ID> # 根据单号或 ID 查询单据结构化详情
hose-use bill schema # 查看企业全部单据实体与数据模型字典
# 6. OpenAPI 规范导出 (原始下游契约 & 包装层工具规范)
hose-use openapi paths # 查看包装层 API 路径与概要一览
hose-use openapi --raw paths # 查看合思原生下游全量 API 路径
hose-use openapi info # 查看 OpenAPI 规范元数据概览
hose-use openapi # 输出包装层标准 OpenAPI 3.1.0 JSON
hose-use openapi --raw # 输出原生下游全量 OpenAPI 3.1.0 JSON
# 7. 内置 HTTP Server 与常驻 Service 守护进程
hose-use http --port=8888 # 前台启动 HTTP 服务与 Scalar 交互式文档 (http://localhost:8888/docs)
hose-use service start # 后台启动常驻守护进程
hose-use service status # 查看常驻服务运行状态、PID 与接口端点
hose-use service logs # 查看守护进程日志
hose-use service stop # 优雅停止常驻守护进程
# 8. Agent Skill 与连通性诊断
hose-use skill install # 一键将 Agent Skill 安装到 ~/.agents/skills/
hose-use probe # 诊断当前企业主站 Session、EASO 握手与接口连通性
# 9. MCP Server (单工具网关模式)
hose-use mcp # 启动 MCP Server (默认暴露 hose_cli 单工具网关)
```
### AI 智能体与 MCP 单工具网关 (`hose_cli`)
`hose-use` 采用 **单工具网关架构 (Single-Gate Pattern)**。在 MCP 环境下默认仅暴露一个 `hose_cli` 工具,接收 `command` 字符串:
- 避免数十个业务工具占用大量 Prompt Tokens;
- 业务语义完全收敛在 `skills/hose-use/SKILL.md` 与 `references/` 专卷中,Agent 按需学习;
- 内部同进程调用 CLI 分发层,零子进程开销;
- 若需要传统细粒度工具,可通过环境变量 `HOSE_MCP_MODE=all` 开启兼容模式。
### 模块化 Agent Skill 与 IDE 插件规范
- **多文件 Skill 模块体系**:知识体系划分至 `references/auth.md`、`references/bill.md`、`references/workflow.md`、`references/service.md`,执行 `hose-use skill install` 自动递归安装并支持环境自愈;
- **原生 IDE 插件规范支持**:内嵌 `.zcode-plugin/plugin.json` 与 `.mcp.json` 清单,支持标准 IDE 插件市场/本地插件直接载入,并在设置界面支持可视化切换 MCP 开关;
- **MCP 单文件产物**:支持通过 `bun run build:plugin` 快速编译 Node.js 兼容的轻量单文件 `dist/mcp/server.js`。
## 架构
```text
+3
View File
@@ -7,6 +7,7 @@
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"ky": "^2.0.2",
"yaml": "^2.9.0",
"zod": "^4.4.3",
},
"devDependencies": {
@@ -206,6 +207,8 @@
"wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
"yaml": ["yaml@2.9.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="],
"zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],
"zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
+635
View File
@@ -0,0 +1,635 @@
import{createRequire as LN}from"node:module";var JN=Object.create;var{getPrototypeOf:XN,defineProperty:F0,getOwnPropertyNames:ON}=Object;var jN=Object.prototype.hasOwnProperty;function AN($){return this[$]}var GN,QN,CJ=($,i,v)=>{var u=$!=null&&typeof $==="object";if(u){var n=i?GN??=new WeakMap:QN??=new WeakMap,b=n.get($);if(b)return b}v=$!=null?JN(XN($)):{};let I=i||!$||!$.__esModule?F0(v,"default",{value:$,enumerable:!0}):v;for(let U of ON($))if(!jN.call(I,U))F0(I,U,{get:AN.bind($,U),enumerable:!0});if(u)n.set($,I);return I};var S=($,i)=>()=>(i||$((i={exports:{}}).exports,i),i.exports);var YN=($)=>$;function NN($,i){this[$]=YN.bind(null,i)}var Gi=($,i)=>{for(var v in i)F0($,v,{get:i[v],enumerable:!0,configurable:!0,set:NN.bind(i,v)})};var _J=LN(import.meta.url);var l4=S((jO)=>{Object.defineProperty(jO,"__esModule",{value:!0});jO.regexpCode=jO.getEsmExportName=jO.getProperty=jO.safeStringify=jO.stringify=jO.strConcat=jO.addCodeArg=jO.str=jO._=jO.nil=jO._Code=jO.Name=jO.IDENTIFIER=jO._CodeOrName=void 0;class Gb{}jO._CodeOrName=Gb;jO.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class gv extends Gb{constructor($){super();if(!jO.IDENTIFIER.test($))throw Error("CodeGen: name must be a valid identifier");this.str=$}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}jO.Name=gv;class ii extends Gb{constructor($){super();this._items=typeof $==="string"?[$]:$}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let $=this._items[0];return $===""||$==='""'}get str(){var $;return($=this._str)!==null&&$!==void 0?$:this._str=this._items.reduce((i,v)=>`${i}${v}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((i,v)=>{if(v instanceof gv)i[v.str]=(i[v.str]||0)+1;return i},{})}}jO._Code=ii;jO.nil=new ii("");function XO($,...i){let v=[$[0]],u=0;while(u<i.length)Cg(v,i[u]),v.push($[++u]);return new ii(v)}jO._=XO;var Rg=new ii("+");function OO($,...i){let v=[T4($[0])],u=0;while(u<i.length)v.push(Rg),Cg(v,i[u]),v.push(Rg,T4($[++u]));return fL(v),new ii(v)}jO.str=OO;function Cg($,i){if(i instanceof ii)$.push(...i._items);else if(i instanceof gv)$.push(i);else $.push(cL(i))}jO.addCodeArg=Cg;function fL($){let i=1;while(i<$.length-1){if($[i]===Rg){let v=xL($[i-1],$[i+1]);if(v!==void 0){$.splice(i-1,3,v);continue}$[i++]="+"}i++}}function xL($,i){if(i==='""')return $;if($==='""')return i;if(typeof $=="string"){if(i instanceof gv||$[$.length-1]!=='"')return;if(typeof i!="string")return`${$.slice(0,-1)}${i}"`;if(i[0]==='"')return $.slice(0,-1)+i.slice(1);return}if(typeof i=="string"&&i[0]==='"'&&!($ instanceof gv))return`"${$}${i.slice(1)}`;return}function yL($,i){return i.emptyStr()?$:$.emptyStr()?i:OO`${$}${i}`}jO.strConcat=yL;function cL($){return typeof $=="number"||typeof $=="boolean"||$===null?$:T4(Array.isArray($)?$.join(","):$)}function hL($){return new ii(T4($))}jO.stringify=hL;function T4($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}jO.safeStringify=T4;function mL($){return typeof $=="string"&&jO.IDENTIFIER.test($)?new ii(`.${$}`):XO`[${$}]`}jO.getProperty=mL;function oL($){if(typeof $=="string"&&jO.IDENTIFIER.test($))return new ii(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}jO.getEsmExportName=oL;function dL($){return new ii($.toString())}jO.regexpCode=dL});var xg=S((YO)=>{Object.defineProperty(YO,"__esModule",{value:!0});YO.ValueScope=YO.ValueScopeName=YO.Scope=YO.varKinds=YO.UsedValueState=void 0;var C$=l4();class GO extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var Yb;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(Yb||(YO.UsedValueState=Yb={}));YO.varKinds={const:new C$.Name("const"),let:new C$.Name("let"),var:new C$.Name("var")};class rg{constructor({prefixes:$,parent:i}={}){this._names={},this._prefixes=$,this._parent=i}toName($){return $ instanceof C$.Name?$:this.name($)}name($){return new C$.Name(this._newName($))}_newName($){let i=this._names[$]||this._nameGroup($);return`${$}${i.index++}`}_nameGroup($){var i,v;if(((v=(i=this._parent)===null||i===void 0?void 0:i._prefixes)===null||v===void 0?void 0:v.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}YO.Scope=rg;class fg extends C$.Name{constructor($,i){super(i);this.prefix=$}setValue($,{property:i,itemIndex:v}){this.value=$,this.scopePath=C$._`.${new C$.Name(i)}[${v}]`}}YO.ValueScopeName=fg;var DK=C$._`\n`;class QO extends rg{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?DK:C$.nil}}get(){return this._scope}name($){return new fg($,this._newName($))}value($,i){var v;if(i.ref===void 0)throw Error("CodeGen: ref must be passed in value");let u=this.toName($),{prefix:n}=u,b=(v=i.key)!==null&&v!==void 0?v:i.ref,I=this._values[n];if(I){let w=I.get(b);if(w)return w}else I=this._values[n]=newLine truncated
`:""},this._extScope=$,this._scope=new ni.Scope({parent:$}),this._nodes=[new BO]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,i){let v=this._extScope.value($,i);return(this._values[v.prefix]||(this._values[v.prefix]=new Set)).add(v),v}getScopeValue($,i){return this._extScope.getValue($,i)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,i,v,u){let n=this._scope.toName(i);if(v!==void 0&&u)this._constants[n.str]=v;return this._leafNode(new LO($,n,v)),n}const($,i,v){return this._def(ni.varKinds.const,$,i,v)}let($,i,v){return this._def(ni.varKinds.let,$,i,v)}var($,i,v){return this._def(ni.varKinds.var,$,i,v)}assign($,i,v){return this._leafNode(new hg($,i,v))}add($,i){return this._leafNode(new KO($,_$.operators.ADD,i))}code($){if(typeof $=="function")$();else if($!==d.nil)this._leafNode(new FO($));return this}object(...$){let i=["{"];for(let[v,u]of $){if(i.length>1)i.push(",");if(i.push(v),v!==u||this.opts.es5)i.push(":"),(0,d.addCodeArg)(i,u)}return i.push("}"),new d._Code(i)}if($,i,v){if(this._blockNode(new Ki($)),i&&v)this.code(i).else().code(v).endIf();else if(i)this.code(i).endIf();else if(v)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new Ki($))}else(){return this._elseNode(new E4)}endIf(){return this._endBlockNode(Ki,E4)}_for($,i){if(this._blockNode($),i)this.code(i).endFor();return this}for($,i){return this._for(new SO($),i)}forRange($,i,v,u,n=this.opts.es5?ni.varKinds.var:ni.varKinds.let){let b=this._scope.toName($);return this._for(new ZO(n,b,i,v),()=>u(b))}forOf($,i,v,u=ni.varKinds.const){let n=this._scope.toName($);if(this.opts.es5){let b=i instanceof d.Name?i:this.var("_arr",i);return this.forRange("_i",0,d._`${b}.length`,(I)=>{this.var(n,d._`${b}[${I}]`),v(n)})}return this._for(new yg("of",u,n,i),()=>v(n))}forIn($,i,v,u=this.opts.es5?ni.varKinds.var:ni.varKinds.const){if(this.opts.ownProperties)return this.forOf($,d._`Object.keys(${i})`,v);let n=this._scope.toName($);return this._for(new yg("in",u,n,i),()=>v(n))}endFor(){return this._endBlockNode(Wv)}label($){return this._leafNode(new zO($))}break($){return this._leafNode(new HO($))}return($){let i=new Lb;if(this._blockNode(i),this.code($),i.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(Lb)}try($,i,v){if(!i&&!v)throw Error('CodeGen: "try" without "catch" and "finally"');let u=new VO;if(this._blockNode(u),this.code($),i){let n=this.name("e");this._currNode=u.catch=new Kb(n),i(n)}if(v)this._currNode=u.finally=new zb,this.code(v);return this._endBlockNode(Kb,zb)}throw($){return this._leafNode(new PO($))}block($,i){if(this._blockStarts.push(this._nodes.length),$)this.code($).endBlock(i);return this}endBlock($){let i=this._blockStarts.pop();if(i===void 0)throw Error("CodeGen: not in self-balancing block");let v=this._nodes.length-i;if(v<0||$!==void 0&&v!==$)throw Error(`CodeGen: wrong number of nodes: ${v} vs ${$} expected`);return this._nodes.length=i,this}func($,i=d.nil,v,u){if(this._blockNode(new Nb($,i,v)),u)this.code(u).endFunc();return this}endFunc(){return this._endBlockNode(Nb)}optimize($=1){while($-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,i){let v=this._currNode;if(v instanceof $||i&&v instanceof i)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${i?`${$.kind}/${i.kind}`:$.kind}"`)}_elseNode($){let i=this._currNode;if(!(i instanceof Ki))throw Error('CodeGen: "else" without "if"');return this._currNode=i.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let i=this._nodes;i[i.length-1]=$}}_$.CodeGen=qO;function Wn($,i){for(let v in i)$[v]=($[v]||0)+(i[v]||0);return $}function Hb($,i){return i instanceof d._CodeOrName?Wn($,i.names):$}function Jv($,i,v){if($ instanceof d.Name)return u($);if(!n($))return $;return new d._Code($._items.reduce((b,I)=>{if(I instanceof d.Name)I=u(I);if(I instanceof d._Code)b.push(...I._items);else b.push(I);return b},[]));function u(b){let I=v[b.str];if(I===void 0||i[b.str]!==1)return b;return delete i[b.str],I}function n(b){return b instanceof d._Code&&b._items.some((I)=>I instanceof d.Name&&i[I.str]===1&&v[I.str]!==void 0)}}function JK($,i){for(let v in i)$[v]=($[v]||0)-(i[v]||0)}function MO($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:d._`!${cg($)}`}_$.not=MO;var XK=kO(_$.operators.AND);function OK(...$){return $.reduce(XK)}_$.and=OK;var jK=kO(_$.operators.OR);function AK(...$){return $.reduce(jK)}_$.or=AK;function kO($){return(i,v)=>i===d.nil?v:v===d.nil?i:d._`${cg(i)} ${$} ${cg(v)}`}function cg($){return $ instanceof d.Name?$:d._`(${$})`}});var p=S((fO)=>{Object. Line truncated
|| (${I} == "string" && ${n} && ${n} == +${n})`).assign(U,x._`+${n}`);return;case"integer":u.elseIf(x._`${I} === "boolean" || ${n} === null
|| (${I} === "string" && ${n} && ${n} == +${n} && !(${n} % 1))`).assign(U,x._`+${n}`);return;case"boolean":u.elseIf(x._`${n} === "false" || ${n} === 0 || ${n} === null`).assign(U,!1).elseIf(x._`${n} === "true" || ${n} === 1`).assign(U,!0);return;case"null":u.elseIf(x._`${n} === "" || ${n} === 0 || ${n} === false`),u.assign(U,null);return;case"array":u.elseIf(x._`${I} === "string" || ${I} === "number"
|| ${I} === "boolean" || ${n} === null`).assign(U,x._`[${n}]`)}}}function Zz({gen:$,parentData:i,parentDataProperty:v},u){$.if(x._`${i} !== undefined`,()=>$.assign(x._`${i}[${v}]`,u))}function sg($,i,v,u=Xv.Correct){let n=u===Xv.Correct?x.operators.EQ:x.operators.NEQ,b;switch($){case"null":return x._`${i} ${n} null`;case"array":b=x._`Array.isArray(${i})`;break;case"object":b=x._`${i} && typeof ${i} == "object" && !Array.isArray(${i})`;break;case"integer":b=I(x._`!(${i} % 1) && !isNaN(${i})`);break;case"number":b=I();break;default:return x._`typeof ${i} ${n} ${$}`}return u===Xv.Correct?b:(0,x.not)(b);function I(U=x.nil){return(0,x.and)(x._`typeof ${i} == "number"`,U,v?x._`isFinite(${i})`:x.nil)}}wj.checkDataType=sg;function $W($,i,v,u){if($.length===1)return sg($[0],i,v,u);let n,b=(0,Ij.toHash)($);if(b.array&&b.object){let I=x._`typeof ${i} != "object"`;n=b.null?I:x._`!${i} || ${I}`,delete b.null,delete b.array,delete b.object}else n=x.nil;if(b.number)delete b.integer;for(let I in b)n=(0,x.and)(n,sg(I,i,v,u));return n}wj.checkDataTypes=$W;var Vz={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:i})=>typeof $=="string"?x._`{type: ${$}}`:x._`{type: ${i}}`};function iW($){let i=qz($);(0,Hz.reportError)(i,Vz)}wj.reportTypeError=iW;function qz($){let{gen:i,data:v,schema:u}=$,n=(0,Ij.schemaRefOrVal)($,u,"type");return{gen:i,keyword:"type",data:v,schema:u.type,schemaCode:n,schemaValue:n,parentSchema:u,params:{},it:$}}});var Oj=S((Jj)=>{Object.defineProperty(Jj,"__esModule",{value:!0});Jj.assignDefaults=void 0;var Ov=y(),Rz=p();function Cz($,i){let{properties:v,items:u}=$.schema;if(i==="object"&&v)for(let n in v)Wj($,n,v[n].default);else if(i==="array"&&Array.isArray(u))u.forEach((n,b)=>Wj($,b,n.default))}Jj.assignDefaults=Cz;function Wj($,i,v){let{gen:u,compositeRule:n,data:b,opts:I}=$;if(v===void 0)return;let U=Ov._`${b}${(0,Ov.getProperty)(i)}`;if(n){(0,Rz.checkStrictMode)($,`default is ignored for: ${U}`);return}let D=Ov._`${U} === undefined`;if(I.useDefaults==="empty")D=Ov._`${D} || ${U} === null || ${U} === ""`;u.if(D,Ov._`${U} = ${(0,Ov.stringify)(v)}`)}});var a$=S((Gj)=>{Object.defineProperty(Gj,"__esModule",{value:!0});Gj.validateUnion=Gj.validateArray=Gj.usePattern=Gj.callValidateCode=Gj.schemaProperties=Gj.allSchemaProperties=Gj.noPropertyInData=Gj.propertyInData=Gj.isOwnProperty=Gj.hasPropFunc=Gj.reportMissingProp=Gj.checkMissingProp=Gj.checkReportMissingProp=void 0;var w$=y(),nW=p(),hi=zi(),_z=p();function rz($,i){let{gen:v,data:u,it:n}=$;v.if(uW(v,u,i,n.opts.ownProperties),()=>{$.setParams({missingProperty:w$._`${i}`},!0),$.error()})}Gj.checkReportMissingProp=rz;function fz({gen:$,data:i,it:{opts:v}},u,n){return(0,w$.or)(...u.map((b)=>(0,w$.and)(uW($,i,b,v.ownProperties),w$._`${n} = ${b}`)))}Gj.checkMissingProp=fz;function xz($,i){$.setParams({missingProperty:i},!0),$.error()}Gj.reportMissingProp=xz;function jj($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:w$._`Object.prototype.hasOwnProperty`})}Gj.hasPropFunc=jj;function vW($,i,v){return w$._`${jj($)}.call(${i}, ${v})`}Gj.isOwnProperty=vW;function yz($,i,v,u){let n=w$._`${i}${(0,w$.getProperty)(v)} !== undefined`;return u?w$._`${n} && ${vW($,i,v)}`:n}Gj.propertyInData=yz;function uW($,i,v,u){let n=w$._`${i}${(0,w$.getProperty)(v)} === undefined`;return u?(0,w$.or)(n,(0,w$.not)(vW($,i,v))):n}Gj.noPropertyInData=uW;function Aj($){return $?Object.keys($).filter((i)=>i!=="__proto__"):[]}Gj.allSchemaProperties=Aj;function cz($,i){return Aj(i).filter((v)=>!(0,nW.alwaysValidSchema)($,i[v]))}Gj.schemaProperties=cz;function hz({schemaCode:$,data:i,it:{gen:v,topSchemaRef:u,schemaPath:n,errorPath:b},it:I},U,D,w){let g=w?w$._`${$}, ${i}, ${u}${n}`:i,J=[[hi.default.instancePath,(0,w$.strConcat)(hi.default.instancePath,b)],[hi.default.parentData,I.parentData],[hi.default.parentDataProperty,I.parentDataProperty],[hi.default.rootData,hi.default.rootData]];if(I.opts.dynamicRef)J.push([hi.default.dynamicAnchors,hi.default.dynamicAnchors]);let X=w$._`${g}, ${v.object(...J)}`;return D!==w$.nil?w$._`${U}.call(${D}, ${X})`:w$._`${U}(${X})`}Gj.callValidateCode=hz;var mz=w$._`new RegExp`;function oz({gen:$,it:{opts:i}},v){let u=i.unicodeRegExp?"u":"",{regExp:n}=i.code,b=n(v,u);return $.scopeValue("pattern",{key:b.toString(),ref:b,code:w$._`${n.code==="new RegExp"?mz:(0,_z.useFunc)($,n)}(${v}, ${u})`})}Gj.usePattern=oz;function dz($){let{gen:i,data:v,keyword:u,it:n}=$,b=i.name("valid");if(n.allErrors){let U=i.let("valid",!0);return I(()=>i.assign(U,!1)),U}return i.var(b,!0),I(()=>i.break()),b;function I(U){let D=i.const("len",w$._`${v}.length`);i.forRange("i",0,D,(w)=>{$.subschema({keyword:u,dataProp:w,dataPropType:nW.Type.Num},b),i.if((0,w$.not)(b),U)})}}Gj.validateArray=dz;function pz($){let{gen:i,schema:v,keyword:u,it:n}=$;if(!Array.isArray(v))throw Error("ajv implementation error");if(v.some((D)=>(0,nW.alwaysValidSchema)(n,D))&&!n.opts.unevaluated)return;let I=i.let("valid",!1),U=i.name("_valid");i.block(()=>v.for Line truncated
missingProperty: ${u},
depsCount: ${i},
deps: ${v}}`};var jS={keyword:"dependencies",type:"object",schemaType:"object",error:TA.error,code($){let[i,v]=AS($);MA($,i),kA($,v)}};function AS({schema:$}){let i={},v={};for(let u in $){if(u==="__proto__")continue;let n=Array.isArray($[u])?i:v;n[u]=$[u]}return[i,v]}function MA($,i=$.schema){let{gen:v,data:u,it:n}=$;if(Object.keys(i).length===0)return;let b=v.let("missing");for(let I in i){let U=i[I];if(U.length===0)continue;let D=(0,$6.propertyInData)(v,u,I,n.opts.ownProperties);if($.setParams({property:I,depsCount:U.length,deps:U.join(", ")}),n.allErrors)v.if(D,()=>{for(let w of U)(0,$6.checkReportMissingProp)($,w)});else v.if(BW._`${D} && (${(0,$6.checkMissingProp)($,U,b)})`),(0,$6.reportMissingProp)($,b),v.else()}}TA.validatePropertyDeps=MA;function kA($,i=$.schema){let{gen:v,data:u,keyword:n,it:b}=$,I=v.name("valid");for(let U in i){if((0,OS.alwaysValidSchema)(b,i[U]))continue;v.if((0,$6.propertyInData)(v,u,U,b.opts.ownProperties),()=>{let D=$.subschema({keyword:n,schemaProp:U},I);$.mergeValidEvaluated(D,I)},()=>v.var(I,!0)),$.ok(I)}}TA.validateSchemaDeps=kA;TA.default=jS});var _A=S((CA)=>{Object.defineProperty(CA,"__esModule",{value:!0});var RA=y(),YS=p(),NS={message:"property name must be valid",params:({params:$})=>RA._`{propertyName: ${$.propertyName}}`},LS={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:NS,code($){let{gen:i,schema:v,data:u,it:n}=$;if((0,YS.alwaysValidSchema)(n,v))return;let b=i.name("valid");i.forIn("key",u,(I)=>{$.setParams({propertyName:I}),$.subschema({keyword:"propertyNames",data:I,dataTypes:["string"],propertyName:I,compositeRule:!0},b),i.if((0,RA.not)(b),()=>{if($.error(!0),!n.allErrors)i.break()})}),$.ok(b)}};CA.default=LS});var SW=S((rA)=>{Object.defineProperty(rA,"__esModule",{value:!0});var hb=a$(),bi=y(),zS=zi(),mb=p(),HS={message:"must NOT have additional properties",params:({params:$})=>bi._`{additionalProperty: ${$.additionalProperty}}`},PS={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:HS,code($){let{gen:i,schema:v,parentSchema:u,data:n,errsCount:b,it:I}=$;if(!b)throw Error("ajv implementation error");let{allErrors:U,opts:D}=I;if(I.props=!0,D.removeAdditional!=="all"&&(0,mb.alwaysValidSchema)(I,v))return;let w=(0,hb.allSchemaProperties)(u.properties),g=(0,hb.allSchemaProperties)(u.patternProperties);J(),$.ok(bi._`${b} === ${zS.default.errors}`);function J(){i.forIn("key",n,(N)=>{if(!w.length&&!g.length)j(N);else i.if(X(N),()=>j(N))})}function X(N){let L;if(w.length>8){let B=(0,mb.schemaRefOrVal)(I,u.properties,"properties");L=(0,hb.isOwnProperty)(i,B,N)}else if(w.length)L=(0,bi.or)(...w.map((B)=>bi._`${N} === ${B}`));else L=bi.nil;if(g.length)L=(0,bi.or)(L,...g.map((B)=>bi._`${(0,hb.usePattern)($,B)}.test(${N})`));return(0,bi.not)(L)}function O(N){i.code(bi._`delete ${n}[${N}]`)}function j(N){if(D.removeAdditional==="all"||D.removeAdditional&&v===!1){O(N);return}if(v===!1){if($.setParams({additionalProperty:N}),$.error(),!U)i.break();return}if(typeof v=="object"&&!(0,mb.alwaysValidSchema)(I,v)){let L=i.name("valid");if(D.removeAdditional==="failing")G(N,L,!1),i.if((0,bi.not)(L),()=>{$.reset(),O(N)});else if(G(N,L),!U)i.if((0,bi.not)(L),()=>i.break())}}function G(N,L,B){let V={keyword:"additionalProperties",dataProp:N,dataPropType:mb.Type.Str};if(B===!1)Object.assign(V,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(V,L)}}};rA.default=PS});var cA=S((yA)=>{Object.defineProperty(yA,"__esModule",{value:!0});var BS=f4(),fA=a$(),ZW=p(),xA=SW(),SS={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:i,schema:v,parentSchema:u,data:n,it:b}=$;if(b.opts.removeAdditional==="all"&&u.additionalProperties===void 0)xA.default.code(new BS.KeywordCxt(b,xA.default,"additionalProperties"));let I=(0,fA.allSchemaProperties)(v);for(let J of I)b.definedProperties.add(J);if(b.opts.unevaluated&&I.length&&b.props!==!0)b.props=ZW.mergeEvaluated.props(i,(0,ZW.toHash)(I),b.props);let U=I.filter((J)=>!(0,ZW.alwaysValidSchema)(b,v[J]));if(U.length===0)return;let D=i.name("valid");for(let J of U){if(w(J))g(J);else{if(i.if((0,fA.propertyInData)(i,n,J,b.opts.ownProperties)),g(J),!b.allErrors)i.else().var(D,!0);i.endIf()}$.it.definedProperties.add(J),$.ok(D)}function w(J){return b.opts.useDefaults&&!b.compositeRule&&v[J].default!==void 0}function g(J){$.subschema({keyword:"properties",schemaProp:J,dataProp:J},D)}}};yA.default=SS});var pA=S((dA)=>{Object.defineProperty(dA,"__esModule",{value:!0});var hA=a$(),ob=y(),mA=p(),oA=p(),VS={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:i,schema:v,data:u,parentSchema:n,it:b}=$,{opts:I}=b,U=(0,hA.allSchemaProperties)(v),D=U.filter((G)=>(0,mA.alwaysValidSchema)(b,v[G]));if(U.length===0||D.length===U.length&&(!b.opts.unevaluated||b.props===!0))return;let w=I.strictSchema&&!I.allowMatchingProperties&&n.properties,g=i.name("valid");if(b.props!==!0&&!(b.props instanceof ob.Name))b.props=(0,oA.evalu Line truncated
`)}var Vn=($)=>(i,v,u,n)=>{let b=u?{...u,async:!1}:{async:!1},I=i._zod.run({value:v,issues:[]},b);if(I instanceof Promise)throw new wi;if(I.issues.length){let U=new(n?.Err??$)(I.issues.map((D)=>V$(D,b,X$())));throw S6(U,n?.callee),U}return I.value},hv=Vn(t$),qn=($)=>async(i,v,u,n)=>{let b=u?{...u,async:!0}:{async:!0},I=i._zod.run({value:v,issues:[]},b);if(I instanceof Promise)I=await I;if(I.issues.length){let U=new(n?.Err??$)(I.issues.map((D)=>V$(D,b,X$())));throw S6(U,n?.callee),U}return I.value},mv=qn(t$),Mn=($)=>(i,v,u)=>{let n=u?{...u,async:!1}:{async:!1},b=i._zod.run({value:v,issues:[]},n);if(b instanceof Promise)throw new wi;return b.issues.length?{success:!1,error:new($??xv)(b.issues.map((I)=>V$(I,n,X$())))}:{success:!0,data:b.value}},kn=Mn(t$),Tn=($)=>async(i,v,u)=>{let n=u?{...u,async:!0}:{async:!0},b=i._zod.run({value:v,issues:[]},n);if(b instanceof Promise)b=await b;return b.issues.length?{success:!1,error:new $(b.issues.map((I)=>V$(I,n,X$())))}:{success:!0,data:b.value}},ov=Tn(t$),Z6=($)=>(i,v,u)=>{let n=u?{...u,direction:"backward"}:{direction:"backward"};return Vn($)(i,v,n)},oJ=Z6(t$),V6=($)=>(i,v,u)=>{return Vn($)(i,v,u)},dJ=V6(t$),q6=($)=>async(i,v,u)=>{let n=u?{...u,direction:"backward"}:{direction:"backward"};return qn($)(i,v,n)},pJ=q6(t$),M6=($)=>async(i,v,u)=>{return qn($)(i,v,u)},aJ=M6(t$),k6=($)=>(i,v,u)=>{let n=u?{...u,direction:"backward"}:{direction:"backward"};return Mn($)(i,v,n)},eJ=k6(t$),T6=($)=>(i,v,u)=>{return Mn($)(i,v,u)},sJ=T6(t$),l6=($)=>async(i,v,u)=>{let n=u?{...u,direction:"backward"}:{direction:"backward"};return Tn($)(i,v,n)},$8=l6(t$),E6=($)=>async(i,v,u)=>{return Tn($)(i,v,u)},i8=E6(t$);var c$={};Gi(c$,{xid:()=>y0,uuid7:()=>aN,uuid6:()=>pN,uuid4:()=>dN,uuid:()=>bn,uppercase:()=>j1,unicodeEmail:()=>n8,undefined:()=>X1,ulid:()=>x0,time:()=>I1,string:()=>D1,sha512_hex:()=>Q7,sha512_base64url:()=>N7,sha512_base64:()=>Y7,sha384_hex:()=>j7,sha384_base64url:()=>G7,sha384_base64:()=>A7,sha256_hex:()=>J7,sha256_base64url:()=>O7,sha256_base64:()=>X7,sha1_hex:()=>w7,sha1_base64url:()=>W7,sha1_base64:()=>g7,rfc5322Email:()=>sN,number:()=>dv,null:()=>J1,nanoid:()=>h0,md5_hex:()=>I7,md5_base64url:()=>D7,md5_base64:()=>U7,mac:()=>s0,lowercase:()=>O1,ksuid:()=>c0,ipv6:()=>e0,ipv4:()=>a0,integer:()=>g1,idnEmail:()=>$7,httpProtocol:()=>v1,html5Email:()=>eN,hostname:()=>v7,hex:()=>b7,guid:()=>o0,extendedDuration:()=>oN,emoji:()=>p0,email:()=>d0,e164:()=>u1,duration:()=>m0,domain:()=>u7,datetime:()=>U1,date:()=>b1,cuid2:()=>f0,cuid:()=>r0,cidrv6:()=>i1,cidrv4:()=>$1,browserEmail:()=>i7,boolean:()=>W1,bigint:()=>w1,base64url:()=>t6,base64:()=>n1});var r0=/^[cC][0-9a-z]{6,}$/,f0=/^[0-9a-z]+$/,x0=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,y0=/^[0-9a-vA-V]{20}$/,c0=/^[A-Za-z0-9]{27}$/,h0=/^[a-zA-Z0-9_-]{21}$/,m0=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,oN=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,o0=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,bn=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},dN=bn(4),pN=bn(6),aN=bn(7),d0=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,eN=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,sN=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,n8=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,$7=n8,i7=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,n7="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function p0(){return new RegExp(n7,"u")}var a0=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,e0=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,s0=($)=>{let i=o$($??":");return new RegExp(`^(?:[0-9A-F]{2}${i}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${i}){5}[0-9a-f]{2}$`)},$1=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-Line truncated
`).filter((b)=>b),u=Math.min(...v.map((b)=>b.length-b.trimStart().length)),n=v.map((b)=>b.slice(u)).map((b)=>" ".repeat(this.indent*2)+b);for(let b of n)this.content.push(b)}compile(){let $=Function,i=this?.args,u=[...(this?.content??[""]).map((n)=>` ${n}`)];return new $(...i,u.join(`
`))}}var T1={major:4,minor:4,patch:3};var t=A("$ZodType",($,i)=>{var v;$??($={}),$._zod.def=i,$._zod.bag=$._zod.bag||{},$._zod.version=T1;let u=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))u.unshift($);for(let n of u)for(let b of n._zod.onattach)b($);if(u.length===0)(v=$._zod).deferred??(v.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let n=(I,U,D)=>{let w=ki(I),g;for(let J of U){if(J._zod.def.when){if(R0(I))continue;if(!J._zod.def.when(I))continue}else if(w)continue;let X=I.issues.length,O=J._zod.check(I);if(O instanceof Promise&&D?.async===!1)throw new wi;if(g||O instanceof Promise)g=(g??Promise.resolve()).then(async()=>{if(await O,I.issues.length===X)return;if(!w)w=ki(I,X)});else{if(I.issues.length===X)continue;if(!w)w=ki(I,X)}}if(g)return g.then(()=>{return I});return I},b=(I,U,D)=>{if(ki(I))return I.aborted=!0,I;let w=n(U,u,D);if(w instanceof Promise){if(D.async===!1)throw new wi;return w.then((g)=>$._zod.parse(g,D))}return $._zod.parse(w,D)};$._zod.run=(I,U)=>{if(U.skipChecks)return $._zod.parse(I,U);if(U.direction==="backward"){let w=$._zod.parse({value:I.value,issues:[]},{...U,skipChecks:!0});if(w instanceof Promise)return w.then((g)=>{return b(g,I,U)});return b(w,I,U)}let D=$._zod.parse(I,U);if(D instanceof Promise){if(U.async===!1)throw new wi;return D.then((w)=>n(w,u,U))}return n(D,u,U)}}c($,"~standard",()=>({validate:(n)=>{try{let b=kn($,n);return b.success?{value:b.data}:{issues:b.error?.issues}}catch(b){return ov($,n).then((I)=>I.success?{value:I.data}:{issues:I.error?.issues})}},vendor:"zod",version:1}))}),In=A("$ZodString",($,i)=>{t.init($,i),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??D1($._zod.bag),$._zod.parse=(v,u)=>{if(i.coerce)try{v.value=String(v.value)}catch(n){}if(typeof v.value==="string")return v;return v.issues.push({expected:"string",code:"invalid_type",input:v.value,inst:$}),v}}),n$=A("$ZodStringFormat",($,i)=>{ln.init($,i),In.init($,i)}),E1=A("$ZodGUID",($,i)=>{i.pattern??(i.pattern=o0),n$.init($,i)}),t1=A("$ZodUUID",($,i)=>{if(i.version){let u={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[i.version];if(u===void 0)throw Error(`Invalid UUID version: "${i.version}"`);i.pattern??(i.pattern=bn(u))}else i.pattern??(i.pattern=bn());n$.init($,i)}),R1=A("$ZodEmail",($,i)=>{i.pattern??(i.pattern=d0),n$.init($,i)}),C1=A("$ZodURL",($,i)=>{n$.init($,i),$._zod.check=(v)=>{try{let u=v.value.trim();if(!i.normalize&&i.protocol?.source===v1.source){if(!/^https?:\/\//i.test(u)){v.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:v.value,inst:$,continue:!i.abort});return}}let n=new URL(u);if(i.hostname){if(i.hostname.lastIndex=0,!i.hostname.test(n.hostname))v.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:i.hostname.source,input:v.value,inst:$,continue:!i.abort})}if(i.protocol){if(i.protocol.lastIndex=0,!i.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol))v.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:i.protocol.source,input:v.value,inst:$,continue:!i.abort})}if(i.normalize)v.value=n.href;else v.value=u;return}catch(u){v.issues.push({code:"invalid_format",format:"url",input:v.value,inst:$,continue:!i.abort})}}}),_1=A("$ZodEmoji",($,i)=>{i.pattern??(i.pattern=p0()),n$.init($,i)}),r1=A("$ZodNanoID",($,i)=>{i.pattern??(i.pattern=h0),n$.init($,i)}),f1=A("$ZodCUID",($,i)=>{i.pattern??(i.pattern=r0),n$.init($,i)}),x1=A("$ZodCUID2",($,i)=>{i.pattern??(i.pattern=f0),n$.init($,i)}),y1=A("$ZodULID",($,i)=>{i.pattern??(i.pattern=x0),n$.init($,i)}),c1=A("$ZodXID",($,i)=>{i.pattern??(i.pattern=y0),n$.init($,i)}),h1=A("$ZodKSUID",($,i)=>{i.pattern??(i.pattern=c0),n$.init($,i)}),m1=A("$ZodISODateTime",($,i)=>{i.pattern??(i.pattern=U1(i)),n$.init($,i)}),o1=A("$ZodISODate",($,i)=>{i.pattern??(i.pattern=b1),n$.init($,i)}),d1=A("$ZodISOTime",($,i)=>{i.pattern??(i.pattern=I1(i)),n$.init($,i)}),p1=A("$ZodISODuration",($,i)=>{i.pattern??(i.pattern=m0),n$.init($,i)}),a1=A("$ZodIPv4",($,i)=>{i.pattern??(i.pattern=a0),n$.init($,i),$._zod.bag.format="ipv4"}),e1=A("$ZodIPv6",($,i)=>{i.pattern??(i.pattern=e0),n$.init($,i),$._zod.bag.format="ipv6",$._zod.check=(v)=>{try{new URL(`http://[${v.value}]`)}catch{v.issues.push({code:"invalid_format",format:"ipv6",input:v.value,inst:$,continue:!i.abort})}}}),s1=A("$ZodMAC",($,i)=>{i.pattern??(i.pattern=s0(i.delimiter)),n$.init($,i),$._zod.bag.format="mac"}),$I=A("$ZodCIDRv4",($,i)=>{i.pattern??(i.pattern=$1),n$.init($,i)}),iI=A("$ZodCIDRv6",($,i)=>{i.pattern??(i.pattern=i1),n$.init($,i),$._zod.check=(v)=>{let u=v.value.split("/");try{if(u.length!==2)throw Error();let[n,b]=u;if(!b)throw Error();let I=Number(b);if(`${I}`!==b)throw Error();if(I<0||I>128)throw Error();new URL(`http://[${n}]`)}catch{v.issues.push({code:"invalid_format",format:"cidrv6",input:v.value,inst:$,continue:!i.abort})}}});function nI($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}var Line truncated
if (${q}.issues.length) {
if (${M} in input) {
payload.issues = payload.issues.concat(${q}.issues.map(iss => ({
...iss,
path: iss.path ? [${M}, ...iss.path] : [${M}]
})));
}
}
if (${q}.value === undefined) {
if (${M} in input) {
newResult[${M}] = undefined;
}
} else {
newResult[${M}] = ${q}.value;
}
`);else if(!C)O.write(`
const ${q}_present = ${M} in input;
if (${q}.issues.length) {
payload.issues = payload.issues.concat(${q}.issues.map(iss => ({
...iss,
path: iss.path ? [${M}, ...iss.path] : [${M}]
})));
}
if (!${q}_present && !${q}.issues.length) {
payload.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: undefined,
path: [${M}]
});
}
if (${q}_present) {
if (${q}.value === undefined) {
newResult[${M}] = undefined;
} else {
newResult[${M}] = ${q}.value;
}
}
`);else O.write(`
if (${q}.issues.length) {
payload.issues = payload.issues.concat(${q}.issues.map(iss => ({
...iss,
path: iss.path ? [${M}, ...iss.path] : [${M}]
})));
}
if (${q}.value === undefined) {
if (${M} in input) {
newResult[${M}] = undefined;
}
} else {
newResult[${M}] = ${q}.value;
}
`)}O.write("payload.value = newResult;"),O.write("return payload;");let B=O.compile();return(V,q)=>B(X,V,q)},b,I=un,U=!nn.jitless,w=U&&M0.value,g=i.catchall,J;$._zod.parse=(X,O)=>{J??(J=u.value);let j=X.value;if(!I(j))return X.issues.push({expected:"object",code:"invalid_type",input:j,inst:$}),X;if(U&&w&&O?.async===!1&&O.jitless!==!0){if(!b)b=n(i.shape);if(X=b(X,O),!g)return X;return P8([],j,X,O,J,$)}return v(X,O)}});function w8($,i,v,u){for(let b of $)if(b.issues.length===0)return i.value=b.value,i;let n=$.filter((b)=>!ki(b));if(n.length===1)return i.value=n[0].value,n[0];return i.issues.push({code:"invalid_union",input:i.value,inst:v,errors:$.map((b)=>b.issues.map((I)=>V$(I,u,X$())))}),i}var sv=A("$ZodUnion",($,i)=>{t.init($,i),c($._zod,"optin",()=>i.options.some((u)=>u._zod.optin==="optional")?"optional":void 0),c($._zod,"optout",()=>i.options.some((u)=>u._zod.optout==="optional")?"optional":void 0),c($._zod,"values",()=>{if(i.options.every((u)=>u._zod.values))return new Set(i.options.flatMap((u)=>Array.from(u._zod.values)));return}),c($._zod,"pattern",()=>{if(i.options.every((u)=>u._zod.pattern)){let u=i.options.map((n)=>n._zod.pattern);return new RegExp(`^(${u.map((n)=>Cv(n.source)).join("|")})$`)}return});let v=i.options.length===1?i.options[0]._zod.run:null;$._zod.parse=(u,n)=>{if(v)return v(u,n);let b=!1,I=[];for(let U of i.options){let D=U._zod.run({value:u.value,issues:[]},n);if(D instanceof Promise)I.push(D),b=!0;else{if(D.issues.length===0)return D;I.push(D)}}if(!b)return w8(I,u,$,n);return Promise.all(I).then((U)=>{return w8(U,u,$,n)})}});function g8($,i,v,u){let n=$.filter((b)=>b.issues.length===0);if(n.length===1)return i.value=n[0].value,i;if(n.length===0)i.issues.push({code:"invalid_union",input:i.value,inst:v,errors:$.map((b)=>b.issues.map((I)=>V$(I,u,X$())))});else i.issues.push({code:"invalid_union",input:i.value,inst:v,errors:[],inclusive:!1});return i}var NI=A("$ZodXor",($,i)=>{sv.init($,i),i.inclusive=!1;let v=i.options.length===1?i.options[0]._zod.run:null;$._zod.parse=(u,n)=>{if(v)return v(u,n);let b=!1,I=[];for(let U of i.options){let D=U._zod.run({value:u.value,issues:[]},n);if(D instanceof Promise)I.push(D),b=!0;else I.push(D)}if(!b)return g8(I,u,$,n);return Promise.all(I).then((U)=>{return g8(U,u,$,n)})}}),LI=A("$ZodDiscriminatedUnion",($,i)=>{i.inclusive=!1,sv.init($,i);let v=$._zod.parse;c($._zod,"propValues",()=>{let n={};for(let b of i.options){let I=b._zod.propValues;if(!I||Object.keys(I).length===0)throw Error(`Invalid discriminated union option at index "${i.options.indexOf(b)}"`);for(let[U,D]of Object.entries(I)){if(!n[U])n[U]=new Set;for(let w of D)n[U].add(w)}}return n});let u=Sn(()=>{let n=i.options,b=new Map;for(let I of n){let U=I._zod.propValues?.[i.discriminator];if(!U||U.size===0)throw Error(`Invalid discriminated union option at index "${i.options.indexOf(I)}"`);for(let D of U){if(b.has(D))throw Error(`Duplicate discriminator value "${String(D)}"`);b.set(D,I)}}return b});$._zod.parse=(n,b)=>{let I=n.value;if(!un(I))return n.issues.push({code:"invalid_type",expected:"object",input:I,inst:$}),n;let U=u.value.get(I?.[i.discriminator]);if(U)return U._zod.run(n,b);if(i.unionFallback||b.direction==="backward")return v(n,b);return n.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:i.discriminator,options:Array.from(u.value.keys()),input:I,path:[i.discriminator],inst:$}),n}}),KI=A("$ZodIntersection",($,i)=>{t.init($,i),$._zod.parse=(v,u)=>{let n=v.value,b=i.left._zod.run({value:n,issues:[]},u),I=i.right._zod.run({value:n,issues:[]},u);if(b instanceof Promise||I instanceof Promise)return Promise.all([b,I]).then(([D,w])=>{return W8(v,D,w)});return W8(v,b,I)}});function l1($,i){if($===i)return{valid:!0,data:$};if($ instanceof Date&&i instanceof Date&&+$===+i)return{valid:!0,data:$};if(Mi($)&&Mi(i)){let v=Object.keys(i),u=Object.keys($).filter((b)=>v.indexOf(b)!==-1),n={...$,...i};for(let b of u){let I=l1($[b],i[b]);if(!I.valid)return{valid:!1,mergeErrorPath:[b,...I.mergeErrorPath]};n[b]=I.data}return{valid:!0,data:n}}if(Array.isArray($)&&Array.isArray(i)){if($.length!==i.length)return{valid:!1,mergeErrorPath:[]};let v=[];for(let u=0;u<$.length;u++){let n=$[u],b=i[u],I=l1(n,b);if(!I.valid)return{valid:!1,mergeErrorPath:[u,...I.mergeErrorPath]};v.push(I.data)}return{valid:!0,data:v}}return{valid:!1,mergeErrorPath:[]}}function W8($,i,v){let u=new Map,n;for(let U of i.issues)if(U.code==="unrecognized_keys"){n??(n=U);for(let D of U.keys){if(!u.has(D))u.set(D,{});u.get(D).l=!0}}else $.issues.push(U);for(let U of v.issues)if(U.code==="unrecognized_keys")for(let D of U.keys){if(!u.has(D))u.set(D,{});u.get(D).r=!0}else $.issues.push(U);let b=[...u].filter(([,U])=>U.l&&U.r).map(([U])=>U);if(b.length&&n)$.issues.push({...n,keys:b});if(ki($))return $;let I=l1(i.value,v.value);if(!I.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(I.mergeErrorPath)}`);return $.value=I.data,$}var m6=A("$ZodTuple",($,i)=>{t.init($,i Line truncated
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let I of $.seen.entries()){let U=I[1];if(i===I[0]){b(I);continue}if($.external){let w=$.external.registry.get(I[0])?.id;if(i!==I[0]&&w){b(I);continue}}if($.metadataRegistry.get(I[0])?.id){b(I);continue}if(U.cycle){b(I);continue}if(U.count>1){if($.reused==="ref"){b(I);continue}}}}function Ri($,i){let v=$.seen.get(i);if(!v)throw Error("Unprocessed schema. This is a bug in Zod.");let u=(U)=>{let D=$.seen.get(U);if(D.ref===null)return;let w=D.def??D.schema,g={...w},J=D.ref;if(D.ref=null,J){u(J);let O=$.seen.get(J),j=O.schema;if(j.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))w.allOf=w.allOf??[],w.allOf.push(j);else Object.assign(w,j);if(Object.assign(w,g),U._zod.parent===J)for(let N in w){if(N==="$ref"||N==="allOf")continue;if(!(N in g))delete w[N]}if(j.$ref&&O.def)for(let N in w){if(N==="$ref"||N==="allOf")continue;if(N in O.def&&JSON.stringify(w[N])===JSON.stringify(O.def[N]))delete w[N]}}let X=U._zod.parent;if(X&&X!==J){u(X);let O=$.seen.get(X);if(O?.schema.$ref){if(w.$ref=O.schema.$ref,O.def)for(let j in w){if(j==="$ref"||j==="allOf")continue;if(j in O.def&&JSON.stringify(w[j])===JSON.stringify(O.def[j]))delete w[j]}}}$.override({zodSchema:U,jsonSchema:w,path:D.path??[]})};for(let U of[...$.seen.entries()].reverse())u(U[0]);let n={};if($.target==="draft-2020-12")n.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")n.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")n.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let U=$.external.registry.get(i)?.id;if(!U)throw Error("Schema is missing an `id` property");n.$id=$.external.uri(U)}Object.assign(n,v.def??v.schema);let b=$.metadataRegistry.get(i)?.id;if(b!==void 0&&n.id===b)delete n.id;let I=$.external?.defs??{};for(let U of $.seen.entries()){let D=U[1];if(D.def&&D.defId){if(D.def.id===D.defId)delete D.def.id;I[D.defId]=D.def}}if($.external);else if(Object.keys(I).length>0)if($.target==="draft-2020-12")n.$defs=I;else n.definitions=I;try{let U=JSON.parse(JSON.stringify(n));return Object.defineProperty(U,"~standard",{value:{...i["~standard"],jsonSchema:{input:pn(i,"input",$.processors),output:pn(i,"output",$.processors)}},enumerable:!1,writable:!1}),U}catch(U){throw Error("Error converting schema to JSON.")}}function M$($,i){let v=i??{seen:new Set};if(v.seen.has($))return!1;v.seen.add($);let u=$._zod.def;if(u.type==="transform")return!0;if(u.type==="array")return M$(u.element,v);if(u.type==="set")return M$(u.valueType,v);if(u.type==="lazy")return M$(u.getter(),v);if(u.type==="promise"||u.type==="optional"||u.type==="nonoptional"||u.type==="nullable"||u.type==="readonly"||u.type==="default"||u.type==="prefault")return M$(u.innerType,v);if(u.type==="intersection")return M$(u.left,v)||M$(u.right,v);if(u.type==="record"||u.type==="map")return M$(u.keyType,v)||M$(u.valueType,v);if(u.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;return M$(u.in,v)||M$(u.out,v)}if(u.type==="object"){for(let n in u.shape)if(M$(u.shape[n],v))return!0;return!1}if(u.type==="union"){for(let n of u.options)if(M$(n,v))return!0;return!1}if(u.type==="tuple"){for(let n of u.items)if(M$(n,v))return!0;if(u.rest&&M$(u.rest,v))return!0;return!1}return!1}var SD=($,i={})=>(v)=>{let u=Ei({...v,processors:i});return $$($,u),ti(u,$),Ri(u,$)},pn=($,i,v={})=>(u)=>{let{libraryOptions:n,target:b}=u??{},I=Ei({...n??{},target:b,io:i,processors:v});return $$($,I),ti(I,$),Ri(I,$)};var f5={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ZD=($,i,v,u)=>{let n=v;n.type="string";let{minimum:b,maximum:I,format:U,patterns:D,contentEncoding:w}=$._zod.bag;if(typeof b==="number")n.minLength=b;if(typeof I==="number")n.maxLength=I;if(U){if(n.format=f5[U]??U,n.format==="")delete n.format;if(U==="time")delete n.format}if(w)n.contentEncoding=w;if(D&&D.size>0){let g=[...D];if(g.length===1)n.pattern=g[0].source;else if(g.length>1)n.allOf=[...g.map((J)=>({...i.target==="draft-07"||i.target==="draft-04"||i.target==="openapi-3.0"?{type:"string"}:{},pattern:J.source}))]}},VD=($,i,v,u)=>{let n=v,{minimum:b,maximum:I,format:U,multipleOf:D,exclusiveMaximum:w,exclusiveMinimum:g}=$._zod.bag;if(typeof U==="string"&&U.includes("int"))n.type="integer";else n.type="number";let J=typeof g==="number"&&g>=(b??Number.NEGATIVE_INFINITY),X=typeof w==="number"&&w<=(I??Number.POSITIVE_INFINITY),O=i.target==="draft-04"||i.target==="openapi-3.0";if(J)if(O)n.minimum=g,n.exclusiveMinimum=!0;else n.exclusiveMinimum=g;else if(typeof b==="number")n.minimum=b;if(X)if(O)n.maximum=w,n.exclusiveMaximum=!0;else n.exclusiveMaximum=w;else if(typeof I==="number")n.maximum=I;if(typeof D==="number")n.multipleOf=D},qD=($,i,v,u)=>{v.type="boolean"},MD=($,i,v,u)=>{if(i.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},kD=($,i,v,u)=>{if(i.unrepresentable==="Line truncated
`);if($===-1)return null;let i=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),gV(i)}clear(){this._buffer=void 0}}function gV($){return nO.parse(JSON.parse($))}function eG($){return JSON.stringify($)+`
`}class hW{constructor($=sG.stdin,i=sG.stdout){this._stdin=$,this._stdout=i,this._readBuffer=new cW,this._started=!1,this._ondata=(v)=>{this._readBuffer.append(v),this.processReadBuffer()},this._onerror=(v)=>{this.onerror?.(v)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send($){return new Promise((i)=>{let v=eG($);if(this._stdout.write(v))i();else this._stdout.once("drain",i)})}}import{dirname as F6,resolve as wN}from"node:path";import{fileURLToPath as hM}from"node:url";import{existsSync as pi,mkdirSync as jV,readFileSync as iQ,readdirSync as AV,writeFileSync as nQ}from"node:fs";import{homedir as $0}from"node:os";import{dirname as GV,join as zv}from"node:path";var WV=W.enum(["account","assist","browser","manual","curl","f12"]),JV=W.object({accessToken:W.string().describe("主站访问令牌"),corpId:W.string().describe("企业 ID"),staffId:W.string().describe("员工 ID")}),XV=W.object({refreshTtl:W.number().default(300).describe("提前多少秒刷新,默认 5 分钟"),refreshToken:W.string().optional().describe("OAuth2 Refresh Token"),expiresAt:W.number().optional().describe("AccessToken 到期时间戳 (ms)")}),OV=W.object({platform:W.string().optional().describe("官方会话平台类型 (如 ASSIST, WEB, MOBILE, OPENAPI)"),isAssistPlatform:W.boolean().optional().describe("是否为官方协助/代客平台登录"),isShortTermToken:W.boolean().optional().describe("是否为短期临时 Token"),assistId:W.string().optional().describe("协助会话/工单 ID"),operationUserId:W.string().optional().describe("协助操作人 ID (如内部运维/实施账号)"),operationUserName:W.string().optional().describe("协助操作人姓名"),staffName:W.string().optional().describe("当前员工真实姓名"),cellphone:W.string().optional().describe("绑定手机号"),isAdmin:W.boolean().optional().describe("是否管理员"),deviceType:W.string().optional().describe("设备类型"),loginAccountType:W.string().optional().describe("登录账号类型"),loginTime:W.number().optional().describe("登录时间戳 (ms)"),expTime:W.number().optional().describe("过期时间戳 (ms)"),sourceChannel:W.string().optional().describe("来源渠道 (如 APP, WEB)")}),mW=W.object({id:W.string().describe("配置/身份唯一标识 (默认等于 corpId,同企业多身份时形如 corpId@accountId 或 corpId:staffId)"),name:W.string().describe("企业名称"),corpId:W.string().optional().describe("底层企业物理 ID (未填时默认等于 id)"),userId:W.string().optional().describe("所属用户 ID"),staffId:W.string().optional().describe("员工工号 (默认取 credentials.staffId)"),staffName:W.string().optional().describe("员工真实姓名"),baseUrl:W.string().url().optional().default("https://app.ekuaibao.com"),source:WV.optional().default("manual").describe("凭证来源: account/assist/browser/manual/curl/f12"),accountId:W.string().optional().describe("所属主账号标识(如手机号)"),credentials:JV,auth:XV.optional(),session:OV.optional().describe("官方服务端 Session 与操作人元数据")}),oW=W.object({stateful:W.boolean().default(!0).describe("是否为有状态模式 (true 记忆默认企业,false 无状态需显式传 --corp)"),defaultCorpId:W.string().optional().describe("默认工作企业 ID"),defaultAccountId:W.string().optional().describe("默认主账号")});var v6="enterprises",dW="HOSE_ENTERPRISES_DIR",vQ="HOSE_USER_ENTERPRISES_DIR",uQ="HOSE_CONFIG_FILE",pW=zv($0(),".config","hose-use","enterprises"),bQ=zv($0(),".cache","ekb-mcp","enterprises");var sb=zv($0(),".config","hose-use","config.json"),$Q=zv($0(),".cache","ekb-mcp","config.json");function IQ($){jV($,{recursive:!0})}function aW(){let $=process.env[dW]?.trim();if($)return pi($)?[$]:[];let i=process.env[vQ]?.trim();if(i)return[v6,i].filter((n)=>pi(n));let v=[v6,pW,bQ],u=[];for(let n of v)if(pi(n)&&!u.includes(n))u.push(n);return u}function eW(){let $=process.env[dW]?.trim();if($)return $;let i=process.env[vQ]?.trim();if(i)return i;if(pi(v6))return v6;return pW}function i0(){return[`${dW}=<path>`,v6,pW,bQ]}function n0(){let $=process.env[uQ]?.trim();if($)return $;if(pi(sb))return sb;if(pi($Q))return $Q;return sb}function Qn(){let $=n0();try{if(pi($)){let i=iQ($,"utf-8");return oW.parse(JSON.parse(i))}}catch{}return{stateful:!0,defaultCorpId:void 0,defaultAccountId:void 0}}function u6($){let i=Qn(),v=oW.parse({...i,...$}),n=process.env[uQ]?.trim()||sb;return IQ(GV(n)),nQ(n,JSON.stringify(v,null,2),"utf-8"),v}f Line truncated
`+"如需设置默认企业,可执行 `hose config mode stateful` 切换为有状态模式。");let I=$[0];if(I)return I;let U=v?.length?` (已检索路径: ${v.join(", ")})`:"";throw Error(`未找到任何企业配置。请先运行 'hose auth login' 登录或添加企业配置${U}。`)}class b6{current=null;corps=new Map;stateful=!0;defaultCorpId;constructor($=[],i={}){this.stateful=i.stateful??!0,this.defaultCorpId=i.defaultCorpId,this.reload($)}reload($){this.corps.clear();for(let i of $)this.corps.set(i.id,i);if(!this.stateful){this.current=null;return}if(this.defaultCorpId&&this.corps.has(this.defaultCorpId))this.current=this.corps.get(this.defaultCorpId);else if(this.corps.size>0)this.current=Array.from(this.corps.values())[0];else this.current=null}isStateful(){return this.stateful}setStateful($){if(this.stateful=$,!$)this.current=null;else if(!this.current&&this.corps.size>0)this.current=Array.from(this.corps.values())[0]}getCurrent(){return this.current}getCorp($){return this.corps.get($)}resolve($,i){return QV(Array.from(this.corps.values()),{stateful:this.stateful,defaultCorpId:this.defaultCorpId,corpId:$},i)}upsertCorp($,i=!1){if(this.corps.set($.id,$),this.stateful&&(i||!this.current))this.current=$,this.defaultCorpId=$.id}switchCorp($,i=!0){let v=this.corps.get($);if(!v)return!1;if(this.current=v,this.defaultCorpId=v.id,i&&this.stateful)u6({defaultCorpId:v.id});return!0}listCorps(){return Array.from(this.corps.values()).map(($)=>({id:$.id,name:$.name,source:$.source||"manual",accountId:$.accountId,staffId:$.credentials.staffId,baseUrl:$.baseUrl,current:$.id===this.current?.id,expiresAt:$.auth?.expiresAt||$.session?.expTime}))}}class Fi extends Error{name="KyError";get isKyError(){return!0}}class I6 extends Fi{name="HTTPError";response;request;options;data;constructor($,i,v){let u=$.status||$.status===0?$.status:"",n=$.statusText??"",b=`${u} ${n}`.trim(),I=b?`status code ${b}`:"an unknown error";super(`Request failed with ${I}: ${i.method} ${i.url}`);this.response=$,this.request=i,this.options=v}}class U6 extends Fi{name="NetworkError";request;constructor($,i){super(`Request failed due to a network error: ${$.method} ${$.url}`,i);this.request=$}}class D6 extends Error{name="NonError";value;constructor($){let i="Non-error value was thrown";try{if(typeof $==="string")i=$;else if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string")i=$.message}catch{}super(i);this.value=$}}class Fv extends Fi{name="ForceRetryError";customDelay;code;customRequest;constructor($){let i=$?.cause?$.cause instanceof Error?$.cause:new D6($.cause):void 0;super($?.code?`Forced retry: ${$.code}`:"Forced retry",i?{cause:i}:void 0);this.customDelay=$?.delay,this.code=$?.code,this.customRequest=$?.request}}class sW extends Error{name="SchemaValidationError";issues;constructor($){super("Response schema validation failed");this.issues=$}}class Ui extends Fi{name="TimeoutError";request;constructor($){super(`Request timed out: ${$.method} ${$.url}`);this.request=$}}var $J=(()=>{let $=!1,i=!1,v=typeof globalThis.ReadableStream==="function",u=typeof globalThis.Request==="function";if(v&&u)try{i=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return $=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return $&&!i})(),DQ=typeof globalThis.AbortController==="function",v0=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",wQ=typeof globalThis.ReadableStream==="function",gQ=typeof globalThis.FormData==="function",u0=["get","post","put","patch","head","delete"],YV=()=>{return};YV();var WQ={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Bv=2147483647,JQ=40,b0=Symbol("stop");class I0{options;constructor($){this.options=$}}var XQ=($)=>new I0($),OQ={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,baseUrl:!0,prefix:!0,retry:!0,timeout:!0,totalTimeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},jQ={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0};var U0=new TextEncoder,NV=($)=>{if(!$)return 0;if($ instanceof FormData){let i=0;for(let[v,u]of $)i+=JQ,i+=U0.encode(`Content-Disposition: form-data; name="${v}"`).byteLength,i+=typeof u==="string"?U0.encode(u).byteLength:u.size;return i}if($ instanceof Blob)return $.size;if($ instanceof ArrayBuffer||ArrayBuffer.isView($))return $.byteLength;if(typeof $==="string")return U0.encode($).byteLength;if($ instanceof URLSearchParams)return U0.encode($.toString()).byteLength;return 0},AQ=($,i,v)=>{let u,n=0;return $.pipeThrough(new TransformStream({transform(b,I){if(I.enqueue(b),u){n+=u.byteLength;let U=i===0?0:n/i;if(U>=1)U=1-Number.EPSILON;v?.({percent:U,totalBytes:Math.max(i,n),transf Line truncated
${i}
-----END PUBLIC KEY-----`;return EQ.publicEncrypt({key:v,padding:EQ.constants.RSA_PKCS1_PADDING},Buffer.from($)).toString("base64")}function A6($,i="86"){let v=$.trim();if(v.includes("-"))return v;return`${i}-${v}`}async function sV($){let i=$.businessCenterUrl||Yn,v=$.areaCode||"86",u=$.deviceType||"desktop",n=await aV(i),b=eV($.password,n),I=await Q$.post(`${i}/cloud-auth/public/auth/login-by-password`,{json:{deviceType:u,username:A6($.phone,v),password:b}}).json();if(!I.data)throw new g$(I.errorMessage||"账号或密码错误");return{cloudAuthToken:I.data}}async function RQ($){let i=$.businessCenterUrl||Yn,v=$.areaCode||"86",u={bizType:"LOGIN",account:A6($.phone,v),channelType:"SMS",...$.captchaParams},n=await Q$.post(`${i}/cloud-auth/public/auth/send-verification-code`,{json:u}).json();if(n.errorCode)throw new g$(n.errorMessage||"发送验证码失败");return{codeId:n.data?.codeId}}async function $q($){let i=$.businessCenterUrl||Yn,v=$.areaCode||"86",u=$.deviceType||"desktop",n=await Q$.post(`${i}/cloud-auth/public/auth/login-by-code`,{json:{username:A6($.phone,v),code:$.code.trim(),codeId:$.codeId,deviceType:u}}).json();if(!n.data)throw new g$(n.errorMessage||"验证码错误或已过期");return{cloudAuthToken:n.data}}async function iq($={}){let i=$.webbridgeUrl||dV;try{let u=(await Q$.post(`${i}/command`,{json:{action:"evaluate",args:{code:`(() => {
const sessionStr = localStorage.getItem("session");
const cloudAuthToken = localStorage.getItem("cloudAuthToken");
let sessionObj = null;
try { sessionObj = JSON.parse(sessionStr || "{}"); } catch {}
return {
cloudAuthToken,
accessToken: sessionObj?.user?.accessToken || localStorage.getItem("accessToken"),
corpId: sessionObj?.user?.corpId || localStorage.getItem("corpId"),
staffId: sessionObj?.user?.staffId || sessionObj?.staff?.id || localStorage.getItem("staffId"),
};
})()`},session:"ekb-sync-auth"}}).json()).data?.value;if(!u||!u.cloudAuthToken&&!u.accessToken)throw new g$("未能从当前浏览器会话中获取到合思登录凭证,请确保网页已登录");return{cloudAuthToken:u.cloudAuthToken,activeSession:u.accessToken&&u.corpId?{accessToken:u.accessToken,corpId:u.corpId,staffId:u.staffId}:void 0}}catch(v){if(v instanceof g$)throw v;throw new g$(`连接浏览器 WebBridge 失败: ${v instanceof Error?v.message:String(v)}`)}}function CQ($){let i={};if(!$)return i;let v=/(?:-H|--header)\s+['"]([^'"]+)['"]/gi,u;while((u=v.exec($))!==null){let b=u[1],I=b.indexOf(":");if(I!==-1){let U=b.slice(0,I).trim().toLowerCase().replace(/[^a-z]/g,""),D=b.slice(I+1).trim();if(U==="accesstoken")i.accessToken=D;if(U==="corpid"||U==="corporationid")i.corpId=D;if(U==="staffid")i.staffId=D}}let n=$.split(`
`);for(let b of n){let I=b.trim(),U=I.indexOf(":");if(U!==-1){let D=I.slice(0,U).trim().toLowerCase().replace(/[^a-z]/g,""),w=I.slice(U+1).trim().replace(/^['"]|['"]$/g,"");if(D==="accesstoken"&&!i.accessToken)i.accessToken=w;if((D==="corpid"||D==="corporationid")&&!i.corpId)i.corpId=w;if(D==="staffid"&&!i.staffId)i.staffId=w}}if(!i.corpId){let b=/(?:[?&]corpId=)([^&'"\s]+)/i.exec($);if(b)i.corpId=decodeURIComponent(b[1])}if(!i.accessToken){let b=/ekb-access-token=([^;'"\s]+)/i.exec($);if(b)i.accessToken=decodeURIComponent(b[1])}if(!i.corpId){let b=/(?:^|;\s*)corpId=([^;'"\s]+)/i.exec($);if(b)i.corpId=decodeURIComponent(b[1])}return i}async function _Q($){let{accessToken:i,corpId:v,staffId:u}=$,n=$.baseUrl||pV;if(!i||!v||!u)throw new g$("导入凭证失败:accessToken、corpId、staffId 均为必填项");let b;try{if(b=(await Q$.get(`${n}/api/account/v2/session`,{headers:{accesstoken:i,corpid:v,staffid:u}}).json()).value,!b||!b.corporationId&&!b.id&&!b.userId)throw Error("服务端未返回有效 Session")}catch(G){throw new g$(`凭证校验失败,请检查 token 是否已过期: ${G instanceof Error?G.message:String(G)}`)}let I=$.name,U=b?.privilege,D,w,g,J;try{let G=await Q$.get(`${n}/api/engine/realm/$UNITY/actions/jwt`,{searchParams:{corpId:v},headers:{accesstoken:i,corpid:v,staffid:u}}).json(),N=G.id||G.value;if(N){let L=N.split(".");if(L.length>=2){let B=JSON.parse(Buffer.from(L[1],"base64").toString("utf-8"));if(!I&&B.corporationName)I=B.corporationName;if(B.staffName)U=B.staffName;if(B.cellphone)D=B.cellphone;if(B.isAdmin!==void 0)w=B.isAdmin==="true"||B.isAdmin===!0;if(B.exp)J=Number(B.exp)*1000}}}catch{}let X="curl";if(b?.isAssistPlatform||b?.platform==="ASSIST")X="assist";let O;if(b?.expTime&&b.expTime>0)O=b.expTime;else if(J&&J>0)O=J;else if(b?.isAssistPlatform&&b?.loginTime)O=b.loginTime+7200000;let j={id:v,name:I||`企业-${v}`,baseUrl:n,source:X,staffName:U,credentials:{accessToken:i,corpId:v,staffId:u},auth:{refreshTtl:300,expiresAt:O},session:{platform:b?.platform,isAssistPlatform:b?.isAssistPlatform,isShortTermToken:b?.isShortTermToken,assistId:b?.assistId,operationUserId:b?.operationUserId,operationUserName:b?.operationUserName,staffName:U,cellphone:D,isAdmin:w,deviceType:b?.deviceType,loginAccountType:b?.loginAccountType,loginTime:b?.loginTime,expTime:O||b?.expTime,sourceChannel:g}};return Pv(j,$.enterprisesDir),j}async function nq($,i=Yn){let v=await Q$.get(`${i}/cloud-auth/public/auth/list-corporations`,{headers:{"cloud-auth-token":$}}).json();if(!v.data?.items)throw new g$(v.errorMessage||"获取企业列表失败");return[...v.data.items||[],...v.data.externalItems||[]].map((n)=>lQ.parse(n))}async function JJ($,i,v,u=tQ,n=Yn){let b=await Q$.post(`${n}/cloud-auth/public/auth/switch-corporation`,{headers:{"cloud-auth-token":$},json:{corporationId:i.corporationId,userId:i.userId,cluster:i.cluster}}).json(),I=b.data?.accessToken;if(!I)throw new g$(b.errorMessage||`切换到企业 ${i.corporationName} 失败`);let U=await Q$.post(`${u}/api/idp/public/oauth2/token`,{json:{clientId:i.clientId||"whispered-app",grantType:"authorization_code",code:I,withIdToken:!1}}).json();if(!U.access_token)throw new g$(`换取企业 ${i.corporationName} 访问令牌失败`);let D={id:i.corporationId,name:i.corporationName,corpId:i.corporationId,userId:i.userId,staffId:i.staffId,baseUrl:i.baseUrl||"https://app.ekuaibao.com",source:"account",accountId:v,credentials:{accessToken:U.access_token,corpId:i.corporationId,staffId:i.staffId},auth:{refreshTtl:300,refreshToken:U.refresh_token,expiresAt:Date.now()+U.expires_in*1000}};return{accessToken:U.access_token,refreshToken:U.refresh_token,expiresIn:U.expires_in,corpConfig:D}}async function XJ($,i=Yn,v=tQ){let u=$.accountId?WJ($.accountId):Vv();if(!u?.cloudAuthToken)return!1;try{let n={corporationId:$.corpId||$.credentials.corpId,corporationName:$.name,cluster:"app",clientId:"whispered-app",staffId:$.staffId||$.credentials.staffId,userId:$.userId||u.userId||"",baseUrl:$.baseUrl||"https://app.ekuaibao.com",external:!1,needAuth:!1},b=await JJ(u.cloudAuthToken,n,$.accountId,v,i);if($.credentials.accessToken=b.accessToken,!$.auth)$.auth={refreshTtl:300};return $.auth.refreshToken=b.refreshToken,$.auth.expiresAt=Date.now()+b.expiresIn*1000,Pv($),!0}catch(n){return console.warn(`[auth] 自动续杯刷新企业 ${$.name} 失败:`,n instanceof Error?n.message:String(n)),!1}}async function rQ($){let{cloudAuthToken:i}=await sV($),v=A6($.phone,$.areaCode);return g0(v,i,$)}async function fQ($){let{cloudAuthToken:i}=await $q($),v=A6($.phone,$.areaCode);return g0(v,i,$)}async function xQ($={}){let{cloudAuthToken:i,activeSession:v}=await iq($);if(i)return g0("browser_session",i,$);if(v){let u={id:v.corpId,name:"当前浏览器企业",baseUrl:"https://app.ekuaibao.com",source:"browser",credentials:{accessToken:v.accessToken,corpId:v.corpId,staffId:v.staffId||`${v.corpId}:admin`}};return Pv(u,$.enterprisesDir),{selectedCorp:u,allCorps:[u],cloudAuthToken:"",accountId:"browser_ Line truncated
`)}function Y$($,i){if(i.length===0)return` (暂无数据)
`;let v=i.map((U)=>U.map((D)=>String(D??""))),u=$.map((U,D)=>{let w=Math.max(...v.map((g)=>(g[D]||"").length),0);return Math.max(U.length,w)}),n=$.map((U,D)=>U.padEnd(u[D])).join(" "),b=u.map((U)=>"-".repeat(U)).join(" "),I=v.map((U)=>U.map((D,w)=>D.padEnd(u[w])).join(" "));return[n,b,...I].map((U)=>` ${U}`).join(`
`)}function KJ(){return`
合思/易快报企业级 CLI 工具 (hose-use) v${E}
用法:
hose-use <命令域> <子命令> [参数] [选项]
核心命令域:
auth 认证与凭证管理 (login, status, refresh, import, accounts)
corps 多企业租户管理 (list, switch, current)
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
workflow 工作流管理 (list, get, find, toggle)
bill 单据与费用明细检索 (list, get <单号|ID>, schema, link <单号|ID>)
contact 企业通讯录与人员检索 (list, search <关键词>, get <staffId>)
platform 自建应用管理 (list)
skill Agent Skill 管理 (install, status, dump)
probe 连通性诊断 (probe [corpId])
update 版本自更新与发布记录 (update, update check, update --changelog)
openapi OpenAPI 3.1.0 规范导出 (openapi, openapi --raw, openapi paths, openapi info)
http 启动轻量 HTTP Server 与交互式文档 (http [--port=8888] [--host=127.0.0.1])
service 常驻守护进程管理 (service start|stop|restart|status|logs)
mcp MCP Server 运行 (serve)
version 查看版本信息
全局选项:
--corp=<id> 临时指定操作的企业/身份 ID (覆盖默认企业)
--json, -j 以 JSON 结构化输出结果 (适合脚本/流水线集成)
--output-file, -o 将大体积结果直接转储至本地文件并输出精简摘要
--full 允许全量输出大体积 JSON (绕过 200KB 防爆拦截)
--stateless 单次强制以无状态模式执行
--stateful 单次强制以有状态模式执行
--help, -h 查看帮助信息
常用示例:
hose-use auth login --phone=177... --password=... # 纯 API 账密自动登录
hose-use auth status # 查看当前登录状态与活跃企业
hose-use config paths # 查看多级企业配置目录链
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
hose-use corps list # 列出名下所有企业
hose-use corps switch ID01MCcOgJl1td # 切换工作企业
hose-use contact search 张三 # 模糊搜索员工工号、邮箱与电话
hose-use contact list --limit=20 # 采样查看企业通讯录(带防爆截断保护)
hose-use workflow list # 汇总查看全部工作流
hose-use workflow find --task=code-js2 # 搜索包含自定义脚本的工作流
hose-use bill list # 查看当前企业单据与报销列表
hose-use bill link CL20260901001 # 获取单据 Web 详情直达免密跳转链接
hose-use bill list --json -o /tmp/bills.json # 导出单据报文到本地磁盘并防爆
hose-use bill get n0GMIM0dkQmKbS # 根据单号精准查询单据结构化详情
hose-use http --port=8888 # 启动本地 HTTP 服务与可视化交互文档
hose-use service start # 后台启动常驻守护进程服务
hose-use service status # 查看守护进程运行状态与接口地址
hose-use probe # 诊断当前企业鉴权连通性
hose-use skill install # 安装 Agent 技能到用户目录
hose-use update # 自动检查并升级到最新版本
hose-use update --changelog # 查看版本发布历史
hose-use openapi paths # 查看所有 API 路径与概要一览
hose-use openapi --raw # 导出原生下游全量 OpenAPI 规范
`.trim()}import rq from"readline";function XY($={}){let i=Hv(),v=Qn(),u=$.stateless?!1:$.stateful?!0:v.stateful,n=new b6(i,{stateful:u,defaultCorpId:v.defaultCorpId}),b=null;try{b=n.resolve($.corpId,i0())}catch{b=null}return{corpContext:n,selectedCorp:b,jsonMode:$.jsonMode??!1,outputOptions:$.outputOptions,appRoot:$.appRoot,entryFile:$.entryFile,launcher:$.launcher}}async function Bi($){let i=await x$($),{client:v}=await ei($);return{corp:$,ekbClient:i,easoClient:v}}function Si($){let i=rq.createInterface({input:process.stdin,output:process.stdout});return new Promise((v)=>{i.question($,(u)=>{i.close(),v(u.trim())})})}async function OY($,i){let v=$.action||"status";switch(v){case"login":return fq($,i);case"status":case"whoami":return xq($,i);case"refresh":return yq($,i);case"import":return cq($,i);case"accounts":return hq($,i);case"switch-account":return mq($,i);default:return{stdout:"",stderr:`未知 auth 子命令: ${v}。支持: login, status, refresh, import, accounts, switch-account
`,exitCode:1}}}async function fq($,i){let v=m($.options,["phone","p"]),u=m($.options,["password","pwd"]),n=W$($.options,["sms"]),b=W$($.options,["sync"]),I=W$($.options,["interactive","i"])||!v&&!u&&!n&&!b;if(b){let X=await xQ({saveAll:!0});if(i.jsonMode)return{stdout:l(X),stderr:"",exitCode:0};return{stdout:`[SUCCESS] 成功从浏览器会话同步企业凭证!
默认企业: ${X.selectedCorp.name} (${X.selectedCorp.id})
共保存企业: ${X.allCorps.length} 家
`,stderr:"",exitCode:0}}if(n){let X=v||await Si("请输入手机号: ");if(!X)return{stdout:"",stderr:`手机号不能为空
`,exitCode:1};let O;try{O=(await RQ({phone:X})).codeId,console.log("短信验证码已发送!")}catch(N){console.log("若触发了人机验证,请在浏览器中获取验证码后直接在下方输入。")}let j=await Si("请输入收到的 6 位短信验证码: ");if(!j)return{stdout:"",stderr:`验证码不能为空
`,exitCode:1};let G=await fQ({phone:X,code:j,codeId:O,saveAll:!0});if(i.jsonMode)return{stdout:l(G),stderr:"",exitCode:0};return{stdout:`[SUCCESS] 短信验证码登录成功!
账号: ${G.accountId}
默认企业: ${G.selectedCorp.name} (${G.selectedCorp.id})
共保存企业: ${G.allCorps.length} 家
`,stderr:"",exitCode:0}}let U=v||(I?await Si("请输入手机号: "):""),D=u||(I?await Si("请输入密码: "):"");if(!U||!D)return{stdout:"",stderr:`手机号和密码不能为空
`,exitCode:1};let w=await rQ({phone:U,password:D,saveAll:!0});if(i.jsonMode)return{stdout:l(w),stderr:"",exitCode:0};let g=w.allCorps.map((X,O)=>[O+1,X.id,X.name,X.credentials.staffId]),J=Y$(["#","企业 ID","企业名称","员工工号"],g);return{stdout:`[SUCCESS] 账密登录成功!
账号: ${w.accountId}
默认企业: ${w.selectedCorp.name} (${w.selectedCorp.id})
共保存企业配置: ${w.allCorps.length} 家
${J}
`,stderr:"",exitCode:0}}async function xq($,i){let v=i.selectedCorp,u=Vv(),n=!1,b=null;if(v)try{let g=await(await x$(v)).get("api/account/v2/session").json();n=!!g.value,b=g.value}catch{n=!1}let I={activeAccount:u?.accountId||null,currentCorp:v?{id:v.id,name:v.name,staffId:v.credentials.staffId,source:v.source,accountId:v.accountId,tokenValid:n}:null,session:b};if(i.jsonMode)return{stdout:l(I),stderr:"",exitCode:0};let U={"当前活跃账号":u?.accountId||"未登录","当前激活企业":v?`${v.name} (${v.id})`:"未配置","当前员工工号":v?.credentials.staffId||"-","员工真实姓名":v?.staffName||v?.session?.staffName||"-","凭证来源类型":Nn(v?.source),"Token 有效性":n?"✅ 有效 (已通过 Session 验证)":"❌ 无效或未连接","Token 过期时间":si(v?.auth?.expiresAt||v?.session?.expTime)};if(v?.session){if(v.session.loginTime)U["会话创建时间"]=new Date(v.session.loginTime).toLocaleString("zh-CN",{hour12:!1});if(v.session.platform)U["官方平台类型"]=v.session.platform;if(v.session.isAssistPlatform){if(U["协助调试模式"]="是 (Assist Platform)",v.session.operationUserName||v.session.operationUserId)U["协助操作人员"]=`${v.session.operationUserName||""} (${v.session.operationUserId||""})`.trim();if(v.session.assistId)U["协助会话 ID"]=v.session.assistId}if(v.session.cellphone)U["绑定手机号码"]=v.session.cellphone;if(v.session.isAdmin!==void 0)U["是否企业管理"]=v.session.isAdmin?"是":"否"}return{stdout:`====== 当前登录与企业状态 ======
${J$(U)}
`,stderr:"",exitCode:0}}async function yq($,i){let v=m($.options,["account","a"]),u=await yQ(v,{saveAll:!0});if(i.jsonMode)return{stdout:l(u),stderr:"",exitCode:0};return{stdout:`[SUCCESS] 成功批量刷新账号 ${u.accountId} 下的所有企业 AccessToken!
共刷新企业: ${u.allCorps.length} 家
`,stderr:"",exitCode:0}}async function cq($,i){let v=m($.options,["raw","headers","curl"]),u=m($.options,["token","accessToken"]),n=m($.options,["corp","corpId"]),b=m($.options,["staff","staffId"]),I=m($.options,["name"]);if(!v&&!u)v=await Si("请粘贴抓包文本 / cURL 命令行 (直接回车则手动逐项输入): ");if(v){let g=CQ(v);if(g.accessToken)u=g.accessToken;if(g.corpId)n=g.corpId;if(g.staffId)b=g.staffId}if(!u)u=await Si("请输入 accessToken: ");if(!n)n=await Si("请输入 corpId: ");if(!b)b=await Si("请输入 staffId: ");if(!u||!n||!b)return{stdout:"",stderr:`accessToken, corpId, staffId 均为必填!
`,exitCode:1};let U=await _Q({accessToken:u,corpId:n,staffId:b,name:I});if(i.jsonMode)return{stdout:l(U),stderr:"",exitCode:0};let D={"企业名称":U.name,"企业 ID":U.id,"员工工号":U.credentials.staffId,"员工姓名":U.staffName||U.session?.staffName||"-","凭证来源":Nn(U.source),"过期时间":si(U.auth?.expiresAt||U.session?.expTime),"保存路径":`enterprises/${U.id}.json`};if(U.session?.isAssistPlatform){if(D["协助平台"]="是 (Assist Platform 调试授权)",U.session.operationUserName||U.session.operationUserId)D["协助操作人"]=`${U.session.operationUserName||""} (${U.session.operationUserId||""})`.trim();if(U.session.assistId)D["协助会话 ID"]=U.session.assistId}return{stdout:`[SUCCESS] 成功导入并保存企业凭证!
${J$(D)}
`,stderr:"",exitCode:0}}async function hq($,i){let v=kQ(),u=Vv();if(i.jsonMode)return{stdout:l({activeAccountId:u?.accountId,accounts:v}),stderr:"",exitCode:0};if(v.length===0)return{stdout:`暂无保存的账号,请使用 hose auth login 登录
`,stderr:"",exitCode:0};let n=v.map((I,U)=>[I.accountId===u?.accountId?`* ${U+1}`:` ${U+1}`,I.accountId,I.userId||"-",I.corporations.length,new Date(I.updatedAt).toLocaleString()]);return{stdout:`====== 本地已保存账号列表 ======
${Y$(["#","账号标识","用户 ID","关联企业数","最近更新时间"],n)}
`,stderr:"",exitCode:0}}async function mq($,i){let v=$.args[0]||m($.options,["account","a"]);if(!v)return{stdout:"",stderr:`用法: hose auth switch-account <accountId>
`,exitCode:1};if(!TQ(v))return{stdout:"",stderr:`未找到账号: ${v}
`,exitCode:1};return{stdout:`[SUCCESS] 当前活跃主账号已切换至: ${v}
`,stderr:"",exitCode:0}}async function jY($,i){let v=$.action||"list";switch(v){case"list":return oq($,i);case"switch":case"use":return dq($,i);case"current":return pq($,i);default:return{stdout:"",stderr:`未知 corps 子命令: ${v}。支持: list, switch, current
`,exitCode:1}}}async function oq($,i){let v=i.corpContext.listCorps();if(i.jsonMode)return{stdout:l({activeCorpId:i.selectedCorp?.id,corporations:v},i.outputOptions),stderr:"",exitCode:0};if(v.length===0)return{stdout:`未找到任何企业配置,请先运行 hose auth login
`,stderr:"",exitCode:0};let u=v.map((b,I)=>[b.current?`* ${I+1}`:` ${I+1}`,b.id,b.name,b.staffId,b.source||"manual",si(b.expiresAt),b.accountId||"-"]),n=Y$(["#","企业 ID","企业名称","员工工号","来源","Token 过期时间","所属账号"],u);return{stdout:`====== 已配置企业列表 (${v.length} 家) ======
${n}
提示: 使用 hose corps switch <企业ID> 切换工作企业
`,stderr:"",exitCode:0}}async function dq($,i){let v=$.args[0];if(!v)return{stdout:"",stderr:`用法: hose corps switch <企业ID>
`,exitCode:1};if(!i.corpContext.switchCorp(v))return{stdout:"",stderr:`企业 ${v} 不存在或未配置。可运行 hose corps list 查看可用列表。
`,exitCode:1};let n=i.corpContext.getCurrent();if(i.jsonMode)return{stdout:l(n,i.outputOptions),stderr:"",exitCode:0};return{stdout:`[SUCCESS] 已切换到企业: ${n?.name} (${n?.id})
`,stderr:"",exitCode:0}}async function pq($,i){let v=i.selectedCorp;if(!v)return{stdout:"",stderr:`未选中任何企业
`,exitCode:1};if(i.jsonMode)return{stdout:l(v,i.outputOptions),stderr:"",exitCode:0};let u={"企业 ID":v.id,"企业名称":v.name,"员工工号":v.credentials.staffId,"员工姓名":v.staffName||v.session?.staffName||"-","凭证来源":Nn(v.source),"Token 过期时间":si(v.auth?.expiresAt||v.session?.expTime),"所属账号":v.accountId||"-","主站地址":v.baseUrl||"https://app.ekuaibao.com"};if(v.session){if(v.session.loginTime)u["会话创建时间"]=new Date(v.session.loginTime).toLocaleString("zh-CN",{hour12:!1});if(v.session.platform)u["官方平台类型"]=v.session.platform;if(v.session.isAssistPlatform){if(u["协助登录模式"]="是 (Assist Platform)",v.session.operationUserName||v.session.operationUserId)u["协助操作人员"]=`${v.session.operationUserName||""} (${v.session.operationUserId||""})`.trim();if(v.session.assistId)u["协助会话 ID"]=v.session.assistId}if(v.session.cellphone)u["绑定手机号码"]=v.session.cellphone;if(v.session.isAdmin!==void 0)u["是否企业管理"]=v.session.isAdmin?"是":"否"}return{stdout:`====== 当前激活企业 ======
${J$(u)}
`,stderr:"",exitCode:0}}async function AY($,i){let v=$.action||"show";switch(v){case"show":case"get":case"list":return aq($,i);case"paths":case"path":case"dirs":return $M($,i);case"mode":return eq($,i);case"set":return sq($,i);default:return{stdout:"",stderr:`未知 config 子命令: ${v}。支持: show, paths, mode <stateful|stateless>, set <key> <val>
`,exitCode:1}}}async function aq($,i){let v=Qn(),u=i.selectedCorp,n=n0(),b={mode:v.stateful?"stateful":"stateless",stateful:v.stateful,defaultCorpId:v.defaultCorpId||null,defaultAccountId:v.defaultAccountId||null,activeCorp:u?{id:u.id,name:u.name}:null,configFile:n};if(i.jsonMode)return{stdout:l(b),stderr:"",exitCode:0};return{stdout:`====== 全局运行配置 ======
${J$({"运行模式 (Mode)":v.stateful?"有状态模式 (Stateful - 自动记忆默认企业)":"无状态模式 (Stateless - 每次需显式传 --corp)","默认工作企业":v.defaultCorpId||"未设置 (使用首个可用企业)","当前解析企业":u?`${u.name} (${u.id})`:"无","配置文件路径":n})}
提示:
切换模式: hose config mode <stateful|stateless>
指定企业: hose corps switch <corpId>
`,stderr:"",exitCode:0}}async function eq($,i){let v=$.args[0]?.toLowerCase();if(!v||v!=="stateful"&&v!=="stateless")return{stdout:"",stderr:`用法: hose config mode <stateful|stateless>
`,exitCode:1};let u=v==="stateful",n=u6({stateful:u});if(i.jsonMode)return{stdout:l(n),stderr:"",exitCode:0};return{stdout:`[SUCCESS] 全局运行模式已切换为: ${u?"有状态模式 (Stateful)":"无状态模式 (Stateless)"}
`,stderr:"",exitCode:0}}async function sq($,i){let v=$.args[0],u=$.args[1];if(!v||u===void 0)return{stdout:"",stderr:`用法: hose config set <key> <val> (如 hose config set defaultCorpId uzU7pcWfScck00)
`,exitCode:1};let n={};if(v==="stateful")n.stateful=u==="true"||u==="1";else if(v==="defaultCorpId")n.defaultCorpId=u;else if(v==="defaultAccountId")n.defaultAccountId=u;else return{stdout:"",stderr:`不支持配置键: ${v}。支持: stateful, defaultCorpId, defaultAccountId
`,exitCode:1};let b=u6(n);if(i.jsonMode)return{stdout:l(b),stderr:"",exitCode:0};return{stdout:`[SUCCESS] 配置已更新: ${v} = ${u}
`,stderr:"",exitCode:0}}async function $M($,i){let v=process.env.HOSE_ENTERPRISES_DIR,u=process.env.HOSE_USER_ENTERPRISES_DIR,n=process.env.HOSE_CONFIG_FILE,b=aW(),I=eW(),U=n0(),D=i0(),w={configFile:U,writableDir:I,existingDirs:b,env:{HOSE_ENTERPRISES_DIR:v||null,HOSE_USER_ENTERPRISES_DIR:u||null,HOSE_CONFIG_FILE:n||null},candidates:D};if(i.jsonMode)return{stdout:l(w),stderr:"",exitCode:0};return{stdout:`====== 配置路径诊断 (Config Paths) ======
${J$({"当前生效配置文件":U,"凭证保存写入目录":I,"已发现企业目录":b.length?b.join(`
`):"无 (未发现任何有效企业目录)","环境变量指定目录":v||"未设置 (HOSE_ENTERPRISES_DIR)","全部目录候选链":D.join(`
`)})}
`,stderr:"",exitCode:0}}async function GY($,i){if(!i.selectedCorp)return{stdout:"",stderr:`未选中企业,请先通过 hose corps switch 或 --corp 指定企业
`,exitCode:1};let u=$.action||"list";switch(u){case"list":case"list-all":case"ls":return iM($,i);case"get":case"detail":case"info":return nM($,i);case"find":case"search":return vM($,i);case"toggle":return uM($,i);default:return{stdout:"",stderr:`未知 workflow 子命令: ${u}。支持: list, get, find, toggle
`,exitCode:1}}}async function iM($,i){let v=await Bi(i.selectedCorp),u=l$($.options,["page"])||1,n=l$($.options,["pageSize","size"])||50,b=await Q6(v,{page:u,pageSize:n});if(i.jsonMode)return{stdout:l(b,i.outputOptions),stderr:"",exitCode:0};if(b.workflows.length===0)return{stdout:`企业 [${i.selectedCorp.name}] 下暂无工作流
`,stderr:"",exitCode:0};let I=b.workflows.map((D,w)=>[w+1,D.id,D.pipelineName,D.platformName||D.platformId||"-",D.state===1?"\uD83D\uDFE2 启用":"⚪ 停用",D.tasks?.length??"-"]),U=Y$(["#","工作流 ID","工作流名称","所属自建应用","状态","节点数"],I);return{stdout:`====== [${i.selectedCorp.name}] 工作流列表 (共 ${b.workflows.length} 条) ======
${U}
`,stderr:"",exitCode:0}}async function nM($,i){let v=$.args[0]||m($.options,["id","pipelineId"]);if(!v)return{stdout:"",stderr:`用法: hose workflow get <pipelineId>
`,exitCode:1};let u=await Bi(i.selectedCorp),n=await Mv(u.easoClient,v);if(i.jsonMode)return{stdout:l(n,i.outputOptions),stderr:"",exitCode:0};let b=J$({"工作流 ID":n.id,"工作流名称":n.label,"状态":n.state===1?"\uD83D\uDFE2 启用":"⚪ 停用","版本号":n.version||"-","节点总数":n.tasks?.length??0}),I="";if(n.tasks&&n.tasks.length>0){let U=n.tasks.map((D,w)=>[w+1,D.name||"-",D.label||"-",D.type,D.groupName||"-"]);I=`
节点结构:
`+Y$(["#","节点标识","节点名称","类型","分组"],U)}return{stdout:`====== 工作流详情 ======
${b}
${I}
`,stderr:"",exitCode:0}}async function vM($,i){let v=m($.options,["task","taskType","type"])||$.args[0];if(!v)return{stdout:"",stderr:`用法: hose workflow find --task=<节点类型> (如 code-js2, http, condition)
`,exitCode:1};let u=await Bi(i.selectedCorp),n=W$($.options,["includeDetail","detail"]),b=l$($.options,["page"])||1,I=l$($.options,["pageSize","size"])||50,U=await iY(u,v,{page:b,pageSize:I,includeDetail:n});if(i.jsonMode)return{stdout:l(U,i.outputOptions),stderr:"",exitCode:0};if(U.workflows.length===0)return{stdout:`未找到包含节点类型 [${v}] 的工作流
`,stderr:"",exitCode:0};let D=U.workflows.map((g,J)=>[J+1,g.id,g.pipelineName,g.platformName||g.platformId||"-",g.state===1?"\uD83D\uDFE2 启用":"⚪ 停用"]),w=Y$(["#","工作流 ID","工作流名称","所属自建应用","状态"],D);return{stdout:`====== 匹配节点类型 [${v}] 的工作流 (共 ${U.workflows.length} 条) ======
${w}
`,stderr:"",exitCode:0}}async function uM($,i){let v=$.args[0]||m($.options,["id","pipelineId"]),u=m($.options,["state","s"]);if(!v||u===void 0)return{stdout:"",stderr:`用法: hose workflow toggle <pipelineId> --state=<1|0> (1启用, 0停用)
`,exitCode:1};let n=u==="1"||u==="true"?1:0,b=await Bi(i.selectedCorp),I=await sQ(b.easoClient,v,n);if(i.jsonMode)return{stdout:l(I,i.outputOptions),stderr:"",exitCode:0};return{stdout:`[SUCCESS] 工作流 ${v} 状态已更新为: ${n===1?"\uD83D\uDFE2 启用":"⚪ 停用"}
`,stderr:"",exitCode:0}}async function QY($,i){if(!i.selectedCorp)return{stdout:"",stderr:`未选中企业,请先通过 hose corps switch 或 --corp 指定企业
`,exitCode:1};let u=$.action||"list";switch(u){case"list":case"ls":return bM($,i);default:return{stdout:"",stderr:`未知 platform 子命令: ${u}。支持: list
`,exitCode:1}}}async function bM($,i){let v=await Bi(i.selectedCorp),u=await qv(v.ekbClient,i.selectedCorp.credentials.corpId);if(i.jsonMode)return{stdout:l(u,i.outputOptions),stderr:"",exitCode:0};if(u.length===0)return{stdout:`企业 [${i.selectedCorp.name}] 下暂无自建应用
`,stderr:"",exitCode:0};let n=u.map((I,U)=>[U+1,I.id,I.name,I.active?"\uD83D\uDFE2 已启用":"⚪ 未启用"]),b=Y$(["#","自建应用 ID","应用名称","状态"],n);return{stdout:`====== [${i.selectedCorp.name}] 自建应用列表 (共 ${u.length} 个) ======
${b}
`,stderr:"",exitCode:0}}import{existsSync as PJ}from"node:fs";import{join as K6}from"node:path";import{mkdirSync as FY,writeFileSync as XM}from"node:fs";import{homedir as A0}from"node:os";import{dirname as OM,join as N6}from"node:path";var YY=`---
name: hose-use
description: "v0.5.1: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据费用检索与下钻、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
metadata:
version: 0.5.1
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.5.1)
---
# hose-use (v0.5.2)
在具备 MCP 的 AI 智能体环境中,**优先使用 \`hose_cli\` 单工具网关**,传入 \`command: string\` 执行;在终端或自动化脚本中,直接调用全局 \`hose\` 或 \`hose-use\` 命令行。
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(\`references/*.md\`)。
---
## Agent 执行原则 (First Rules)
1. **通道自适应**:将 CLI/MCP 视为 Agent 的执行通道,而不是要求用户学习命令行。Agent 应主动将用户的自然语言诉求转换为具体的 CLI 命令;严禁要求用户手动拼装命令行参数。
2. **多租户优先探查**:在需要企业参数前,优先执行 \`hose corps list\`。如果目标企业已配置,通过企业名称映射出对应的 \`id\` 并作为 \`--corp=<id>\` 传入;不要向普通用户询问底层 \`corpId\`。
3. **输出防护与大报文处理**:
- 面对单据明细、实体字典、工作流等大数据量查询,优先使用 \`--json -o <path>\` 本地转储或使用 \`--limit\` 限制分页;
- 严禁盲目使用 \`--full\` 将上万行原始报文一次性塞入上下文;
- 永远解析 JSON stdout,不要从格式化表格的终端字符中正则刮取数据。
4. **无状态与并发安全**:Agent 在自动化批处理或会话中,建议使用无状态模式(添加 \`--stateless\` 或显式指定 \`--corp=<id>\`),避免多任务并发切换全局状态发生冲突。
---
## 意图路由导航 (Route By Intent)
| 用户意图 / 场景 | 推荐命令 | 深入参考文档 |
|---|---|---|
| 首次登录 / 账密认证 / Token过期 / 多账号 | \`hose auth login\`, \`hose auth status\`, \`hose auth refresh\` | [references/auth.md](references/auth.md) |
| 代客协助凭证导入 / 探针连通性诊断 | \`hose auth import\`, \`hose probe\` | [references/auth.md](references/auth.md) |
| 企业租户切换 / 查看当前企业 | \`hose corps list\`, \`hose corps switch <id>\` | [references/auth.md](references/auth.md) |
| 报销单据检索 / 费用明细下钻 / 中文字典 | \`hose bill list\`, \`hose bill get <单号|ID>\` | [references/bill.md](references/bill.md) |
| 单据 Web 详情直达链接生成 | \`hose bill link <单号|ID>\` | [references/bill.md](references/bill.md) |
| 单据实体模型与字段元数据查询 | \`hose bill schema\` | [references/bill.md](references/bill.md) |
| 企业通讯录检索 / 员工档案 / 防爆保护 | \`hose contact search\`, \`hose contact list\`, \`hose contact get\` | [references/contact.md](references/contact.md) |
| 跨自建应用工作流聚合检索 | \`hose workflow list\`, \`hose platform list\` | [references/workflow.md](references/workflow.md) |
| 特定任务节点扫描 (如脚本/Webhook) | \`hose workflow find --task=code-js2\` | [references/workflow.md](references/workflow.md) |
| 工作流详情与开通切换 | \`hose workflow get\`, \`hose workflow toggle\` | [references/workflow.md](references/workflow.md) |
| 常驻守护进程管理 / 后台运行 | \`hose service start\`, \`hose service status\` | [references/service.md](references/service.md) |
| 启动本地 HTTP 服务 / 打开可视化交互文档 | \`hose http --port=8888\` (访问 \`/docs\`) | [references/service.md](references/service.md) |
| CLI 同进程执行网关 / REST 接口调用 | \`POST /api/cli\`, \`GET /v1/corps\` | [references/service.md](references/service.md) |
| 导出标准 OpenAPI 3.1.0 JSON 规范 | \`hose openapi\`, \`hose openapi --raw\` | [references/service.md](references/service.md) |
| 一键自动自更新 / 查看版本发布日志 | \`hose update\`, \`hose update --changelog\` | \`hose update --help\` |
---
## 常用命令速查
\`\`\`bash
# 1. 认证与企业
hose auth login --phone=17718556446 --password=... # 纯 API 账密自动登录
hose auth status # 查看 Token 剩余有效期与登录账号
hose corps list # 查看企业租户列表
hose corps switch ID01MCcOgJl1td # 切换工作企业
hose probe # 诊断当前企业接口连通性
# 2. 企业通讯录与人员 (默认严格防爆限流,优先 search)
hose contact search 王硕 # 模糊搜索员工工号、邮箱与电话
hose contact list --limit=20 # 采样查看企业通讯录(带防爆截断保护)
hose contact list --json -o /tmp/staffs.json # 导出全量通讯录至本地磁盘并防爆
hose contact get ID01MCcOgJl1td:3LsanKdS7Uo000 # 精准获取指定员工档案
# 3. 单据与费用
hose bill list # 查看最新单据与报销记录
hose bill link CL20260901001 # 生成官方 Web 详情直达免密跳转链接
hose bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘
hose bill get n0GMIM0dkQmKbS # 精准查询单据详情 (中文字段映射)
hose bill schema # 查询单据实体元数据字典
# 4. 自建应用与工作流
hose platform list # 查看自建应用列表
hose workflow list # 聚合扫描全部应用下的工作流
hose workflow find --task=code-js2 # 查找部署了代码节点的工作流
hose workflow get wf_01k83y... # 查看指定工作流节点拓扑
# 5. 服务与守护进程
hose http --port=8888 # 启动前台 HTTP 服务与交互式文档
hose service start # 后台启动常驻守护进程服务
hose service status # 查看常驻守护进程运行状态与端点
hose service logs # 查看常驻守护进程日志
hose service stop # 停止后台常驻守护进程
\`\`\`
---
## 全局选项
- \`--corp=<id>\`:临时指定操作的企业 ID(单次覆盖默认企业)
- \`--json\`, \`-j\`:以标准 JSON 结构化输出结果
- \`--output-file, -o <path>\`:将结果直接安全写入本地文件,仅返回精简摘要
- \`--full\`:全量输出大报文(绕过 200KB 体积防爆拦截)
- \`--stateless\`:单次命令强制以无状态模式执行
- \`--stateful\`:单次命令强制以有状态模式执行
- \`--help, -h\`:查看命令帮助与参数说明
`;var NY=`schema_version: "v1"
name: "hose-use"
description: "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业多租户切换、单据明细检索、自建应用工作流管理、内置 HTTP 服务与常驻守护进程。"
auth:
type: "none"
tools:
- name: "hose_cli"
description: "执行合思/易快报 hose-use CLI 命令。详细命令语法请参考 hose-use skill 文档。"
parameters:
type: "object"
properties:
command:
type: "string"
description: "完整的 hose-use 命令字符串,例如 'bill list --json', 'workflow find --task=code-js2', 'service status'"
required:
- "command"
`;var LY="# 认证、多租户与运行模式指南 (Authentication & Multi-Tenant Guide)\n\n本参考专卷详细说明 `hose-use` 的登录鉴权、会话维护、代客凭证、企业租户切换以及全局运行模式。\n\n---\n\n## 1. 账号认证与登录 (`auth`)\n\n`hose-use` 实现了**纯 API 级 RSA 密码加密登录**,无需通过浏览器抓包或人工复制 Cookie。\n\n### 纯 API 账密自动登录\n```bash\n# 自动通过公钥加密密码,登录并拉取名下全部企业凭据写入本地配置\nhose-use auth login --phone=17718556446 --password=YourPassword123\n```\n- **核心逻辑**:向合思主站请求 RSA 公钥,将密码密文提交到 `/api/auth/login`;成功后自动遍历用户关联的企业租户,调用换票接口写入对应的企业配置。\n\n### 查看登录状态与 Token 有效期\n```bash\nhose-use auth status\n```\n- 自动计算并输出自然语言剩余有效期(如 `29天23小时后过期`),清晰展示当前账号与当前企业。\n\n### 30 天无感 Token 刷新\n```bash\nhose-use auth refresh\n```\n- 主动调用主站会话刷新接口,续期当前企业凭据的 AccessToken。\n\n### 代客协助凭证导入\n```bash\nhose-use auth import \\\n --name=\"CSM代客\" \\\n --corp-id=\"Cxa3oOtQi2eS$g\" \\\n --staff-id=\"Cxa3oOtQi2eS$g:2HQbkGx2DgnM00\" \\\n --token=\"1361c470-3d7c-4a3a-a1fb-e946aee5723b\"\n```\n- **智能探测机制**:若 `corp-id` 包含 `$UNITY` 或特殊字符,系统会自动探测代客服务会话接口,解析 13 位过期毫秒时间戳并正确建立凭证映射。\n\n### 多账号清单\n```bash\nhose-use auth accounts\n```\n- 查看本地已记录的手机号多账号清单及其关联的企业列表。\n\n---\n\n## 2. 企业租户管理 (`corps`)\n\n### 列出所有企业\n```bash\nhose-use corps list\nhose-use corps list --json\n```\n\n### 切换当前活跃企业\n```bash\nhose-use corps switch uzU7pcWfScck00\n```\n- 在有状态(stateful)模式下,此命令将更新全局默认企业 ID。\n\n### 查看当前企业\n```bash\nhose-use corps current\n```\n\n---\n\n## 3. 全局配置与模式管理 (`config`)\n\n### 运行模式(有状态 vs 无状态)\n- **有状态模式 (Stateful,默认)**:\n - 会话状态保存在 `~/.config/hose-use/config.json` 中;\n - 执行 `corps switch` 后,后续命令自动继承当前选中的企业。\n- **无状态模式 (Stateless,推荐给 Agent)**:\n - 不依赖全局状态切换,所有命令通过 `--corp=<id>` 显式指定,防止并发操作相互干扰;\n - 通过环境变量 `HOSE_STATELESS=1` 或单次参数 `--stateless` 开启。\n\n```bash\n# 查看当前配置\nhose-use config show\n\n# 查看多层级配置发现路径诊断\nhose-use config paths\n\n# 切换全局运行模式\nhose-use config mode stateless\nhose-use config mode stateful\n```\n\n### 多层级配置发现顺序\n1. 环境变量 `HOSE_ENTERPRISES_DIR`(最高优先级)\n2. 当前工作区根目录下的 `enterprises/`\n3. 用户主目录配置:`~/.config/hose-use/enterprises/`\n4. 历史兼容缓存:`~/.cache/ekb-mcp/enterprises/`\n\n---\n\n## 4. 连通性探针 (`probe`)\n\n```bash\n# 诊断当前企业的鉴权链路与平台可用性\nhose-use probe\n\n# 诊断指定企业的连通性\nhose-use probe --corp=uzU7pcWfScck00\n```\n- **探针行为**:\n 1. 验证主站 Session 是否有效;\n 2. 测试 EASO 平台 SSO 握手是否成功;\n 3. 输出各环节毫秒级延迟与 HTTP 状态。\n";var KY="# 单据与费用明细指南 (Bill & Expense Guide)\n\n本参考专卷详细说明合思单据检索、费用报销明细下钻、中文标签映射字典以及大报文防爆机制。\n\n---\n\n## 1. 单据列表检索 (`bill list`)\n\n### 基础查询\n```bash\n# 查看当前企业最近的单据与报销列表 (默认表格格式)\nhose-use bill list\n\n# 指定企业查询并以 JSON 输出\nhose-use bill list --corp=uzU7pcWfScck00 --json\n```\n\n### 过滤选项\n- `--type=<type>`:按单据大类过滤(如 `TRAVEL_EXPENSE` 差旅报销、`DAILY_EXPENSE` 日常报销、`BORROW` 借款申请、`LOAN` 借款申请等);\n- `--status=<status>`:按审批状态过滤(如 `APPROVED` 审批完成、`PROCESSING` 审批中、`REJECTED` 已驳回、`DRAFT` 草稿等);\n- `--limit=<number>`:单页数量(默认 20,最大 100);\n- `--page=<number>`:分页页码(默认 1)。\n\n```bash\n# 查询审批通过的差旅报销单\nhose-use bill list --type=TRAVEL_EXPENSE --status=APPROVED --limit=50\n```\n\n---\n\n## 2. 单据详情精准下钻 (`bill get`)\n\n支持传入**单据编号**(如 `CL20260903001`)或合思全局**单据 ID**(如 `n0GMIM0dkQmKbS`):\n\n```bash\nhose-use bill get n0GMIM0dkQmKbS\nhose-use bill get CL20260903001 --json\n```\n\n### 中文字段智能映射字典\n合思底层原生单据接口通常返回类似 `c0_1`, `d1_4`, `u_fee_amount` 等混淆字段。\n`hose-use` 内置**动态中文 LabeLine truncated
本参考专卷详细说明合思自建应用(EASO 开放平台)的工作流跨域扫描、任务节点聚合检索与自动化开通。
---
## 1. 自建应用管理 (\`platform\`)
合思企业支持创建多个自建应用,每个应用承载独立的业务流程与工作流。
\`\`\`bash
# 列出当前企业下全部已开通的自建应用
hose-use platform list
hose-use platform list --json
\`\`\`
**输出关键字段**:
- \`appId\`:应用全局唯一标识
- \`appName\`:应用中文名称
- \`status\`:应用运行状态(ENABLE / DISABLE)
- \`createdAt\` / \`updatedAt\`:创建与最后更新时间
---
## 2. 跨应用工作流聚合检索 (\`workflow list\`)
合思官方后台一次只能查看单个自建应用的工作流。\`hose-use\` 实现了跨应用并发聚合扫描:
\`\`\`bash
# 查看所有自建应用下的全部工作流汇总
hose-use workflow list
# 查看指定自建应用下的工作流
hose-use workflow list --app-id=app_01j72x...
\`\`\`
---
## 3. 工作流任务节点精准扫描 (\`workflow find\`)
用于快速定位企业中部署了特定逻辑节点(如自定义 JS 脚本、飞书推送、钉钉同步等)的工作流:
\`\`\`bash
# 搜索包含自定义代码节点 (code-js2) 的所有工作流
hose-use workflow find --task=code-js2
# 搜索包含飞书通知节点的工作流
hose-use workflow find --task=feishu-notify
# 模糊搜索包含关键词的工作流
hose-use workflow find --keyword="自动审批"
\`\`\`
---
## 4. 工作流详情查询 (\`workflow get\`)
获取工作流的完整节点拓扑、参数配置与表达式定义:
\`\`\`bash
hose-use workflow get wf_01k83y...
hose-use workflow get wf_01k83y... --json -o /tmp/workflow_detail.json
\`\`\`
---
## 5. 工作流启用与关闭 (\`workflow toggle\`)
\`\`\`bash
# 激活/启用指定工作流
hose-use workflow toggle wf_01k83y... --enable
# 停用指定工作流
hose-use workflow toggle wf_01k83y... --disable
\`\`\`
`;var HY=`# 服务、守护进程与 API 网关指南 (Service & HTTP Gateway Guide)
本参考专卷详细说明 \`hose-use\` 内置的轻量 HTTP Server、常驻 Service 守护进程、Scalar 交互式文档以及 OpenAPI 规范导出能力。
---
## 1. 常驻 Service 守护进程 (\`service\`)
常驻守护进程允许 \`hose-use\` 在后台全天候运行,支持远程/本地无子进程开销调用 CLI,同时持久化存储 PID 与运行日志。
### 常用指令
\`\`\`bash
# 启动常驻后台守护进程 (自动落盘 PID 到 ~/.config/hose-use/service.pid)
hose-use service start
# 检查常驻服务运行状态、PID、端口与访问端点
hose-use service status
# 查看常驻服务最近运行日志
hose-use service logs
# 重启常驻服务
hose-use service restart
# 优雅停止常驻服务 (清理 PID 文件)
hose-use service stop
# 容器/前台守护运行模式 (供 Dockerfile 或 Supervisor 使用)
hose-use service run
\`\`\`
### 自愈保护机制
每次执行 \`service status\` 或 \`service start\` 时,系统会自动探测记录的 PID:
- 若进程已终止(孤儿 PID)或 PID 被其它非 \`hose\` 进程复用,系统会自动执行自愈逻辑,清理失效的 PID 文件。
---
## 2. 前台 HTTP 服务 (\`http\` / \`serve\`)
在当前终端前台启动 HTTP 服务并输出直观的服务信息面板,按 \`Ctrl+C\` 即可平滑退出:
\`\`\`bash
# 启动本地 HTTP 服务 (默认端口 8888,主机 127.0.0.1)
hose-use http
# 指定自定义端口与主机
hose-use http --port=9999 --host=0.0.0.0
\`\`\`
---
## 3. HTTP 路由端点一览
| 方法 | 端点 | 说明 |
|---|---|---|
| \`GET\` | \`/\` | 服务元信息、版本号与端点导航 |
| \`GET\` | \`/health\` | 存活健康探针(返回 \`{ "status": "ok", "version": "..." }\`) |
| \`GET\` | \`/docs\` | 基于 **Scalar API Reference** 的沉浸式交互文档界面 |
| \`GET\` | \`/openapi.json\` | 包装层标准 OpenAPI 3.1.0 JSON 规范 |
| \`GET\` | \`/raw-openapi.json\` | 合思原生下游 OpenAPI 规范 |
| \`POST\` | \`/api/cli\` | **CLI 同进程执行网关**(免 spawn 子进程) |
| \`GET\` | \`/v1/corps\` | RESTful 风格企业租户列表与运行模式 |
### 同进程 CLI 执行网关 (\`POST /api/cli\`)
通过 HTTP POST 提交任意 CLI 命令字符串,在主服务进程内部直接分发执行,毫秒级响应,无需拉起 Node/Bun 子进程:
\`\`\`bash
curl -X POST http://127.0.0.1:8888/api/cli \\
-H "Content-Type: application/json" \\
-d '{"command": "corps list --json"}'
\`\`\`
**响应结构**:
\`\`\`json
{
"success": true,
"stdout": "...",
"stderr": "",
"exitCode": 0,
"data": {
"corporations": [ ... ]
}
}
\`\`\`
---
## 4. OpenAPI 规范导出 (\`openapi\`)
\`\`\`bash
# 查看所有 API 路径与概要一览
hose-use openapi paths
# 查看合思原生下游全量 API 路径
hose-use openapi --raw paths
# 查看 OpenAPI 规范元数据概览
hose-use openapi info
# 输出包装层标准 OpenAPI 3.1.0 JSON (适合导入 Postman/Swagger/Apifox)
hose-use openapi
# 输出原生下游全量 OpenAPI 3.1.0 JSON
hose-use openapi --raw
\`\`\`
`;var PY="# hose-use 专卷:企业通讯录与人员档案 (Contact Domain)\n\n本文件是 `skills/hose-use/` 的领域参考专卷,详述合思/易快报企业通讯录的人员检索、防爆保护机制与单人档案下钻。\n\n---\n\n## 核心设计与防爆原则\n\n企业通讯录往往包含上千乃至上万名员工。**无节制全量拉取会瞬间冲垮 Agent 上下文,导致会话熔断或崩溃。**\n\n因此,`hose-use` 遵循以下防爆安全原则:\n1. **搜索优先 (Search First)**:优先使用 `hose contact search <关键词>` 进行局部模糊匹配(仅返回 1~5 条命中结果);\n2. **列表默认限流截断 (Default Limit 20)**:`hose contact list` 默认截断只输出前 20 条,并打印总人数统计和精准检索指引;\n3. **大报文转储落地 (`-o / --output-file`)**:若需全量导出通讯录供复杂分析,使用 `-o` 将全量人员安全落盘到磁盘,仅向 Agent 回传精简的文件路径元数据;\n4. **全量放行保护 (`--full`)**:仅在确定企业体量较小或明确需要全量时方可显式加上 `--full`。\n\n---\n\n## CLI 命令速查\n\n```bash\n# 1. 模糊搜索人员 (支持姓名、邮箱、手机号、staffId)\nhose contact search 王硕\nhose contact search xiezihao@hosecloud.com\nhose contact search 18600612659\n\n# 2. 采样查看企业通讯录 (默认截断前 20 条,防上下文溢出)\nhose contact list\nhose contact list --limit=50\n\n# 3. 大报文安全落地到磁盘 (返回精简文件元数据,保护 LLM 终端)\nhose contact list --json -o /tmp/all_staffs.json\n\n# 4. 精确下钻查看指定人员详细档案\nhose contact get ID01MCcOgJl1td:3LsanKdS7Uo000\n\n# 5. 指定特定企业租户检索\nhose contact search 李 --corp=ID01MCcOgJl1td\n```\n\n---\n\n## MCP 工具调用\n\n在单工具网关模式下,推荐使用 `hose_cli` 触发:\n```json\n{\n \"command\": \"contact search 王硕\"\n}\n```\n\n在全量模式(`HOSE_MCP_MODE=all`)下,提供以下细粒度工具:\n- `contact_search(keyword: string, limit?: number)`:返回匹配的员工列表\n- `contact_get(staffId: string)`:获取单条员工详情\n- `contact_list(limit?: number, allowFull?: boolean)`:带保护的企业通讯录列表\n\n---\n\n## 业务联动典型场景\n\n### 1. 查找某人发起的单据\n当用户要求“帮我查一下王硕提交的报销单”时:\n1. 先通过 `hose contact search 王硕` 获取其 `staffId`(如 `ID01MCcOgJl1td:3LsanKdS7Uo000`);\n2. 再通过 `hose bill list --keyword=王硕` 或根据 `staffId` 过滤单据明细;\n3. 获得单据后,通过 `hose bill link <单号>` 生成官方 Web 直达链接反馈给用户。\n";var BY={"SKILL.md":YY,"agents/openai.yaml":NY,"references/auth.md":LY,"references/bill.md":KY,"references/contact.md":PY,"references/workflow.md":zY,"references/service.md":HY};function SY(){return BY["SKILL.md"]||""}function L6(){return N6(A0(),".agents","skills","hose-use")}function zJ(){return[N6(A0(),".agents","skills","hose-use"),N6(A0(),".gemini","antigravity","skills","hose-use"),N6(A0(),".codex","skills","hose-use")]}function G0($=L6()){FY($,{recursive:!0});let i=[];for(let[v,u]of Object.entries(BY)){let n=N6($,v);FY(OM(n),{recursive:!0}),XM(n,u,"utf8"),i.push(v)}return{targetDir:$,files:i}}function HJ(){let $=L6();return G0($),{synced:!0,targetDir:$}}async function ZY($,i){let v=$.action||"status";switch(v){case"dump":case"cat":case"show":return{stdout:`${SY()}
`,stderr:"",exitCode:0};case"install":case"init":case"sync":{let u=W$($.options,["local"])||W$($.options,["workspace"]),n=m($.options,["dir","target"])||$.args[0],b=n?n:u?K6(process.cwd(),".agents","skills","hose-use"):L6(),I=G0(b),U=zJ();for(let D of U)if(D!==b)try{G0(D)}catch{}if(i.jsonMode)return{stdout:l({installed:!0,targetDir:I.targetDir,fileCount:I.files.length,files:I.files}),stderr:"",exitCode:0};return{stdout:`[SUCCESS] hose-use 技能已成功安装至: ${I.targetDir}
包含文件: ${I.files.join(", ")}
`,stderr:"",exitCode:0}}case"status":case"get":{let u=L6(),n=K6(process.cwd(),".agents","skills","hose-use"),b=zJ(),I={global:{dir:u,installed:PJ(K6(u,"SKILL.md"))},local:{dir:n,installed:PJ(K6(n,"SKILL.md"))},candidates:b.map((D)=>({dir:D,installed:PJ(K6(D,"SKILL.md"))}))};if(i.jsonMode)return{stdout:l(I),stderr:"",exitCode:0};return{stdout:`====== Agent Skill 状态 ======
${J$({"全局 Skill 目录":`${u} [${I.global.installed?"已安装 ✅":"未安装 ❌"}]`,"本地 Skill 目录":`${n} [${I.local.installed?"已安装 ✅":"未安装 ❌"}]`})}
提示: 运行 hose-use skill install 进行全局安装
`,stderr:"",exitCode:0}}default:return{stdout:"",stderr:`未知 skill 子命令: ${v}。支持: install, status, dump
`,exitCode:1}}}async function VY($,i){let v=i.selectedCorp;if(!v)return{stdout:"",stderr:`未配置任何企业,请先运行 hose auth login 或使用 --corp 指定
`,exitCode:1};let u={enterprise:{id:v.id,name:v.name,staffId:v.credentials.staffId,baseUrl:v.baseUrl,source:v.source,accountId:v.accountId},ekbSession:{status:"pending"},easoToken:{status:"pending"},platformAccess:{status:"pending"}};try{let I=await Bi(v);try{let U=await I.ekbClient.get("api/account/v2/session").json();u.ekbSession={status:"ok",userId:U.value?.userId,loginStaffId:U.value?.loginStaffId,expTime:U.value?.expTime?new Date(U.value.expTime).toLocaleString():void 0}}catch(U){u.ekbSession={status:"error",error:U instanceof Error?U.message:String(U)}}try{let U=await qv(I.ekbClient,v.credentials.corpId);u.platformAccess={status:"ok",totalPlatforms:U.length};let D=await eQ(I.easoClient,U[0]?.id||"platform");u.easoToken={status:"ok",message:"EASO 四步换票握手成功"}}catch(U){u.easoToken={status:"error",error:U instanceof Error?U.message:String(U)}}}catch(I){u.error=I instanceof Error?I.message:String(I)}if(i.jsonMode)return{stdout:l(u),stderr:"",exitCode:0};let n={"企业名称":v.name,"企业 ID":v.id,"员工工号":v.credentials.staffId,"员工姓名":v.staffName||v.session?.staffName||"-","凭证来源":Nn(v.source),"Token 过期时间":si(v.auth?.expiresAt||v.session?.expTime),"主站 Session 连通":u.ekbSession.status==="ok"?"\uD83D\uDFE2 正常":"\uD83D\uDD34 异常","EASO 引擎鉴权换票":u.easoToken.status==="ok"?"\uD83D\uDFE2 握手成功":"\uD83D\uDD34 失败","自建应用扫描":u.platformAccess.status==="ok"?`\uD83D\uDFE2 可访问 (${u.platformAccess.totalPlatforms} 个自建应用)`:"\uD83D\uDD34 失败"};if(v.session?.isAssistPlatform){if(n["协助操作人"]=`${v.session.operationUserName||""} (${v.session.operationUserId||""})`.trim(),v.session.assistId)n["协助会话 ID"]=v.session.assistId}return{stdout:`====== 诊断结果 (Enterprise Probe) ======
${J$(n)}
`,stderr:"",exitCode:0}}import{spawn as jM}from"child_process";import{join as AM}from"path";async function qY($,i){let v=i.appRoot||process.cwd(),u=AM(v,"src","server.ts");console.error("启动 MCP Server on stdio...");let n=jM("bun",["run",u],{stdio:"inherit",cwd:v,env:process.env});return await new Promise((b)=>{n.on("exit",()=>b())}),{stdout:"",stderr:"",exitCode:0}}import{chmodSync as QM,mkdirSync as YM,renameSync as FJ,rmSync as NM,unlinkSync as RY,writeFileSync as TY}from"node:fs";import{dirname as LM,join as lY}from"node:path";import{spawnSync as Ln}from"node:child_process";import{dirname as MY}from"node:path";import{fileURLToPath as GM}from"node:url";function z6($=process.execPath,i=import.meta.url){if(i.includes("/$bunfs/")||i.includes("\\$bunfs\\"))return!0;let v=$.toLowerCase().replace(/\\/g,"/");return!v.endsWith("/bun")&&!v.endsWith("/bun.exe")}function kY($,i=z6()){if(i)return process.cwd();let v=$||GM(import.meta.url);return MY(MY(v))}var CY="yunyingk/hose-use",KM="HOSE_USE_GITHUB_REPO";async function _Y($,i,v={}){let u=$.area==="changelog"||$.action==="changelog"||$.action==="log"||$.action==="history"||W$($.options,["changelog","log","l"]),n=$.action==="check"||W$($.options,["check","check-only","c"]),b=m($.options,["version","tag","target","t"])||(!u&&!n&&$.action&&!$.action.startsWith("-")?$.action:void 0),I=b&&b.toLowerCase()!=="latest"?b.replace(/^v/,""):void 0,U=m($.options,["repo"])||process.env[KM]?.trim()||CY,D={checkOnly:n,changelogOnly:u,limit:l$($.options,["limit","n"]),force:W$($.options,["force","f"]),targetVersion:I,repo:U},w=v.appRoot||kY(v.entryFile);if(I){let C=rY(I,E);if(C<0&&!D.force){let r=`无法降级 hose-use(当前版本 v${E},目标版本 v${I})。如需强制重装请使用 --force。`;if(i.jsonMode)return{stdout:l({updated:!1,currentVersion:E,targetVersion:I,mode:z6()?"binary":"source",message:r}),stderr:"",exitCode:1};return{stdout:"",stderr:`[ERROR] ${r}
`,exitCode:1}}if(C===0&&!D.force){let r=`hose-use 当前已是版本 v${E}。如需强制重装请添加 --force。`;if(i.jsonMode)return{stdout:l({updated:!1,currentVersion:E,targetVersion:I,mode:z6()?"binary":"source",message:r}),stderr:"",exitCode:0};return{stdout:`ℹ️ ${r}
`,stderr:"",exitCode:0}}}if(D.changelogOnly){let C=await BJ(U,D.limit??10);if(i.jsonMode)return{stdout:l({currentVersion:E,totalQueried:C.length,releases:C.map((s)=>({version:s.version,tagName:s.tagName,publishedAt:s.publishedAt,author:s.author,releaseNotes:s.notes,releaseUrl:s.htmlUrl,isCurrent:s.version===E,isNewer:Tv(s.version,E)}))}),stderr:"",exitCode:0};let r=[`====== hose-use 版本发布记录 (当前版本: v${E}) ======`,""];for(let s of C){let y$=s.version===E?" [当前版本]":Tv(s.version,E)?" [新版本 ✨]":"";if(r.push(`• v${s.version} (${s.publishedAt?s.publishedAt.slice(0,10):"未知日期"})${y$}`),s.notes){let $n=s.notes.trim().split(`
`).map((Zi)=>` ${Zi}`).join(`
`);r.push($n)}r.push("")}return{stdout:r.join(`
`),stderr:"",exitCode:0}}if(!z6()){if(D.checkOnly){let r=await BJ(U,30),s=r[0],y$=s?.version??E,$n=r.find((Di)=>Di.version===E),Zi=Tv(y$,E),Fn=r.filter((Di)=>Tv(Di.version,E));if(i.jsonMode)return{stdout:l({updated:!1,updateAvailable:Zi,currentVersion:E,currentVersionPublishedAt:$n?.publishedAt,latestVersion:y$,latestVersionPublishedAt:s?.publishedAt,behindCount:Fn.length,pendingReleases:Fn.map((Di)=>({version:Di.version,tagName:Di.tagName,publishedAt:Di.publishedAt,author:Di.author,releaseNotes:Di.notes,releaseUrl:Di.htmlUrl})),releaseNotes:s?.notes??"",releaseUrl:s?.htmlUrl??"",mode:"source",message:"当前运行于源码开发模式。运行 'hose-use update' 执行 git pull 与依赖更新。"}),stderr:"",exitCode:0};return{stdout:`====== hose-use 版本检查 ======
${J$({"运行模式":"源码开发模式 (Source Mode)","当前版本":`v${E}`,"最新版本":`v${y$} ${Zi?"(可升级 ✨)":"(已是最新 ✅)"}`,"待更新版本数":Fn.length,"源码路径":w})}
${Zi?"可运行 hose-use update 执行 git pull 与依赖同步":"已经是最新版本"}
`,stderr:"",exitCode:0}}try{tY("git",["-C",w,"pull","--ff-only"])}catch(r){let s=r instanceof Error?r.message:String(r);console.error(`git pull 提示: ${s}`)}tY("bun",["install"],{cwd:w});let C=HJ();if(i.jsonMode)return{stdout:l({updated:!0,version:E,mode:"source",skillSynced:C.synced?C.targetDir:!1}),stderr:"",exitCode:0};return{stdout:`[SUCCESS] hose-use 源码与依赖更新成功!
版本: v${E}
技能同步: ${C.synced?"已同步至全局 ✅":"未同步"}
`,stderr:"",exitCode:0}}let g=zM(),J=HM(),X=await BJ(U,30),O=I?X.find((C)=>C.version===I||C.tagName===I||C.tagName===`v${I}`)??await EY(U,I):X[0]??await EY(U);if(!O){let C=`无法从 GitHub 仓库 '${U}' 获取 Release 列表`;if(i.jsonMode)return{stdout:l({updated:!1,currentVersion:E,mode:"binary",message:C}),stderr:"",exitCode:1};return{stdout:"",stderr:`[ERROR] ${C}
`,exitCode:1}}let j=O.version,G=X.find((C)=>C.version===E),N=Tv(j,E),L=N||Boolean(D.force),B=X.filter((C)=>Tv(C.version,E));if(D.checkOnly){if(i.jsonMode)return{stdout:l({updated:!1,updateAvailable:N,currentVersion:E,currentVersionPublishedAt:G?.publishedAt,latestVersion:j,latestVersionPublishedAt:O.publishedAt,behindCount:B.length,pendingReleases:B.map((r)=>({version:r.version,tagName:r.tagName,publishedAt:r.publishedAt,author:r.author,releaseNotes:r.notes,releaseUrl:r.htmlUrl})),releaseNotes:O.notes,releaseUrl:O.htmlUrl,mode:"binary"}),stderr:"",exitCode:0};return{stdout:`====== hose-use 版本检查 ======
${J$({"运行模式":"独立二进制 (Binary Mode)","当前版本":`v${E}`,"最新版本":`v${j} ${N?"(可升级 ✨)":"(已是最新 ✅)"}`,"发布时间":O.publishedAt?O.publishedAt.slice(0,10):"未知","平台架构":`${g}-${J}`})}
${N?`运行 hose-use update 升级至 v${j}`:"已经是最新版本"}
`,stderr:"",exitCode:0}}if(!L){if(i.jsonMode)return{stdout:l({updated:!1,currentVersion:E,currentVersionPublishedAt:G?.publishedAt,latestVersion:j,latestVersionPublishedAt:O.publishedAt,mode:"binary",message:`hose-use 当前已是最新版本 (v${E})`}),stderr:"",exitCode:0};return{stdout:`ℹ️ hose-use 当前已是最新版本 (v${E})。如需重装请添加 --force。
`,stderr:"",exitCode:0}}let V=PM(O.assets,g,J);if(!V){let C=`未找到适用于 ${g}-${J} 平台的 Release 资产 (v${j})。可用文件: ${O.assets.map((r)=>r.name).join(", ")}`;if(i.jsonMode)return{stdout:l({updated:!1,error:!0,message:C}),stderr:"",exitCode:1};return{stdout:"",stderr:`[ERROR] ${C}
`,exitCode:1}}let q=process.execPath,M=LM(q),O$=lY(M,`.tmp-update-${Date.now()}`);YM(O$,{recursive:!0});try{let C=lY(O$,V.name);await FM(V.downloadUrl,C,O.tagName,V.name);let r=C;if(V.name.endsWith(".tar.gz")||V.name.endsWith(".tgz"))r=BM(C,O$,g);else if(V.name.endsWith(".zip"))r=SM(C,O$,g);if(QM(r,493),process.platform==="darwin")try{Ln("/usr/bin/codesign",["--remove-signature",r],{stdio:"ignore"}),Ln("/usr/bin/codesign",["--force","--sign","-",r],{stdio:"ignore"})}catch{}if(process.platform==="win32"){let y$=`${q}.old.${Date.now()}`;try{FJ(q,y$)}catch{}FJ(r,q)}else FJ(r,q);let s=HJ();if(i.jsonMode)return{stdout:l({updated:!0,fromVersion:E,toVersion:j,skillSynced:s.synced?s.targetDir:!1,mode:"binary"}),stderr:"",exitCode:0};return{stdout:`[SUCCESS] ✨ hose-use 已成功升级至 v${j}!
可执行文件: ${q}
Agent 技能: ${s.synced?"已自动同步最新版 ✅":"未同步"}
`,stderr:"",exitCode:0}}finally{try{NM(O$,{recursive:!0,force:!0})}catch{}}}function zM(){if(process.platform==="darwin")return"darwin";if(process.platform==="win32")return"windows";return"linux"}function HM(){return process.arch==="arm64"?"arm64":"x64"}async function BJ($,i=20){let v=process.env.GITHUB_TOKEN||process.env.GH_TOKEN,u={"User-Agent":`hose-use/${E}`,Accept:"application/vnd.github.v3+json",...v?{Authorization:`Bearer ${v}`}:{}},n=[`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${i}`,`https://api.github.com/repos/${$}/releases?per_page=${i}`];for(let b of n)try{let I=await fetch(b,{headers:u,signal:AbortSignal.timeout(5000)});if(!I.ok)continue;let U=await I.json();if(!Array.isArray(U)||U.length===0)continue;let D=[];for(let w of U){let g=w.tag_name??"",J=g.replace(/^v/,"");if(!J)continue;let X=(w.assets??[]).map((O)=>({name:O.name,downloadUrl:O.browser_download_url,size:O.size??0}));D.push({version:J,tagName:g,name:w.name??g,publishedAt:w.published_at,author:w.author?.login,notes:w.body??"",htmlUrl:w.html_url??"",assets:X})}if(D.length>0)return D}catch{}return[]}async function EY($,i){let v=i?i.startsWith("v")?i:`v${i}`:void 0,u=process.env.GITHUB_TOKEN||process.env.GH_TOKEN,n={"User-Agent":`hose-use/${E}`,Accept:"application/vnd.github.v3+json",...u?{Authorization:`Bearer ${u}`}:{}},b=v?[`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/tags/${v}`,`https://api.github.com/repos/${$}/releases/tags/${v}`]:["https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest",`https://api.github.com/repos/${$}/releases/latest`],I;for(let U of b)try{let D=await fetch(U,{headers:n,signal:AbortSignal.timeout(5000)});if(!D.ok)continue;let w=await D.json(),g=w.tag_name??"",J=g.replace(/^v/,"");if(!J)continue;let X=(w.assets??[]).map((j)=>({name:j.name,downloadUrl:j.browser_download_url,size:j.size??0})),O={version:J,tagName:g,name:w.name??g,publishedAt:w.published_at,author:w.author?.login,notes:w.body??"",htmlUrl:w.html_url??"",assets:X};if(X.length>0)return O;if(!I)I=O}catch{}return I}function PM($,i,v){let u={darwin:["darwin","macos","osx","apple"],linux:["linux"],windows:["windows","win32","win64",".exe"]},n={arm64:["arm64","aarch64"],x64:["x64","x86_64","amd64"]},b=u[i]||[],I=n[v]||[],U=$.filter((g)=>{let J=g.name.toLowerCase(),X=b.some((j)=>J.includes(j)),O=I.some((j)=>J.includes(j));return X&&O}),D=U.find((g)=>!g.name.endsWith(".tar.gz")&&!g.name.endsWith(".tgz")&&!g.name.endsWith(".zip")&&!g.name.endsWith(".sha256"));if(D)return D;return U.find((g)=>g.name.endsWith(".tar.gz")||g.name.endsWith(".tgz")||g.name.endsWith(".zip"))||U[0]}function Q0($){try{process.stderr.write(`${$}
`)}catch{}}async function FM($,i,v,u){let n=[],b=v?v.startsWith("v")?v:`v${v}`:void 0,I=u||$.split("/").pop()||"";if(b&&I)n.push(`https://git.ying-qing.cn/gitea/hose-use/releases/download/${b}/${I}`);if($.startsWith("https://git.ying-qing.cn"))n.push($);if(b&&I){let w=`https://github.com/${CY}/releases/download/${b}/${I}`;n.push(`https://ghfast.top/${w}`),n.push(`https://ghproxy.net/${w}`),n.push(`https://gh.ddlc.top/${w}`),n.push(`https://mirror.ghproxy.com/${w}`),n.push(w)}else if($.includes("github.com"))n.push(`https://ghfast.top/${$}`),n.push(`https://ghproxy.net/${$}`),n.push(`https://gh.ddlc.top/${$}`),n.push(`https://mirror.ghproxy.com/${$}`),n.push($);else n.push($);let U=Array.from(new Set(n)),D;for(let w=0;w<U.length;w++){let g=U[w];try{Q0(`==> [${w+1}/${U.length}] 正在下载更新: ${g}`);let J=await fetch(g,{signal:AbortSignal.timeout(6000)});if(!J.ok)throw Error(`HTTP ${J.status} ${J.statusText}`);let X=Number(J.headers.get("content-length"))||0,O=J.body?.getReader();if(!O){let B=Buffer.from(await J.arrayBuffer());if(B.length<1000)throw Error(`下载文件异常(大小仅 ${B.length} 字节)`);TY(i,B),Q0(`✓ 下载完成 (${(B.length/1024/1024).toFixed(1)} MB)`);return}let j=[],G=0,N=0;while(!0){let{done:B,value:V}=await O.read();if(B)break;if(V){j.push(V),G+=V.length;let q=Date.now();if(q-N>200){N=q;let M=X?Math.round(G/X*100):0,O$=(G/1048576).toFixed(1),C=X?(X/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ 进度: ${M}% (${O$} / ${C} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let L=Buffer.concat(j);if(L.length<1000)throw Error(`下载文件异常(大小仅 ${L.length} 字节)`);TY(i,L),Q0(`✓ 下载完成 (${(L.length/1024/1024).toFixed(1)} MB)`);return}catch(J){D=J instanceof Error?J:Error(String(J)),Q0(` ↳ 节点失败: ${D.message}`)}}throw Error(`所有下载镜像均失败: ${D?.message}`)}function BM($,i,v){let u=Ln("tar",["-xzf",$,"-C",i],{stdio:"pipe"});if(u.status!==0)throw Error(`解压 tar 归档失败: ${u.stderr.toString()}`);RY($);let n=v==="windows"?"hose-use.exe":"hose-use",b=Ln("find",[i,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),I=b.find((U)=>U.endsWith(`/${n}`)||U.endsWith(n));if(I)return I;return b[0]||$}function SM($,i,v){let u=Ln("unzip",["-q","-o",$,"-d",i],{stdio:"pipe"});if(u.status!==0)throw Error(`解压 zip 归档失败: ${u.stderr.toString()}`);RY($);let n=v==="windows"?"hose-use.exe":"hose-use",b=Ln("find",[i,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),I=b.find((U)=>U.endsWith(`/${n}`)||U.endsWith(n));if(I)return I;return b[0]||$}function rY($,i){let v=$.replace(/^v/,"").split(".").map((n)=>Number.parseInt(n,10)||0),u=i.replace(/^v/,"").split(".").map((n)=>Number.parseInt(n,10)||0);for(let n=0;n<Math.max(v.length,u.length);n++){let b=v[n]??0,I=u[n]??0;if(b>I)return 1;if(b<I)return-1}return 0}function Tv($,i){return rY($,i)>0}function tY($,i,v={}){let u=Ln($,i,{cwd:v.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(u.stdout)console.error(u.stdout.trimEnd());if(u.stderr)console.error(u.stderr.trimEnd());if(u.status!==0)throw Error(`${$} ${i.join(" ")} 执行失败 (退出码 ${u.status})`)}var fY={openapi:"3.1.0",info:{title:"hose-use API & MCP Tools Specification",version:"0.5.2",description:"Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."},servers:[{url:"http://localhost:3000",description:"Local hose-use CLI / MCP Runtime Gateway"}],tags:[{name:"Auth & SSO",description:"统一认证、多账号管理与 30 天 Token 自动无感续杯"},{name:"Corps & Tenancy",description:"多企业租户管理与工作空间切换"},{name:"Platforms",description:"自建应用检索与实例枚举"},{name:"Workflows",description:"跨自建应用工作流聚合检索、DSL 图谱与启停"},{name:"Bills & Documents",description:"费控单据、报销借款单、发票明细与 DataLink 实体字典"},{name:"Probe & Diagnostics",description:"会话有效性与 EASO 鉴权连通性诊断"}],paths:{"/api/auth/login":{post:{tags:["Auth & SSO"],summary:"纯 API 账密自动全流程登录",description:"自动拉取公钥进行 RSA PKCS#1 加密,发起统一认证中心握手并批量获取名下所有企业身份。",operationId:"authLogin",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["phone","password"],properties:{phone:{type:"string",description:"登录手机号",example:"17718556446"},password:{type:"string",description:"登录明文密码 (由客户端自动完成 RSA 加密)"},autoSwitch:{type:"boolean",description:"是否自动切换到首个企业",default:!0}}}}}},responses:{"200":{description:"登录成功",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"},totalCorps:{type:"integer"},activeCorp:{type:"object",properties:{corpId:{type:"string",description:"企业唯一标识"},corpName:{type:"string",description:"企业名称"},staffId:{type:"string",description:"员工身份 ID"},accountId:{type:"string",description:"归属账号手机号"}}}}}}}},"401":{description:"账密错误或鉴权失败",content:{"application/json":{schema:{type:"object",properties:{error:{type:"boolean",example:!0},message:{type:"string",example:"操作失败原因"}}}}}}}}},"/api/auth/status":{get:{tags:["Auth & SSO"],summary:"查看当前登录与活跃企业状态",description:"查询本地或无状态下的当前账号、工作企业与凭证有效期。",operationId:"authStatus",responses:{"200":{description:"状态正常",content:{"application/json":{schema:{type:"object",properties:{loggedIn:{type:"boolean"},activeCorpId:{type:"string"},activeCorpName:{type:"string"},totalAccounts:{type:"integer"},totalCorps:{type:"integer"}}}}}}}}},"/api/auth/refresh":{post:{tags:["Auth & SSO"],summary:"批量刷新企业 30 天 AccessToken",description:"自动无感为当前账号名下的所有企业租户更新最新 30 天访问令牌。",operationId:"authRefresh",responses:{"200":{description:"刷新完成",content:{"application/json":{schema:{type:"object",properties:{refreshed:{type:"integer"},total:{type:"integer"}}}}}}}}},"/api/corps":{get:{tags:["Corps & Tenancy"],summary:"列出当前账号名下所有已配置企业租户",description:"支持单账号管理多家企业与同一企业下的多员工身份分层展示。",operationId:"listCorps",responses:{"200":{description:"企业租户列表",content:{"application/json":{schema:{type:"array",items:{type:"object",properties:{corpId:{type:"string",description:"企业唯一标识"},corpName:{type:"string",description:"企业名称"},staffId:{type:"string",description:"员工身份 ID"},accountId:{type:"string",description:"归属账号手机号"}}}}}}}}}},"/api/corps/switch":{post:{tags:["Corps & Tenancy"],summary:"切换当前工作企业",description:"在有状态模式下切换并记忆工作企业,后续操作自动以该企业身份执行。",operationId:"switchCorp",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["corpId"],properties:{corpId:{type:"string",description:"目标企业 ID 或身份 ID (corpId@accountId)"}}}}}},responses:{"200":{description:"切换成功",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"},activeCorp:{type:"object",properties:{corpId:{type:"string",description:"企业唯一标识"},corpName:{type:"string",description:"企业名称"},staffId:{type:"string",des Line truncated
${U}
提示: 运行 hose-use openapi ${v?"--raw ":""}可直接输出完整 OpenAPI 3.1.0 JSON
`,stderr:"",exitCode:0}}case"info":case"summary":{let b=Kn(u),I=b.info||{},U=(b.servers||[]).map((X)=>`${X.url} (${X.description||"-"})`),D=(b.tags||[]).map((X)=>`${X.name}: ${X.description||""}`),w=SJ(u),g={title:I.title,version:I.version,description:I.description,type:u,totalEndpoints:w.length,servers:U,tags:D};if(i.jsonMode)return{stdout:l(g),stderr:"",exitCode:0};return{stdout:`====== OpenAPI 规范概览 ======
${J$({"规范标题":I.title,"规范版本":I.version,"规范类型":v?"原始下游原生 API (Raw Spec)":"包装层工具 API (Wrapped Spec)","接口总数":w.length,"描述信息":I.description,"服务器列表":U.join(`
`),"标签分组":D.join(`
`)})}
`,stderr:"",exitCode:0}}case"dump":case"export":case"raw":case void 0:default:{let b=Kn(u);return{stdout:`${JSON.stringify(b,null,2)}
`,stderr:"",exitCode:0}}}}async function cY($,i){let v=i.selectedCorp;if(!v)throw Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose auth login 登录。");let u=await x$(v),n=$.action?.toLowerCase(),b=v.corpId||v.id;switch(n){case"list":case"search":case void 0:{let I=m($.options,["code","c"]),U=m($.options,["keyword","k","q","query"]),D=m($.options,["stage"]),w=m($.options,["state","s"]),g=l$($.options,["count","limit","n"],20),J=await NJ(u,b,{code:I,keyword:U,stage:D,state:w,count:g});if(i.jsonMode)return{stdout:l({corpId:b,corpName:v.name,total:J.total,returned:J.returned,items:J.items},i.outputOptions),stderr:"",exitCode:0};let X=["#","单据编号 (单号)","单据名称","阶段","状态","金额","提交时间"],O=J.items.map((L,B)=>[B+1,L.billCode,L.billName,L.stage||"-",L.state||"-",L.amount||"-",L.submitDate||L.createTime||"-"]),j=Y$(X,O),G=`====== 单据与费用明细列表 (企业: ${v.name} | 总数: ${J.total} | 本次返回: ${J.returned}) ======
`,N=`
提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细
`;return{stdout:G+j+N,stderr:"",exitCode:0}}case"get":case"show":case"find":{let I=$.args[0]||m($.options,["code","id"]);if(!I)throw Error("请提供要查询的单号或单据 ID: hose-use bill get <单号|ID>");let U=await j0(u,b,I);if(U.length===0){if(i.jsonMode)return{stdout:l({found:!1,code:I,message:"未找到匹配单据"}),stderr:"",exitCode:1};return{stdout:"",stderr:`[NOT FOUND] 在企业 [${v.name}] 下未找到单号或 ID 为 [${I}] 的单据
`,exitCode:1}}if(i.jsonMode)return{stdout:l({corpId:b,corpName:v.name,count:U.length,bills:U},i.outputOptions),stderr:"",exitCode:0};let D=[];for(let w=0;w<U.length;w++){let g=U[w];if(D.push(`
====== 单据详情 [${w+1}/${U.length}] (单号: ${g.billCode}) ======`),D.push(` 单据 ID : ${g.billId}`),D.push(` 单据名称 : ${g.billName}`),g.title)D.push(` 单据标题 : ${g.title}`);if(g.stage)D.push(` 业务阶段 : ${g.stage}`);if(g.state)D.push(` 审批状态 : ${g.state}`);if(g.amount)D.push(` 单据金额 : ${g.amount}`);if(g.submitterId)D.push(` 提交人员 : ${g.submitterId}`);if(g.submitDate)D.push(` 提交时间 : ${g.submitDate}`);D.push(` 创建时间 : ${g.createTime}`),D.push(` 更新时间 : ${g.updateTime}`),D.push(`
--- 结构化表单字段明细 ---`);let J=Object.entries(g.details);if(J.length===0)D.push(" (无额外字段数据)");else{let X=Math.max(...J.map(([O])=>O.length),0);for(let[O,j]of J){let G=typeof j==="object"?JSON.stringify(j):String(j);D.push(` ${O.padEnd(X+2)}: ${G}`)}}}return{stdout:D.join(`
`)+`
`,stderr:"",exitCode:0}}case"schema":case"schemas":case"entities":{let{entities:I}=await Y6(u,b,!0);if(i.jsonMode)return{stdout:l({corpId:b,corpName:v.name,totalEntities:I.length,entities:I},i.outputOptions),stderr:"",exitCode:0};let U=["#","实体 ID","实体名称","类型","字段数"],D=I.map((J,X)=>[X+1,J.id,J.name||"-",J.type||"-",J.fields.length]),w=Y$(U,D);return{stdout:`====== 单据实体与数据模型字典 (企业: ${v.name} | 共 ${I.length} 个实体) ======
`+w+`
`,stderr:"",exitCode:0}}case"link":case"url":{let I=$.args[0]||m($.options,["code","id","c"]);if(!I)return{stdout:"",stderr:"用法: hose bill link <单号或ID>",exitCode:1};let U=await j0(u,b,I);if(!U||U.length===0)return{stdout:"",stderr:`未找到单据: ${I}`,exitCode:1};let D=U[0],w=D.billId,g=D.billCode||I,X=`${(v.baseUrl||"https://app.ekuaibao.com").replace(/\/+$/,"")}/#/invoice/detail?id=${encodeURIComponent(w)}&corporationId=${encodeURIComponent(b)}`;if(i.jsonMode)return{stdout:l({code:g,id:w,corpId:b,corpName:v.name,url:X},i.outputOptions),stderr:"",exitCode:0};return{stdout:["====== 合思单据 Web 直达链接 ======",` 单据编号: ${g}`,` 单据 ID : ${w}`,` 所属企业: ${v.name} (${b})`," 直达链接:",` ${X}`,"",`Markdown 链接: [查看单据 ${g}](${X})`].join(`
`)+`
`,stderr:"",exitCode:0}}default:throw Error(`未知 bill 子命令: ${n}。支持: list, get <单号>, schema, link <单号>`)}}var hY=W.object({id:W.string(),name:W.string(),email:W.string().nullable().optional(),cellphone:W.string().nullable().optional(),department:W.string().nullable().optional()});async function Y0($,i=!1){let u=await(await $.get("api/easo/common/staffs",{searchParams:{external:String(i)}})).json();return W.array(hY).parse(u.data??[])}var N0=20;async function ZJ($,i={}){let{client:v}=await ei($),u=await Y0(v,i.external??!1),n=u.length,I=i.allowFull===!0?n:i.limit??N0,U=u.slice(0,I),D=n>U.length;return{total:n,limit:I,hasMore:D,hint:D?`企业员工共 ${n} 人,当前仅展示前 ${U.length} 条以防止上下文溢出。可使用 'hose contact search <姓名|工号>' 精准检索,或附加 '--limit <数量>' / '-o <文件路径>' / '--full'`:void 0,staffs:U}}async function VJ($,i){let{client:v}=await ei($),u=await Y0(v,i.external??!1),n=i.keyword.trim().toLowerCase();if(!n)return u.slice(0,i.limit??N0);return u.filter((I)=>{let U=I.name?.toLowerCase()||"",D=I.email?.toLowerCase()||"",w=I.cellphone||"",g=I.id?.toLowerCase()||"";return U.includes(n)||D.includes(n)||w.includes(n)||g.includes(n)}).slice(0,i.limit??50)}async function qJ($,i){let{client:v}=await ei($),u=await Y0(v,!1),n=i.trim();return u.find((I)=>I.id===n||I.id.endsWith(`:${n}`)||I.id.split(":")[1]===n)||null}var vc=[{name:"contact_search",description:"在当前企业通讯录中模糊检索员工(支持姓名、邮箱、手机号、工号)",parameters:W.object({keyword:W.string().describe("检索关键词,如姓名、邮箱前缀、手机号或工号"),limit:W.number().optional().describe("最大返回条数,默认 20")}),handler:async($,i)=>{let v=await VJ($,i);return{count:v.length,staffs:v}}},{name:"contact_get",description:"根据员工 staffId 或工号精准获取员工详细档案",parameters:W.object({staffId:W.string().describe("员工的完整 staffId 或 ID")}),handler:async($,i)=>{let v=await qJ($,i.staffId);if(!v)throw Error(`未找到员工: ${i.staffId}`);return v}},{name:"contact_list",description:"查看企业通讯录(带默认 20 条防爆截断与总数保护)",parameters:W.object({limit:W.number().optional().describe("截断返回条数,默认 20"),allowFull:W.boolean().optional().describe("是否强制全量输出(大企业请谨慎使用)")}),handler:async($,i)=>{return await ZJ($,i)}}];async function mY($,i){let v=i.selectedCorp;if(!v)return{stdout:"",stderr:"未指定或未找到有效企业配置。请运行 'hose corps list' 或指定 '--corp=<id>'",exitCode:1};let u=$.action||$.args[0]||"list",n=l$($.options,["limit","l"]);if(u==="search"||u==="find"){let b=$.args[0]||m($.options,["keyword","query","k"])||"";if(!b.trim())return{stdout:"",stderr:"用法: hose contact search <关键词 (姓名/邮箱/工号)>",exitCode:1};let I=await VJ(v,{keyword:b,limit:n});if(i.jsonMode)return{stdout:l({count:I.length,keyword:b,staffs:I},i.outputOptions),stderr:"",exitCode:0};if(I.length===0)return{stdout:`未找到匹配关键词 "${b}" 的员工。
`,stderr:"",exitCode:0};let U=["姓名","工号 / staffId","邮箱","手机号"],D=I.map((w)=>[w.name||"-",w.id,w.email||"-",w.cellphone||"-"]);return{stdout:`====== 员工搜索结果 (关键词: "${b}", 找到 ${I.length} 人) ======
${Y$(U,D)}
`,stderr:"",exitCode:0}}if(u==="get"){let b=$.args[0]||m($.options,["id","staff-id"]);if(!b)return{stdout:"",stderr:"用法: hose contact get <staffId>",exitCode:1};let I=await qJ(v,b);if(!I)return{stdout:"",stderr:`未找到员工档案: ${b}`,exitCode:1};if(i.jsonMode)return{stdout:l(I,i.outputOptions),stderr:"",exitCode:0};let U={"员工姓名":I.name,"工号/staffId":I.id,"电子邮箱":I.email||"-","联系手机":I.cellphone||"-","所属部门":I.department||"-"};return{stdout:`====== 员工详细档案 ======
${J$(U)}
`,stderr:"",exitCode:0}}if(u==="list"){let b=i.outputOptions?.allowFull===!0,I=await ZJ(v,{limit:n??(b?void 0:N0),allowFull:b});if(i.jsonMode)return{stdout:l(I,i.outputOptions),stderr:"",exitCode:0};let U=["姓名","工号 / staffId","邮箱","手机号"],D=I.staffs.map((g)=>[g.name||"-",g.id,g.email||"-",g.cellphone||"-"]),w=`====== 企业通讯录采样 (共 ${I.total} 人,当前显示 ${I.staffs.length} 条) ======
`;if(w+=Y$(U,D)+`
`,I.hint)w+=`
\uD83D\uDCA1 提示: ${I.hint}
`;return{stdout:w,stderr:"",exitCode:0}}return{stdout:"",stderr:`未知通讯录子命令: ${u}。支持的子命令: list, search <关键词>, get <staffId>`,exitCode:1}}import{homedir as rM}from"node:os";import{join as uN}from"node:path";import{spawn as lM,execFileSync as EM}from"node:child_process";import{existsSync as eY,mkdirSync as tM,readFileSync as sY,rmSync as P6,writeFileSync as EJ}from"node:fs";import{join as $N}from"node:path";import{createServer as TM}from"node:http";import{URL as qM}from"node:url";function oY(){return`<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<title>hose-use API Reference (v${E})</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⚡</text></svg>" />
<style>
body {
margin: 0;
padding: 0;
background-color: #0f172a;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
</style>
</head>
<body>
<script
id="api-reference"
data-url="/openapi.json"
data-configuration='{"theme":"purple","layout":"modern","showSidebar":true}'
src="https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.25.101/dist/browser/standalone.js"
></script>
</body>
</html>`}async function dY($,i){if(i.setHeader("Access-Control-Allow-Origin","*"),i.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS, PATCH"),i.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Hose-Corp"),$.method==="OPTIONS"){i.writeHead(204),i.end();return}let v=$.headers.host||"localhost",u=$.headers["x-forwarded-proto"]||"http",b=new qM($.url||"/",`${u}://${v}`).pathname.replace(/\/+$/,"")||"/",I=($.method||"GET").toUpperCase();try{if(I==="GET"&&b==="/"){zn(i,200,{name:"hose-use",version:E,description:"合思/易快报企业级 CLI 工具与底层 SDK HTTP 服务",docs:"/docs",openapi:"/openapi.json",rawOpenapi:"/raw-openapi.json",health:"/health",endpoints:{cli:"POST /api/cli",corps:"GET /v1/corps"}});return}if(I==="GET"&&b==="/health"){zn(i,200,{status:"ok",name:"hose-use",version:E,timestamp:new Date().toISOString()});return}if(I==="GET"&&b==="/docs"){MM(i,200,oY());return}if(I==="GET"&&b==="/openapi.json"){zn(i,200,Kn("wrapped"));return}if(I==="GET"&&b==="/raw-openapi.json"){zn(i,200,Kn("raw"));return}if(I==="POST"&&b==="/api/cli"){let U=await kM($),D=(typeof U?.command==="string"?U.command:"").trim();if(!D){MJ(i,400,"Missing 'command' property in request body");return}let w=kJ(D),g=TJ(w),J=await H6(g),X=void 0,O=J.stdout.trim();try{if(O.startsWith("{")||O.startsWith("["))X=JSON.parse(O)}catch{}zn(i,J.exitCode===0?200:400,{success:J.exitCode===0,stdout:J.stdout,stderr:J.stderr,exitCode:J.exitCode,...X!==void 0?{data:X}:{}});return}if(I==="GET"&&b==="/v1/corps"){let U=Hv(),D=Qn();zn(i,200,{count:U.length,mode:D.stateful?"stateful":"stateless",defaultCorpId:D.defaultCorpId,corps:U.map((w)=>({id:w.id,name:w.name,source:w.source,staffId:w.credentials.staffId,baseUrl:w.baseUrl,expiresAt:w.auth?.expiresAt||w.session?.expTime}))});return}MJ(i,404,`Cannot ${I} ${b}. Visit /docs for available endpoints.`)}catch(U){let D=U instanceof Error?U.message:String(U);MJ(i,500,D)}}function zn($,i,v){if($.headersSent)return;let u=JSON.stringify(v,null,2);$.writeHead(i,{"Content-Type":"application/json; charset=utf-8","Content-Length":Buffer.byteLength(u,"utf-8")}),$.end(u)}function MM($,i,v){if($.headersSent)return;$.writeHead(i,{"Content-Type":"text/html; charset=utf-8","Content-Length":Buffer.byteLength(v,"utf-8")}),$.end(v)}function MJ($,i,v){zn($,i,{error:!0,message:v})}async function kM($){return new Promise((i,v)=>{let u="";$.on("data",(n)=>{if(u+=n,u.length>5242880)v(Error("Request payload too large (max 5MB)"))}),$.on("end",()=>{if(!u.trim()){i(null);return}try{i(JSON.parse(u))}catch(n){v(Error(`Invalid JSON body: ${n instanceof Error?n.message:String(n)}`))}}),$.on("error",(n)=>{v(n)})})}var L0=8888,K0="127.0.0.1";async function z0($={}){let i=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):L0),v=$.host??(process.env.HOST?process.env.HOST:K0),u=TM(async(n,b)=>{try{await dY(n,b)}catch(I){if(!b.headersSent)b.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),b.end(JSON.stringify({error:!0,message:I instanceof Error?I.message:String(I)}))}});return new Promise((n,b)=>{u.on("error",(I)=>{b(I)}),u.listen(i,v,()=>{if(!$.silent)console.error(`
⚡ hose-use HTTP Server (v${E}) 已启动`),console.error(` 主服务地址: http://${v}:${i}`),console.error(` 交互式文档: http://${v}:${i}/docs`),console.error(` OpenAPI规范: http://${v}:${i}/openapi.json`),console.error(` CLI执行网关: POST http://${v}:${i}/api/cli`),console.error(` 企业列表接口: GET http://${v}:${i}/v1/corps
`);n(u)})})}async function iN($,i,v={}){switch($){case"run":await RM(i);return;case"start":return pY(i);case"stop":return aY(i,v);case"restart":return aY(i,{quiet:!0}),pY(i);case"logs":case"log":return CM(i);case"status":case void 0:return lJ(i);default:throw Error("用法: hose service <start|stop|restart|status|logs>")}}function lJ($){let i=Ev($),v=H0(i),u=v?nN(v,$.appRoot):!1;if(v&&!u)P6(i,{force:!0});let n=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):L0),b=$.host??(process.env.HOST?process.env.HOST:K0);return{running:u,pid:u?v:void 0,version:$.version,port:n,host:b,url:u?`http://${b}:${n}`:void 0,appRoot:$.appRoot,stateDir:$.stateDir,pidFile:i,logFile:Hn($)}}async function RM($){let i=Ev($),v=Hn($);vN($.stateDir),EJ(i,`${process.pid}
`,{mode:384});let u=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):L0),n=$.host??(process.env.HOST?process.env.HOST:K0);lv(v,`service starting on http://${n}:${u} pid=${process.pid}`);let b=null;try{b=await z0({port:u,host:n,silent:!0}),lv(v,`service listening pid=${process.pid}`)}catch(U){if(lv(v,`service failed to bind port ${u}: ${U instanceof Error?U.message:String(U)}`),H0(i)===process.pid)P6(i,{force:!0});throw U}let I=()=>{if(b)b.close(),b=null;if(H0(i)===process.pid)P6(i,{force:!0});lv(v,`service stopped pid=${process.pid}`)};await new Promise((U)=>{let D=!1,w=()=>{if(D)return;D=!0,I(),process.off("SIGTERM",w),process.off("SIGINT",w),U()};process.once("SIGTERM",w),process.once("SIGINT",w)})}function pY($){vN($.stateDir);let i=lJ($);if(i.running)return i;let v=$.launcher??{command:process.execPath,args:[$.entryFile]},u=[...v.args??[],"service","run"];if($.port)u.push(`--port=${$.port}`);if($.host)u.push(`--host=${$.host}`);let n=lM(v.command,u,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});n.unref();let b=Ev($);return EJ(b,`${n.pid}
`,{mode:384}),lv(Hn($),`service started pid=${n.pid}`),{started:!0,...lJ($)}}function aY($,i={}){let v=Ev($),u=H0(v);if(!u||!nN(u,$.appRoot))return P6(v,{force:!0}),i.quiet?void 0:{stopped:!1,reason:"服务未处于运行状态"};try{process.kill(u,"SIGTERM")}catch{}return P6(v,{force:!0}),lv(Hn($),`service stop requested pid=${u}`),i.quiet?void 0:{stopped:!0,pid:u}}function CM($,i=50){let v=Hn($);if(!eY(v))return{logFile:v,lines:[],content:"暂无服务运行日志"};let n=sY(v,"utf-8").trim().split(`
`).filter(Boolean).slice(-i);return{logFile:v,lines:n,content:n.join(`
`)}}function nN($,i){if(!_M($))return!1;try{let v=EM("ps",["-p",String($),"-o","command="],{encoding:"utf8"});return(v.includes(i)||v.includes("hose-use")||v.includes("src/cli.ts"))&&v.includes("service")&&v.includes("run")}catch{return!1}}function _M($){try{return process.kill($,0),!0}catch{return!1}}function Ev($){return $N($.stateDir,"service.pid")}function Hn($){return $N($.stateDir,"service.log")}function H0($){if(!eY($))return;let i=Number(sY($,"utf-8").trim());return Number.isInteger(i)&&i>0?i:void 0}function vN($){tM($,{recursive:!0,mode:448})}function lv($,i){EJ($,`${new Date().toISOString()} ${i}
`,{flag:"a",mode:384})}var fM=process.env.HOSE_STATE_DIR||uN(rM(),".config","hose-use");async function bN($,i){let v=$.action||$.args[0]||"status",u=l$($.options,["port","p"]),n=m($.options,["host","h"]),b={appRoot:i.appRoot||process.cwd(),entryFile:i.entryFile||uN(i.appRoot||process.cwd(),"src","cli.ts"),stateDir:fM,version:E,launcher:i.launcher,port:u,host:n},I=await iN(v,b);if(I===void 0)return{stdout:"",stderr:"",exitCode:0};if(i.jsonMode)return{stdout:l(I,i.outputOptions),stderr:"",exitCode:0};if(v==="logs"||v==="log"){let J=I;return{stdout:`====== hose-use 守护进程日志 (${J.logFile}) ======
${J.content}
`,stderr:"",exitCode:0}}let U=I,w={"服务状态":Boolean(U.running)?"\uD83D\uDFE2 正在运行 (Running)":"⚪ 已停止 (Stopped)",...U.pid?{"进程 PID":U.pid}:{},...U.url?{"服务地址":U.url}:{},...U.url?{"交互式文档":`${U.url}/docs`}:{},...U.url?{"CLI 网关":`POST ${U.url}/api/cli`}:{},"运行版本":U.version||b.version,"状态目录":U.stateDir||b.stateDir,"PID 文件":U.pidFile||Ev(b),"日志文件":U.logFile||Hn(b)};return{stdout:`====== hose-use 常驻服务管理 (Service) ======
${J$(w)}
`,stderr:"",exitCode:0}}async function IN($,i){let v=l$($.options,["port","p"]),u=m($.options,["host","h"]),n=await z0({port:v,host:u,silent:i.jsonMode}),b=()=>{n.close(()=>{process.exit(0)})};return process.on("SIGINT",b),process.on("SIGTERM",b),await new Promise(()=>{}),{stdout:"",stderr:"",exitCode:0}}var xM=new Set(["http","server","web","mcp"]);function yM($){if(!$.length)return!1;let i=$[0]?.toLowerCase(),v=$[1]?.toLowerCase();if(xM.has(i))return!0;if((i==="service"||i==="daemon")&&v==="run")return!0;return!1}var UN=Promise.resolve(void 0);function H6($,i={}){if(yM($))return DN($,i);let v=UN.then(()=>cM($,i));return UN=v.then(()=>{return},()=>{return}),v}async function cM($,i={}){let v=[],u=[],n=console.log,b=console.error;console.log=(...I)=>{v.push(I.map((U)=>typeof U==="string"?U:String(U)).join(" "))},console.error=(...I)=>{u.push(I.map((U)=>typeof U==="string"?U:String(U)).join(" "))};try{let I=await DN($,i),U=v.length?`${v.join(`
`)}
`:"",D=u.length?`${u.join(`
`)}
`:"";return{stdout:kv(U+(I.stdout||"")),stderr:kv(D+(I.stderr||"")),exitCode:I.exitCode}}finally{console.log=n,console.error=b}}async function DN($,i={}){let v=gY($);if(W$(v.options,["help","h"])||v.area==="help")return{stdout:KJ()+`
`,stderr:"",exitCode:0};if(W$(v.options,["version","v"])||v.area==="version")return{stdout:`hose-use v${E}
`,stderr:"",exitCode:0};let u=W$(v.options,["json","j"]),n=m(v.options,["corp","c"]),b=W$(v.options,["stateless"]),I=W$(v.options,["stateful"]),U=WY(v.options),D=XY({corpId:n,stateless:b,stateful:I,jsonMode:u,outputOptions:U,appRoot:i.appRoot,entryFile:i.entryFile,launcher:i.launcher});try{switch(v.area){case"auth":case"login":return await OY(v,D);case"corps":case"corp":return await jY(v,D);case"config":case"mode":return await AY(v,D);case"workflow":case"workflows":case"wf":return await GY(v,D);case"bill":case"bills":case"fee":case"fees":case"invoice":case"invoices":return await cY(v,D);case"contact":case"contacts":case"staff":case"staffs":return await mY(v,D);case"platform":case"platforms":case"app":case"apps":return await QY(v,D);case"skill":case"skills":return await ZY(v,D);case"probe":case"diagnose":return await VY(v,D);case"update":case"upgrade":case"self-update":case"changelog":return await _Y(v,D,i);case"openapi":case"schema":case"spec":return await yY(v,D);case"http":case"server":case"web":return await IN(v,D);case"service":case"daemon":return await bN(v,D);case"mcp":return await qY(v,i);case void 0:return{stdout:KJ()+`
`,stderr:"",exitCode:0};default:return{stdout:"",stderr:`未知命令域: ${v.area}。运行 hose --help 查看帮助
`,exitCode:1}}}catch(w){let g=kv(w instanceof Error?w.message:String(w));if(u)return{stdout:l({error:!0,message:g}),stderr:"",exitCode:1};return{stdout:"",stderr:`[ERROR] ${g}
`,exitCode:1}}}var tJ="hose_cli",mM="HOSE_MCP_MODE",oM="HOSE_USE_MCP_ENABLED",Pn=hM(import.meta.url),gN=Pn.includes("/dist/mcp/")||Pn.includes("\\dist\\mcp\\")?F6(F6(F6(Pn))):F6(F6(Pn));function dM($=process.env[oM]){if($===void 0)return!0;return["1","true","yes","on"].includes($.trim().toLowerCase())}function WN($=process.env[mM]){if(!$)return"single";let i=$.trim().toLowerCase();if(i==="all"||i==="both"||i==="full")return"all";if(i==="legacy"||i==="multi")return"legacy";return"single"}function kJ($){let i=[],v="",u,n=!1,b=!1;for(let I of $){if(n){v+=I,n=!1,b=!0;continue}if(I==="\\"&&u!=="'"){n=!0,b=!0;continue}if(u){if(I===u)u=void 0;else v+=I;b=!0;continue}if(I==="'"||I==='"'){u=I,b=!0;continue}if(/\s/.test(I)){if(b)i.push(v),v="",b=!1;continue}v+=I,b=!0}if(n)throw Error("Invalid command: trailing escape");if(u)throw Error("Invalid command: unterminated quote");if(b)i.push(v);return i}function TJ($){let i=$[0];if(!i)return[];let v=i.toLowerCase().replace(/\\/g,"/");if(v==="hose-use"||v==="hose"||v.endsWith("/hose-use")||v.endsWith("/hose")||v.endsWith("/hose-use.exe")||v.endsWith("/hose.exe"))return $.slice(1);return $}function P0($){let i=$.exitCode!==0,v=i?$.stderr||$.stdout||"Command failed":$.stdout||$.stderr||"Success";return v=kv(v),{content:[{type:"text",text:v.trimEnd()}],isError:i}}function pM($){if($ instanceof wJ)return{content:[{type:"text",text:"未配置企业,请先添加企业配置或登录"}],isError:!0};if($ instanceof g$)return{content:[{type:"text",text:`认证失败: ${$.message}`}],isError:!0};if($ instanceof O6)return{content:[{type:"text",text:`错误 [${$.code}]: ${$.message}`}],isError:!0};if($ instanceof W.ZodError)return{content:[{type:"text",text:`参数错误: ${$.message}`}],isError:!0};return{content:[{type:"text",text:$ instanceof Error?$.message:"发生内部错误,请稍后重试"}],isError:!0}}function aM($={}){let i=$.enabled??dM(),v=$.mode??WN(),u=new yW({name:"hose-use",version:E},{capabilities:{tools:{}}}),n=[...jJ,...GJ,...LJ];return u.setRequestHandler(qg,async()=>{if(!i)return{tools:[]};let b=[];if(v==="single"||v==="all")b.push({name:tJ,description:"Run hose-use CLI commands (e.g. 'bill query', 'corps list', 'workflow search'). See the hose-use skill for command reference.",inputSchema:{type:"object",properties:{command:{type:"string",description:"A hose-use CLI command string, with or without the leading 'hose-use' or 'hose'. Example: 'corps list' or 'bill query --code BX20260901001'."}},required:["command"],additionalProperties:!1}});if(v==="all"||v==="legacy")for(let I of n)b.push({name:I.name,description:I.description,inputSchema:I.parameters.toJSONSchema()});return{tools:b}}),u.setRequestHandler(V4,async(b)=>{if(!i)return P0({stdout:"",stderr:"hose-use MCP 服务在插件配置中已被禁用 (HOSE_USE_MCP_ENABLED=false)",exitCode:1});let{name:I,arguments:U}=b.params;if(I===tJ){let D=U&&typeof U.command==="string"?U.command:void 0;if(!D?.trim())return P0({stdout:"",stderr:"hose_cli requires a non-empty command string",exitCode:1});try{let w=kJ(D),g=TJ(w);if(!g.length)throw Error("hose_cli requires a non-empty command string");let J=await H6(g,{appRoot:gN,entryFile:Pn});return P0(J)}catch(w){return P0({stdout:"",stderr:w instanceof Error?w.message:String(w),exitCode:1})}}try{let D=Hv(),w=new b6(D),g=jJ.find((j)=>j.name===I);if(g){let j=g.parameters.safeParse(U||{});if(!j.success)return{content:[{type:"text",text:`参数错误: ${j.error.message}`}],isError:!0};let G=await g.handler({corpContext:w},j.data);return{content:[{type:"text",text:typeof G==="string"?G:JSON.stringify(G,null,2)}]}}let J=LJ.find((j)=>j.name===I);if(J){let j=J.parameters.safeParse(U||{});if(!j.success)return{content:[{type:"text",text:`参数错误: ${j.error.message}`}],isError:!0};let G=await J.handler({corpContext:w},j.data);return{content:[{type:"text",text:typeof G==="string"?G:JSON.stringify(G,null,2)}]}}let X=w.getCurrent();if(!X)return{content:[{type:"text",text:"未配置企业,请先调用 auth login 登录或 auth import 导入凭证"}],isError:!0};let O=GJ.find((j)=>j.name===I);if(O){let j=O.parameters.safeParse(U||{});if(!j.success)return{content:[{type:"text",text:`参数错误: ${j.error.message}`}],isError:!0};let G=await x$(X),{client:N}=await ei(X),L=await O.handler({corp:X,ekbClient:G,easoClient:N},j.data);return{content:[{type:"text",text:typeof L==="string"?L:JSON.stringify(L,null,2)}]}}return{content:[{type:"text",text:`未知工具: ${I}。在单工具网关模式下,请通过 ${tJ} 调用。`}],isError:!0}}catch(D){return pM(D)}}),u}async function eM(){let $=aM(),i=new hW;await $.connect(i),console.error(`hose-use MCP Server (v${E}) running on stdio [mode: ${WN()}]`)}async function sM(){let $=await H6(process.argv.slice(3),{appRoot:gN,entryFile:Pn});if($.stdout)process.stdout.write($.stdout);if($.stderr)process.stderr.write(`${$.stderr}${$.stderr.endsWith(`
`)?"":`
`}`);process.exitCode=$.exitCode}var $k=Boolean(_J.main==_J.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&wN(process.argv[1])===wN(Pn));if($k)if(process.argv[2]==="--hose-use-cli"||process.argv[2]==="--hose-cli")await sM();else eM().catch(($)=>{console.error($),process.exitCode=1});export{kJ as tokenizeCommand,eM as startServer,WN as resolveMcpMode,dM as resolveMcpEnabled,TJ as normalizeCliArgs,aM as createServer,P0 as cliResult,mM as HOSE_MCP_MODE_ENV,oM as HOSE_MCP_ENABLED_ENV,tJ as HOSE_CLI_TOOL_NAME};
+1152
View File
File diff suppressed because it is too large. Load diff
+1501
View File
File diff suppressed because it is too large. Load diff
+167
View File
@@ -0,0 +1,167 @@
ErrorResponse:
type: object
properties:
error:
type: boolean
example: true
message:
type: string
example: 操作失败原因
AuthLoginRequest:
type: object
required:
- phone
- password
properties:
phone:
type: string
description: 登录手机号
example: "17718556446"
password:
type: string
description: 登录明文密码 (由客户端自动完成 RSA 加密)
autoSwitch:
type: boolean
description: 是否自动切换到首个企业
default: true
AuthStatusResponse:
type: object
properties:
loggedIn:
type: boolean
activeCorpId:
type: string
activeCorpName:
type: string
totalAccounts:
type: integer
totalCorps:
type: integer
CorpConfig:
type: object
properties:
corpId:
type: string
description: 企业唯一标识
corpName:
type: string
description: 企业名称
staffId:
type: string
description: 员工身份 ID
accountId:
type: string
description: 归属账号手机号
PlatformItem:
type: object
properties:
id:
type: string
description: 自建应用 ID
name:
type: string
description: 自建应用名称
code:
type: string
description: 应用编码
status:
type: string
description: 应用状态
WorkflowSummary:
type: object
properties:
id:
type: string
description: 工作流 ID
name:
type: string
description: 工作流名称
platformId:
type: string
description: 归属自建应用 ID
platformName:
type: string
description: 归属自建应用名称
state:
type: integer
description: "1: 启用, 0: 停用"
updatedAt:
type: string
WorkflowDetail:
type: object
properties:
id:
type: string
name:
type: string
state:
type: integer
nodes:
type: array
items:
type: object
description: 工作流节点列表 (code-js2, loop, sql 等)
links:
type: array
items:
type: object
ProbeResult:
type: object
properties:
corpId:
type: string
corpName:
type: string
mainSession:
type: boolean
description: 主站会话是否有效
easoToken:
type: boolean
description: EASO 平台 Token 是否有效
platformsReachable:
type: boolean
description: 自建应用接口是否可访问
FormattedBill:
type: object
properties:
billId:
type: string
description: 单据 ID
billCode:
type: string
description: 单据业务编号 (单号)
billName:
type: string
description: 单据名称
title:
type: string
description: 单据标题
stage:
type: string
description: 业务阶段 (如 expense, loan, payment)
state:
type: string
description: 审批/支付状态 (如 paid, approving, draft)
amount:
type: string
description: 格式化金额 (如 ¥100.00 CNY)
submitterId:
type: string
description: 提交人员 ID
submitDate:
type: string
description: 提交时间
corporationId:
type: string
description: 归属企业 ID
details:
type: object
description: DataLink 字段字典还原后的中文字段键值对
+54
View File
@@ -0,0 +1,54 @@
openapi: 3.1.0
info:
title: hose-use API & MCP Tools Specification
version: 0.5.2
description: >-
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
servers:
- url: http://localhost:3000
description: Local hose-use CLI / MCP Runtime Gateway
tags:
- name: Auth & SSO
description: 统一认证、多账号管理与 30 天 Token 自动无感续杯
- name: Corps & Tenancy
description: 多企业租户管理与工作空间切换
- name: Platforms
description: 自建应用检索与实例枚举
- name: Workflows
description: 跨自建应用工作流聚合检索、DSL 图谱与启停
- name: Bills & Documents
description: 费控单据、报销借款单、发票明细与 DataLink 实体字典
- name: Probe & Diagnostics
description: 会话有效性与 EASO 鉴权连通性诊断
paths:
/api/auth/login:
$ref: ./paths/auth.yaml#/login
/api/auth/status:
$ref: ./paths/auth.yaml#/status
/api/auth/refresh:
$ref: ./paths/auth.yaml#/refresh
/api/corps:
$ref: ./paths/corps.yaml#/list
/api/corps/switch:
$ref: ./paths/corps.yaml#/switch
/api/platforms:
$ref: ./paths/platform.yaml#/list
/api/workflows:
$ref: ./paths/workflow.yaml#/list
/api/workflows/find:
$ref: ./paths/workflow.yaml#/find
/api/workflows/{pipelineId}:
$ref: ./paths/workflow.yaml#/detail
/api/workflows/{pipelineId}/toggle:
$ref: ./paths/workflow.yaml#/toggle
/api/bills:
$ref: ./paths/bill.yaml#/list
/api/bills/{code}:
$ref: ./paths/bill.yaml#/get
/api/bills/schema:
$ref: ./paths/bill.yaml#/schema
/api/probe:
$ref: ./paths/probe.yaml#/probe
components:
schemas:
$ref: ./components/schemas/index.yaml
+68
View File
@@ -0,0 +1,68 @@
login:
post:
tags:
- Auth & SSO
summary: 纯 API 账密自动全流程登录
description: 自动拉取公钥进行 RSA PKCS#1 加密,发起统一认证中心握手并批量获取名下所有企业身份。
operationId: authLogin
requestBody:
required: true
content:
"application/json":
schema:
$ref: ../components/schemas/index.yaml#/AuthLoginRequest
responses:
"200":
description: 登录成功
content:
"application/json":
schema:
type: object
properties:
success:
type: boolean
totalCorps:
type: integer
activeCorp:
$ref: ../components/schemas/index.yaml#/CorpConfig
"401":
description: 账密错误或鉴权失败
content:
"application/json":
schema:
$ref: ../components/schemas/index.yaml#/ErrorResponse
status:
get:
tags:
- Auth & SSO
summary: 查看当前登录与活跃企业状态
description: 查询本地或无状态下的当前账号、工作企业与凭证有效期。
operationId: authStatus
responses:
"200":
description: 状态正常
content:
"application/json":
schema:
$ref: ../components/schemas/index.yaml#/AuthStatusResponse
refresh:
post:
tags:
- Auth & SSO
summary: 批量刷新企业 30 天 AccessToken
description: 自动无感为当前账号名下的所有企业租户更新最新 30 天访问令牌。
operationId: authRefresh
responses:
"200":
description: 刷新完成
content:
"application/json":
schema:
type: object
properties:
refreshed:
type: integer
total:
type: integer
+101
View File
@@ -0,0 +1,101 @@
list:
get:
tags:
- Bills & Documents
summary: 检索费用单据与发票明细列表
description: 查询企业名下的费用单据、报销单、借款单与发票列表,支持按单号、阶段、状态过滤。
operationId: listBills
parameters:
- name: code
in: query
required: false
description: 按单据编号/单号过滤(如 jO1it3cIufDjNS)
schema:
type: string
- name: keyword
in: query
required: false
description: 按关键字搜索标题、名称或内容
schema:
type: string
- name: stage
in: query
required: false
description: 按业务阶段过滤(expense 报销, loan 借款, payment 付款)
schema:
type: string
- name: state
in: query
required: false
description: 按审批/支付状态过滤(paid 已支付, approving 审批中, draft 草稿)
schema:
type: string
- name: count
in: query
required: false
description: 返回条数限制
schema:
type: integer
default: 20
responses:
"200":
description: 格式化后的单据列表
content:
"application/json":
schema:
type: object
properties:
total:
type: integer
returned:
type: integer
items:
type: array
items:
$ref: "../components/schemas/index.yaml#/FormattedBill"
get:
get:
tags:
- Bills & Documents
summary: 根据单号或 ID 查询单据结构化详情
description: 自动结合 DataLink 字段字典将代码字段还原为业务中文字段。
operationId: getBillByCode
parameters:
- name: code
in: path
required: true
description: 单据编号(如 n0GMIM0dkQmKbS)或单据 ID(如 ID01TRzg7HMLcb)
schema:
type: string
responses:
"200":
description: 单据详情列表
content:
"application/json":
schema:
type: array
items:
$ref: "../components/schemas/index.yaml#/FormattedBill"
schema:
get:
tags:
- Bills & Documents
summary: 获取单据实体与数据模型字典
description: 获取企业全部表单实体、中文字段 Label 与类型定义。
operationId: getBillSchemas
responses:
"200":
description: 实体模型字典
content:
"application/json":
schema:
type: object
properties:
totalEntities:
type: integer
entities:
type: array
items:
type: object
+48
View File
@@ -0,0 +1,48 @@
list:
get:
tags:
- Corps & Tenancy
summary: 列出当前账号名下所有已配置企业租户
description: 支持单账号管理多家企业与同一企业下的多员工身份分层展示。
operationId: listCorps
responses:
"200":
description: 企业租户列表
content:
"application/json":
schema:
type: array
items:
$ref: ../components/schemas/index.yaml#/CorpConfig
switch:
post:
tags:
- Corps & Tenancy
summary: 切换当前工作企业
description: 在有状态模式下切换并记忆工作企业,后续操作自动以该企业身份执行。
operationId: switchCorp
requestBody:
required: true
content:
"application/json":
schema:
type: object
required:
- corpId
properties:
corpId:
type: string
description: 目标企业 ID 或身份 ID (corpId@accountId)
responses:
"200":
description: 切换成功
content:
"application/json":
schema:
type: object
properties:
success:
type: boolean
activeCorp:
$ref: ../components/schemas/index.yaml#/CorpConfig
+23
View File
@@ -0,0 +1,23 @@
list:
get:
tags:
- Platforms
summary: 查询企业下所有启用的自建应用
description: 枚举当前企业已配置的自建应用及 EASO 平台实例。
operationId: listPlatforms
parameters:
- name: corpId
in: query
required: false
schema:
type: string
description: 目标企业 ID (未指定时使用默认工作企业)
responses:
"200":
description: 自建应用列表
content:
"application/json":
schema:
type: array
items:
$ref: ../components/schemas/index.yaml#/PlatformItem
+20
View File
@@ -0,0 +1,20 @@
probe:
get:
tags:
- Probe & Diagnostics
summary: 诊断当前企业鉴权与接口连通性
description: 依次校验企业主站 Session Cookie、EASO 换票握手与自建应用接口可访问性。
operationId: probeCorp
parameters:
- name: corpId
in: query
required: false
schema:
type: string
responses:
"200":
description: 诊断报告
content:
"application/json":
schema:
$ref: ../components/schemas/index.yaml#/ProbeResult
+113
View File
@@ -0,0 +1,113 @@
list:
get:
tags:
- Workflows
summary: 跨自建应用汇总查看全部工作流
description: 自动遍历当前企业下所有自建应用,聚合返回全量工作流列表及运行状态。
operationId: listAllWorkflows
parameters:
- name: corpId
in: query
required: false
schema:
type: string
responses:
"200":
description: 聚合工作流列表
content:
"application/json":
schema:
type: array
items:
$ref: ../components/schemas/index.yaml#/WorkflowSummary
find:
get:
tags:
- Workflows
summary: 按节点类型递归搜索工作流
description: 递归解析所有工作流的 DSL 节点图谱,检索包含特定任务类型(如 code-js2, loop, sql 等)的工作流。
operationId: findWorkflowsByTask
parameters:
- name: task
in: query
required: true
schema:
type: string
example: "code-js2"
description: 目标节点任务类型
- name: corpId
in: query
required: false
schema:
type: string
responses:
"200":
description: 匹配的工作流列表
content:
"application/json":
schema:
type: array
items:
$ref: ../components/schemas/index.yaml#/WorkflowSummary
detail:
get:
tags:
- Workflows
summary: 获取单个工作流详情与节点结构
description: 查询指定工作流的完整节点链、输入输出参数映射与触发器配置。
operationId: getWorkflowDetail
parameters:
- name: pipelineId
in: path
required: true
schema:
type: string
description: 工作流 ID
responses:
"200":
description: 工作流详情
content:
"application/json":
schema:
$ref: ../components/schemas/index.yaml#/WorkflowDetail
toggle:
put:
tags:
- Workflows
summary: 启用或停用工作流
description: "切换工作流的运行开关(1: 启用, 0: 停用)。"
operationId: toggleWorkflow
parameters:
- name: pipelineId
in: path
required: true
schema:
type: string
requestBody:
required: true
content:
"application/json":
schema:
type: object
required:
- state
properties:
state:
type: integer
enum: [0, 1]
description: "目标状态 (1=启用, 0=停用)"
responses:
"200":
description: 状态切换成功
content:
"application/json":
schema:
type: object
properties:
success:
type: boolean
state:
type: integer
+8 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.2.0",
"version": "0.5.2",
"module": "src/server.ts",
"type": "module",
"bin": {
@@ -12,7 +12,13 @@
"probe": "bun run src/cli.ts probe",
"check": "tsc --noEmit",
"typecheck": "tsc --noEmit",
"test": "bun test",
"bump": "bun run scripts/bump-version.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": "bun run --watch src/server.ts",
"start": "bun run src/server.ts",
"export:workflow-schema": "bun run scripts/export-workflow-schema.ts"
@@ -20,6 +26,7 @@
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"ky": "^2.0.2",
"yaml": "^2.9.0",
"zod": "^4.4.3"
},
"devDependencies": {
+24
View File
@@ -0,0 +1,24 @@
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const bun = process.env.BUN_BIN || "bun";
function run(args) {
const result = spawnSync(bun, args, {
cwd: root,
stdio: "inherit",
});
if (result.error) throw result.error;
if (result.status !== 0) {
throw new Error(`${bun} ${args.join(" ")} failed with status ${result.status}`);
}
}
const mcpOutput = resolve(root, "dist/mcp/server.js");
mkdirSync(dirname(mcpOutput), { recursive: true });
run(["build", "src/server.ts", "--minify", "--target=node", "--outfile", mcpOutput]);
writeFileSync(mcpOutput, readFileSync(mcpOutput, "utf8").replace(/[ \t]+$/gm, ""));
console.log(`✓ Successfully bundled MCP server: ${mcpOutput}`);
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env bun
import { readFileSync, writeFileSync, existsSync, cpSync } from "node:fs";
import { join } from "node:path";
import { execSync } from "node:child_process";
const ROOT = join(import.meta.dirname, "..");
const pkgPath = join(ROOT, "package.json");
const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
const currentVersion: string = pkg.version;
const input = process.argv[2]?.trim();
if (!input) {
console.error("Usage: bun run bump <version | patch | minor | major>");
console.error(`Current version: ${currentVersion}`);
process.exit(1);
}
let nextVersion = input.replace(/^v/, "");
if (input === "patch" || input === "minor" || input === "major") {
const [major, minor, patch] = currentVersion.split(".").map(Number);
if (input === "patch") nextVersion = `${major}.${minor}.${patch + 1}`;
if (input === "minor") nextVersion = `${major}.${minor + 1}.0`;
if (input === "major") nextVersion = `${major + 1}.0.0`;
}
if (!/^\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?$/.test(nextVersion)) {
console.error(`Invalid SemVer format: '${nextVersion}'`);
process.exit(1);
}
console.log(`==> Bumping version: ${currentVersion} -> ${nextVersion}`);
// 1. package.json
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
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
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})`);
writeFileSync(skillPath, skillContent);
console.log("✓ Updated skills/hose-use/SKILL.md");
// 5. openapi/openapi.yaml
const openapiPath = join(ROOT, "openapi", "openapi.yaml");
if (existsSync(openapiPath)) {
let openapiContent = readFileSync(openapiPath, "utf-8");
openapiContent = openapiContent.replace(/version: [\d.]+/g, `version: ${nextVersion}`);
writeFileSync(openapiPath, openapiContent);
console.log("✓ Updated openapi/openapi.yaml");
}
// 5.5 .zcode-plugin/plugin.json
const pluginJsonPath = join(ROOT, ".zcode-plugin", "plugin.json");
if (existsSync(pluginJsonPath)) {
const pluginJson = JSON.parse(readFileSync(pluginJsonPath, "utf-8"));
pluginJson.version = nextVersion;
writeFileSync(pluginJsonPath, JSON.stringify(pluginJson, null, 2) + "\n");
console.log("✓ Updated .zcode-plugin/plugin.json");
}
// 6. Sync to global ~/.agents/skills/hose-use/ if present
const globalSkillDir = join(process.env.HOME || "", ".agents", "skills", "hose-use");
if (existsSync(globalSkillDir)) {
cpSync(join(ROOT, "skills", "hose-use"), globalSkillDir, { recursive: true });
console.log("✓ Synchronized ~/.agents/skills/hose-use/");
}
// 7. Rebuild OpenAPI bundles
console.log("==> Rebuilding OpenAPI bundles...");
execSync("bun run openapi:all", { 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`);
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env bun
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import YAML from "yaml";
type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
const inputFile = resolve("openapi/openapi.yaml");
const outputFile = resolve("dist/openapi.json");
const bundled = bundle(inputFile, new Set());
mkdirSync(dirname(outputFile), { recursive: true });
writeFileSync(outputFile, `${JSON.stringify(bundled, null, 2)}\n`);
console.log(`✓ Bundled wrapped OpenAPI: ${outputFile}`);
function bundle(filePath: string, seen: Set<string>): Json {
const absolutePath = resolve(filePath);
if (seen.has(absolutePath)) {
throw new Error(`Circular OpenAPI reference: ${absolutePath}`);
}
const parsed = YAML.parse(readFileSync(absolutePath, "utf8")) as Json;
return resolveReferences(parsed, absolutePath, new Set([...seen, absolutePath]));
}
function resolveReferences(value: Json, currentFile: string, seen: Set<string>): Json {
if (Array.isArray(value)) {
return value.map((item) => resolveReferences(item, currentFile, seen));
}
if (!isObject(value)) return value;
if (typeof value.$ref === "string" && isFileReference(value.$ref)) {
const [refPath, pointer = ""] = value.$ref.split("#");
const refFile = refPath ? resolve(dirname(currentFile), refPath) : currentFile;
const target = pointer ? resolvePointer(bundle(refFile, seen), pointer) : bundle(refFile, seen);
return resolveReferences(target, refFile, seen);
}
return Object.fromEntries(
Object.entries(value).map(([key, item]) => [
key,
resolveReferences(item as Json, currentFile, seen),
])
);
}
function isFileReference(ref: string) {
return !ref.startsWith("#") && !/^[a-z][a-z0-9+.-]*:/i.test(ref);
}
function resolvePointer(document: Json, pointer: string): Json {
const path = pointer.replace(/^#/, "");
if (!path) return document;
return path
.split("/")
.filter(Boolean)
.map((part) => part.replace(/~1/g, "/").replace(/~0/g, "~"))
.reduce((target: Json, key) => {
if (!isObject(target) && !Array.isArray(target)) {
throw new Error(`Invalid JSON pointer segment "${key}" in ${pointer}`);
}
const next = (target as Record<string, Json>)[key];
if (next === undefined) {
throw new Error(`Missing JSON pointer segment "${key}" in ${pointer}`);
}
return next;
}, document);
}
function isObject(value: Json): value is { [key: string]: Json } {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
+768
View File
@@ -0,0 +1,768 @@
#!/usr/bin/env bun
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
const outputFile = resolve("dist/raw-hose-openapi.json");
function standardResponse(description: string, dataSchema: any) {
return {
"200": {
description,
content: {
"application/json": {
schema: {
type: "object",
properties: {
data: dataSchema,
code: { type: "string", example: "SUCCESS" },
message: { type: "string", example: "成功" },
},
},
},
},
},
"401": {
description: "未授权或 Token 已失效",
content: {
"application/json": {
schema: { $ref: "#/components/schemas/ErrorResponse" },
},
},
},
"400": {
description: "请求参数错误或鉴权异常",
content: {
"application/json": {
schema: { $ref: "#/components/schemas/ErrorResponse" },
},
},
},
};
}
const spec = {
openapi: "3.1.0",
info: {
title: "Hose / Ekuaibao Downstream Native API",
version: "1.0.0",
description: "Raw downstream Ekuaibao (合思/易快报), EASO, and Piper business API contracts.",
},
servers: [
{
url: "https://app.ekuaibao.com",
description: "合思/易快报主站与统一认证中心",
},
{
url: "https://easo.ekuaibao.com",
description: "合思 EASO 开放平台网关",
},
{
url: "https://piper.ekuaibao.com",
description: "合思 Piper 工作流与集成网关",
},
],
tags: [
{ name: "SSO & Security", description: "统一认证中心、RSA 公钥密码加密与多企业身份切换" },
{ name: "EASO & Piper Auth", description: "开放平台 OAuth2 免登握手、换票与 Token 自动刷新" },
{ name: "Platforms & Apps", description: "自建应用列表与集成检索" },
{ name: "Workflows & Pipelines", description: "跨应用工作流聚合、运行日志、节点详情与启停" },
{ name: "Bills & Invoices", description: "费控单据、报销单、借款单、发票与 DataLink 实体字典" },
{ name: "Jobs & Execution", description: "工作流任务运行实例与调试" },
{ name: "Staffs & Webhooks", description: "企业通讯录人员与 Webhook 触发配置" },
],
paths: {
"/api/v2/invoice/search": {
post: {
tags: ["Bills & Invoices"],
summary: "检索企业费用单据与发票池",
description: "检索企业名下的费用单据、报销借款单、发票与审批流记录,支持分页与阶段过滤。",
operationId: "rawSearchInvoices",
parameters: [
{ name: "corporationId", in: "query", required: true, schema: { type: "string" } },
],
requestBody: {
content: {
"application/json": {
schema: {
type: "object",
properties: {
limit: {
type: "object",
properties: {
start: { type: "integer", default: 0 },
count: { type: "integer", default: 50 },
},
},
},
},
},
},
},
responses: {
"200": {
description: "单据列表响应",
content: {
"application/json": {
schema: {
type: "object",
properties: {
count: { type: "integer" },
items: { type: "array", items: { type: "object" } },
},
},
},
},
},
},
},
},
"/api/v2/invoice": {
post: {
tags: ["Bills & Invoices"],
summary: "批量按 ID 精确获取单据详情",
description: "根据单据物理 ID 列表批量拉取完整的表单数据与状态。",
operationId: "rawGetInvoicesByIds",
parameters: [
{ name: "corporationId", in: "query", required: true, schema: { type: "string" } },
],
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
required: ["ids"],
properties: {
ids: { type: "array", items: { type: "string" } },
},
},
},
},
},
responses: {
"200": {
description: "单据详情列表",
content: {
"application/json": {
schema: {
type: "object",
properties: {
items: { type: "array", items: { type: "object" } },
},
},
},
},
},
},
},
},
"/api/v2/datalink/entity/search": {
post: {
tags: ["Bills & Invoices"],
summary: "查询 DataLink 实体定义与字段字典",
description: "获取企业全部单据实体模型、字段 Label 中文映射与类型定义。",
operationId: "rawSearchEntities",
parameters: [
{ name: "corporationId", in: "query", required: true, schema: { type: "string" } },
],
requestBody: {
content: {
"application/json": {
schema: {
type: "object",
properties: {
limit: {
type: "object",
properties: {
start: { type: "integer", default: 0 },
count: { type: "integer", default: 100 },
},
},
},
},
},
},
},
responses: {
"200": {
description: "实体定义字典",
content: {
"application/json": {
schema: {
type: "object",
properties: {
items: { type: "array", items: { type: "object" } },
},
},
},
},
},
},
},
},
"/api/common/security/getPublicKey": {
post: {
tags: ["SSO & Security"],
summary: "获取统一认证中心 RSA 公钥",
description: "获取用于登录密码加密的 RSA Public Key 模数与指数 (PKCS#1)。",
operationId: "getPublicKey",
responses: {
"200": {
description: "RSA 公钥响应",
content: {
"application/json": {
schema: {
type: "object",
properties: {
value: {
type: "object",
properties: {
publicKey: { type: "string", description: "RSA 公钥字符串" },
modulus: { type: "string", description: "RSA Modulus" },
exponent: { type: "string", description: "RSA Exponent" },
},
},
},
},
},
},
},
},
},
},
"/api/common/login/verifyPhone": {
post: {
tags: ["SSO & Security"],
summary: "手机号与加密密码纯 API 登录",
description: "使用 RSA 加密后的密码和手机号发起统一认证,换取全企业 AccessToken 与 Session Cookie。",
operationId: "loginVerifyPhone",
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
required: ["phone", "password"],
properties: {
phone: { type: "string", description: "手机号" },
password: { type: "string", description: "RSA 加密后的密码密文" },
countryCode: { type: "string", default: "+86" },
},
},
},
},
},
responses: {
"200": {
description: "登录成功并下发凭证",
content: {
"application/json": {
schema: {
type: "object",
properties: {
value: {
type: "object",
properties: {
accessToken: { type: "string", description: "全局访问令牌" },
user: {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
phone: { type: "string" },
},
},
},
},
},
},
},
},
},
},
},
},
"/api/common/user/corporations": {
get: {
tags: ["SSO & Security"],
summary: "获取账号名下可访问企业列表",
description: "拉取当前已登录账号授权的所有企业租户及其 Staff 身份。",
operationId: "listCorporations",
responses: {
"200": {
description: "企业与身份列表",
content: {
"application/json": {
schema: {
type: "object",
properties: {
items: {
type: "array",
items: { $ref: "#/components/schemas/CorporationItem" },
},
},
},
},
},
},
},
},
},
"/api/common/user/corporations/{corpId}/switch": {
post: {
tags: ["SSO & Security"],
summary: "切换工作企业上下文",
description: "切换当前会话至指定企业租户,并签发该企业的专属 Session。",
operationId: "switchCorporation",
parameters: [
{ name: "corpId", in: "path", required: true, schema: { type: "string" }, description: "目标企业 ID" },
],
responses: {
"200": {
description: "切换结果",
content: {
"application/json": {
schema: {
type: "object",
properties: {
value: {
type: "object",
properties: {
activeCorpId: { type: "string" },
staffId: { type: "string" },
},
},
},
},
},
},
},
},
},
},
"/api/open/oauth2/auth": {
post: {
tags: ["EASO & Piper Auth"],
summary: "EASO 换票 Step 1: 获取授权码",
description: "使用主站会话 Cookie 和 appKey 获取临时 code。",
operationId: "easoGetAuthCode",
responses: {
"200": {
description: "临时授权码",
content: {
"application/json": {
schema: {
type: "object",
properties: {
code: { type: "string", description: "临时授权码" },
},
},
},
},
},
},
},
},
"/api/open/oauth2/token": {
post: {
tags: ["EASO & Piper Auth"],
summary: "EASO 换票 Step 2: 换取 AccessToken",
description: "使用授权码 code 换取平台接口访问 Token 与 RefreshToken。",
operationId: "easoGetToken",
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
required: ["code", "appKey", "appSecret"],
properties: {
code: { type: "string" },
appKey: { type: "string" },
appSecret: { type: "string" },
grant_type: { type: "string", default: "authorization_code" },
},
},
},
},
},
responses: {
"200": {
description: "平台 Token 响应",
content: {
"application/json": {
schema: {
type: "object",
properties: {
access_token: { type: "string" },
refresh_token: { type: "string" },
expires_in: { type: "integer" },
},
},
},
},
},
},
},
},
"/api/open/oauth2/user_info": {
get: {
tags: ["EASO & Piper Auth"],
summary: "EASO 换票 Step 3: 获取当前开放平台用户信息",
description: "使用 AccessToken 获取当前用户的 openId 与企业绑定身份。",
operationId: "easoGetUserInfo",
responses: {
"200": {
description: "用户信息",
content: {
"application/json": {
schema: {
type: "object",
properties: {
openId: { type: "string" },
corpId: { type: "string" },
name: { type: "string" },
},
},
},
},
},
},
},
},
"/api/open/oauth2/token/refresh": {
post: {
tags: ["EASO & Piper Auth"],
summary: "EASO 令牌无感刷新",
description: "使用 refresh_token 换取新的 30 天 accessToken。",
operationId: "easoRefreshToken",
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
required: ["refresh_token"],
properties: {
refresh_token: { type: "string" },
grant_type: { type: "string", default: "refresh_token" },
},
},
},
},
},
responses: {
"200": {
description: "新 Token",
content: {
"application/json": {
schema: {
type: "object",
properties: {
access_token: { type: "string" },
refresh_token: { type: "string" },
expires_in: { type: "integer" },
},
},
},
},
},
},
},
},
"/api/v2/datalink/platform/search": {
get: {
tags: ["Platforms & Apps"],
summary: "获取企业自建应用列表",
description: "查询指定企业下已启用的自建应用与平台实例列表。",
operationId: "searchPlatforms",
parameters: [
{ name: "corpId", in: "query", required: true, schema: { type: "string" }, description: "企业 ID" },
{ name: "scope", in: "query", schema: { type: "string", default: "enable" } },
],
responses: {
"200": {
description: "应用列表",
content: {
"application/json": {
schema: {
type: "object",
properties: {
items: {
type: "array",
items: { $ref: "#/components/schemas/PlatformItem" },
},
},
},
},
},
},
},
},
},
"/api/easo/pipelines/logs": {
get: {
tags: ["Workflows & Pipelines"],
summary: "获取应用下的工作流列表与日志",
description: "按自建应用 ID 分页查询名下的工作流及最近执行日志。",
operationId: "listWorkflowsByPlatform",
parameters: [
{ name: "platformId", in: "query", required: true, schema: { type: "string" } },
{ name: "number", in: "query", schema: { type: "integer", default: 1 } },
{ name: "pageSize", in: "query", schema: { type: "integer", default: 20 } },
],
responses: standardResponse("工作流分页列表", { $ref: "#/components/schemas/WorkflowPageData" }),
},
},
"/api/easo/stats": {
get: {
tags: ["Workflows & Pipelines"],
summary: "获取工作流运行统计",
description: "统计指定应用下工作流的成功、失败及总触发次数。",
operationId: "getWorkflowStats",
parameters: [
{ name: "platformId", in: "query", required: true, schema: { type: "string" } },
],
responses: standardResponse("工作流运行统计", { $ref: "#/components/schemas/WorkflowStatsData" }),
},
},
"/api/easo/charge": {
get: {
tags: ["Workflows & Pipelines"],
summary: "获取工作流配额与计费信息",
description: "查询当前企业工作流运行调用次数与配额剩余。",
operationId: "getWorkflowCharge",
responses: standardResponse("配额信息", { $ref: "#/components/schemas/WorkflowChargeData" }),
},
},
"/api/easo/pipelines/{pipelineId}": {
get: {
tags: ["Workflows & Pipelines"],
summary: "获取工作流详情与 DSL 节点图",
description: "查询指定工作流的完整配置、触发器与节点链路图谱(code-js2, loop, sql 等)。",
operationId: "getWorkflowDetail",
parameters: [
{ name: "pipelineId", in: "path", required: true, schema: { type: "string" } },
],
responses: standardResponse("工作流完整详情", { $ref: "#/components/schemas/WorkflowDetailData" }),
},
},
"/api/easo/pipelines/state/{pipelineId}": {
put: {
tags: ["Workflows & Pipelines"],
summary: "启用或停用工作流",
description: "切换工作流运行状态(1: 启用, 0: 停用)。",
operationId: "toggleWorkflowState",
parameters: [
{ name: "pipelineId", in: "path", required: true, schema: { type: "string" } },
{ name: "state", in: "query", required: true, schema: { type: "integer", enum: [0, 1] } },
],
responses: {
"200": {
description: "状态更新成功",
},
},
},
},
"/api/easo/jobs/running": {
get: {
tags: ["Jobs & Execution"],
summary: "获取运行中的任务实例",
description: "查询工作流正在执行的调试(DEBUG)或生产(PROD)任务列表。",
operationId: "listRunningJobs",
parameters: [
{ name: "pipelineId", in: "query", required: true, schema: { type: "string" } },
{ name: "runType", in: "query", schema: { type: "string", enum: ["DEBUG", "PROD"], default: "DEBUG" } },
],
responses: standardResponse("任务实例列表", {
type: "array",
items: { $ref: "#/components/schemas/WorkflowJobItem" },
}),
},
},
"/api/easo/dsl/all": {
get: {
tags: ["Workflows & Pipelines"],
summary: "获取企业全部 DSL 规则配置",
description: "查询企业下所有生效的 DSL 脚本规则。",
operationId: "listAllDsl",
responses: standardResponse("DSL 规则列表", {
type: "array",
items: { $ref: "#/components/schemas/WorkflowDslItem" },
}),
},
},
"/api/easo/common/staffs": {
get: {
tags: ["Staffs & Webhooks"],
summary: "获取企业员工通讯录列表",
description: "查询企业内部或外部员工名单,用于工作流执行人与节点通知映射。",
operationId: "listCommonStaffs",
parameters: [
{ name: "external", in: "query", schema: { type: "boolean", default: false } },
],
responses: standardResponse("员工列表", {
type: "array",
items: { $ref: "#/components/schemas/StaffItem" },
}),
},
},
"/api/webhook/{pipelineId}": {
get: {
tags: ["Staffs & Webhooks"],
summary: "获取工作流 Webhook 触发配置",
description: "查询指定工作流的 Webhook URL 入口与密钥配置。",
operationId: "getWebhookInfo",
parameters: [
{ name: "pipelineId", in: "path", required: true, schema: { type: "string" } },
],
responses: standardResponse("Webhook 配置", { $ref: "#/components/schemas/WebhookInfoData" }),
},
},
"/api/easo/pipelines/{pipelineId}/sampleData": {
post: {
tags: ["Workflows & Pipelines"],
summary: "提取工作流调试/采样数据",
description: "触发工作流节点采样数据提取,用于脚本调试与输入校验。",
operationId: "sampleWorkflowData",
parameters: [
{ name: "pipelineId", in: "path", required: true, schema: { type: "string" } },
],
responses: {
"200": {
description: "采样数据",
content: {
"application/json": {
schema: {
type: "object",
properties: {
data: { type: "object" },
type: { type: "string" },
},
},
},
},
},
},
},
},
},
components: {
schemas: {
ErrorResponse: {
type: "object",
properties: {
code: { type: "string" },
message: { type: "string" },
details: { type: "object" },
},
},
CorporationItem: {
type: "object",
properties: {
id: { type: "string", description: "企业 ID" },
name: { type: "string", description: "企业名称" },
staffId: { type: "string", description: "员工 ID" },
role: { type: "string", description: "角色权限" },
},
},
PlatformItem: {
type: "object",
properties: {
id: { type: "string", description: "自建应用 ID" },
name: { type: "string", description: "应用名称" },
code: { type: "string", description: "应用标识 Code" },
icon: { type: "string" },
status: { type: "string" },
},
},
WorkflowPageData: {
type: "object",
properties: {
items: {
type: "array",
items: { $ref: "#/components/schemas/WorkflowItem" },
},
total: { type: "integer" },
number: { type: "integer" },
pageSize: { type: "integer" },
},
},
WorkflowItem: {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
description: { type: "string" },
state: { type: "integer", description: "1: 启用, 0: 停用" },
platformId: { type: "string" },
updatedAt: { type: "string" },
},
},
WorkflowStatsData: {
type: "object",
properties: {
totalCount: { type: "integer" },
successCount: { type: "integer" },
failCount: { type: "integer" },
},
},
WorkflowChargeData: {
type: "object",
properties: {
used: { type: "integer" },
total: { type: "integer" },
remaining: { type: "integer" },
},
},
WorkflowDetailData: {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
state: { type: "integer" },
nodes: { type: "array", items: { type: "object" }, description: "节点列表 (含 code-js2, loop, sql 等)" },
links: { type: "array", items: { type: "object" }, description: "节点连线" },
},
},
WorkflowJobItem: {
type: "object",
properties: {
jobId: { type: "string" },
pipelineId: { type: "string" },
status: { type: "string" },
startTime: { type: "string" },
},
},
WorkflowDslItem: {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
content: { type: "string" },
},
},
StaffItem: {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
email: { type: "string" },
cellphone: { type: "string" },
},
},
WebhookInfoData: {
type: "object",
properties: {
webhookUrl: { type: "string" },
token: { type: "string" },
},
},
},
},
};
mkdirSync(dirname(outputFile), { recursive: true });
writeFileSync(outputFile, `${JSON.stringify(spec, null, 2)}\n`);
console.log(`✓ Generated raw downstream OpenAPI: ${outputFile}`);
+16 -5
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
set -e
REPO="yunyingk/hose-serve-tool"
REPO="yunyingk/hose-use"
echo "==> Detecting platform and architecture..."
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
@@ -118,15 +118,25 @@ TMP_FILE="$(mktemp)"
DOWNLOAD_SUCCESS=false
# 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}"
# 1. Try direct GitHub Releases
if download_candidate "$GITHUB_URL" "$TMP_FILE" "GitHub Releases (Direct)"; then
DOWNLOAD_SUCCESS=true
# 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
DOWNLOAD_SUCCESS=true
fi
fi
# 2. Try Fast CDN Proxy Fallback
# 2. Try direct GitHub Releases
if [ "$DOWNLOAD_SUCCESS" = "false" ]; then
if download_candidate "$GITHUB_URL" "$TMP_FILE" "GitHub Releases (Direct)"; then
DOWNLOAD_SUCCESS=true
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
DOWNLOAD_SUCCESS=true
@@ -166,4 +176,5 @@ echo " 1. Login: hose-use auth login --phone=177... --password=..."
echo " 2. List corps: hose-use corps list"
echo " 3. List workflows: hose-use workflow list"
echo " 4. Switch mode: hose-use config mode stateless"
echo " 5. Self-update: hose-use update"
echo ""
+72 -80
View File
@@ -1,105 +1,97 @@
---
name: hose-use
description: 合思/易快报 (ekuaibao) 企业 SaaS CLI 命令行工具与底层 SDK。支持多账号纯 API 登录、30天 Token 自动无感续杯、多企业租户管理、有状态/无状态模式切换、自建应用扫描与跨应用工作流聚合检索。
description: "v0.5.1: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据费用检索与下钻、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
metadata:
version: 0.5.1
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.5.1)
---
# hose-use (合思/易快报企业级 CLI 与底层 SDK)
# hose-use (v0.5.2)
`hose-use` 是面向合思/易快报 SaaS、开发者与 AI 智能体的高性能交互工具。
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
## 核心架构原则
---
- **纯 API 认证**:内置 RSA PKCS#1 密码加密与统一认证中心握手,无需浏览器滑块即可登录。
- **全自动无感续杯**:内置 401 拦截与预检换票机制,Token 到期自动刷新并重试,零人工介入。
- **多账号与多身份分层**:支持一个手机号管理 13+ 家企业;支持同一企业下多身份(`corpId@accountId`)共存。
- **有状态 / 无状态双模式**:
- **有状态 (Stateful)**:自动记忆默认企业,命令无需反复加 `--corp`。
- **无状态 (Stateless)**:严格要求 `--corp <corpId>`,防止多租户或 Agent 误操作。
## Agent 执行原则 (First Rules)
1. **通道自适应**:将 CLI/MCP 视为 Agent 的执行通道,而不是要求用户学习命令行。Agent 应主动将用户的自然语言诉求转换为具体的 CLI 命令;严禁要求用户手动拼装命令行参数。
2. **多租户优先探查**:在需要企业参数前,优先执行 `hose corps list`。如果目标企业已配置,通过企业名称映射出对应的 `id` 并作为 `--corp=<id>` 传入;不要向普通用户询问底层 `corpId`。
3. **输出防护与大报文处理**:
- 面对单据明细、实体字典、工作流等大数据量查询,优先使用 `--json -o <path>` 本地转储或使用 `--limit` 限制分页;
- 严禁盲目使用 `--full` 将上万行原始报文一次性塞入上下文;
- 永远解析 JSON stdout,不要从格式化表格的终端字符中正则刮取数据。
4. **无状态与并发安全**:Agent 在自动化批处理或会话中,建议使用无状态模式(添加 `--stateless` 或显式指定 `--corp=<id>`),避免多任务并发切换全局状态发生冲突。
---
## 意图路由导航 (Route By Intent)
| 用户意图 / 场景 | 推荐命令 | 深入参考文档 |
|---|---|---|
| 首次登录 / 账密认证 / Token过期 / 多账号 | `hose auth login`, `hose auth status`, `hose auth refresh` | [references/auth.md](references/auth.md) |
| 代客协助凭证导入 / 探针连通性诊断 | `hose auth import`, `hose probe` | [references/auth.md](references/auth.md) |
| 企业租户切换 / 查看当前企业 | `hose corps list`, `hose corps switch <id>` | [references/auth.md](references/auth.md) |
| 报销单据检索 / 费用明细下钻 / 中文字典 | `hose bill list`, `hose bill get <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据 Web 详情直达链接生成 | `hose bill link <单号|ID>` | [references/bill.md](references/bill.md) |
| 单据实体模型与字段元数据查询 | `hose bill schema` | [references/bill.md](references/bill.md) |
| 企业通讯录检索 / 员工档案 / 防爆保护 | `hose contact search`, `hose contact list`, `hose contact get` | [references/contact.md](references/contact.md) |
| 跨自建应用工作流聚合检索 | `hose workflow list`, `hose platform list` | [references/workflow.md](references/workflow.md) |
| 特定任务节点扫描 (如脚本/Webhook) | `hose workflow find --task=code-js2` | [references/workflow.md](references/workflow.md) |
| 工作流详情与开通切换 | `hose workflow get`, `hose workflow toggle` | [references/workflow.md](references/workflow.md) |
| 常驻守护进程管理 / 后台运行 | `hose service start`, `hose service status` | [references/service.md](references/service.md) |
| 启动本地 HTTP 服务 / 打开可视化交互文档 | `hose http --port=8888` (访问 `/docs`) | [references/service.md](references/service.md) |
| CLI 同进程执行网关 / REST 接口调用 | `POST /api/cli`, `GET /v1/corps` | [references/service.md](references/service.md) |
| 导出标准 OpenAPI 3.1.0 JSON 规范 | `hose openapi`, `hose openapi --raw` | [references/service.md](references/service.md) |
| 一键自动自更新 / 查看版本发布日志 | `hose update`, `hose update --changelog` | `hose update --help` |
---
## 常用命令速查
### 1. 认证管理 (`hose-use auth`)
```bash
# 纯 API 账密全自动登录(自动获取 RSA 公钥加密并拉取旗下所有企业)
hose-use auth login --phone=17718556446 --password=...
# 1. 认证与企业
hose auth login --phone=17718556446 --password=... # 纯 API 账密自动登录
hose auth status # 查看 Token 剩余有效期与登录账号
hose corps list # 查看企业租户列表
hose corps switch ID01MCcOgJl1td # 切换工作企业
hose probe # 诊断当前企业接口连通性
# 导入 F12 抓包复制的 cURL 或 Request Headers
hose-use auth import --raw="curl ..."
# 2. 企业通讯录与人员 (默认严格防爆限流,优先 search)
hose contact search 王硕 # 模糊搜索员工工号、邮箱与电话
hose contact list --limit=20 # 采样查看企业通讯录(带防爆截断保护)
hose contact list --json -o /tmp/staffs.json # 导出全量通讯录至本地磁盘并防爆
hose contact get ID01MCcOgJl1td:3LsanKdS7Uo000 # 精准获取指定员工档案
# 查看当前登录状态与活跃账号
hose-use auth status
# 3. 单据与费用
hose bill list # 查看最新单据与报销记录
hose bill link CL20260901001 # 生成官方 Web 详情直达免密跳转链接
hose bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘
hose bill get n0GMIM0dkQmKbS # 精准查询单据详情 (中文字段映射)
hose bill schema # 查询单据实体元数据字典
# 一键批量刷新名下所有企业的最新 30 天 AccessToken
hose-use auth refresh
# 4. 自建应用与工作流
hose platform list # 查看自建应用列表
hose workflow list # 聚合扫描全部应用下的工作流
hose workflow find --task=code-js2 # 查找部署了代码节点的工作流
hose workflow get wf_01k83y... # 查看指定工作流节点拓扑
# 查看已保存的全部主账号
hose-use auth accounts
```
### 2. 多企业租户管理 (`hose-use corps`)
```bash
# 列出名下所有已授权企业
hose-use corps list
# 切换当前工作企业 (有状态模式下自动持久化)
hose-use corps switch uzU7pcWfScck00
# 查看当前激活企业信息
hose-use corps current
```
### 3. 全局运行模式 (`hose-use config`)
```bash
# 查看全局运行模式与配置文件路径
hose-use config show
# 切换为无状态模式 (Stateless)
hose-use config mode stateless
# 切换为有状态模式 (Stateful)
hose-use config mode stateful
```
### 4. 平台与工作流管理 (`hose-use workflow` / `hose-use platform`)
```bash
# 汇总查看企业下所有工作流 (跨自建应用聚合)
hose-use workflow list
# 查看指定工作流详情与节点结构
hose-use workflow get 829729467412037634
# 搜索包含指定节点类型的工作流 (如 code-js2, http 等)
hose-use workflow find --task=code-js2
# 启用 / 停用工作流 (1: 启用, 0: 停用)
hose-use workflow toggle <pipelineId> --state=1
# 查看企业下所有启用的自建应用
hose-use platform list
```
### 5. 诊断与 MCP 服务 (`hose-use probe` / `hose-use mcp`)
```bash
# 连通性与 EASO 平台鉴权诊断
hose-use probe
hose-use probe --corp=uzU7pcWfScck00
# 启动极简 MCP stdio 服务
hose-use mcp serve
# 5. 服务与守护进程
hose http --port=8888 # 启动前台 HTTP 服务与交互式文档
hose service start # 后台启动常驻守护进程服务
hose service status # 查看常驻守护进程运行状态与端点
hose service logs # 查看常驻守护进程日志
hose service stop # 停止后台常驻守护进程
```
---
## 全局选项
- `--corp=<id>`:临时指定操作的企业/身份 ID
- `--json`, `-j`:输出 JSON 结构化格式(适合脚本解析)
- `--corp=<id>`:临时指定操作的企业 ID(单次覆盖默认企业)
- `--json`, `-j`:以标准 JSON 结构化输出结果
- `--output-file, -o <path>`:将结果直接安全写入本地文件,仅返回精简摘要
- `--full`:全量输出大报文(绕过 200KB 体积防爆拦截)
- `--stateless`:单次命令强制以无状态模式执行
- `--stateful`:单次命令强制以有状态模式执行
- `--help, -h`:查看命令帮助与参数说明
+16
View File
@@ -0,0 +1,16 @@
schema_version: "v1"
name: "hose-use"
description: "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业多租户切换、单据明细检索、自建应用工作流管理、内置 HTTP 服务与常驻守护进程。"
auth:
type: "none"
tools:
- name: "hose_cli"
description: "执行合思/易快报 hose-use CLI 命令。详细命令语法请参考 hose-use skill 文档。"
parameters:
type: "object"
properties:
command:
type: "string"
description: "完整的 hose-use 命令字符串,例如 'bill list --json', 'workflow find --task=code-js2', 'service status'"
required:
- "command"
+111
View File
@@ -0,0 +1,111 @@
# 认证、多租户与运行模式指南 (Authentication & Multi-Tenant Guide)
本参考专卷详细说明 `hose-use` 的登录鉴权、会话维护、代客凭证、企业租户切换以及全局运行模式。
---
## 1. 账号认证与登录 (`auth`)
`hose-use` 实现了**纯 API 级 RSA 密码加密登录**,无需通过浏览器抓包或人工复制 Cookie。
### 纯 API 账密自动登录
```bash
# 自动通过公钥加密密码,登录并拉取名下全部企业凭据写入本地配置
hose-use auth login --phone=17718556446 --password=YourPassword123
```
- **核心逻辑**:向合思主站请求 RSA 公钥,将密码密文提交到 `/api/auth/login`;成功后自动遍历用户关联的企业租户,调用换票接口写入对应的企业配置。
### 查看登录状态与 Token 有效期
```bash
hose-use auth status
```
- 自动计算并输出自然语言剩余有效期(如 `29天23小时后过期`),清晰展示当前账号与当前企业。
### 30 天无感 Token 刷新
```bash
hose-use auth refresh
```
- 主动调用主站会话刷新接口,续期当前企业凭据的 AccessToken。
### 代客协助凭证导入
```bash
hose-use auth import \
--name="CSM代客" \
--corp-id="Cxa3oOtQi2eS$g" \
--staff-id="Cxa3oOtQi2eS$g:2HQbkGx2DgnM00" \
--token="1361c470-3d7c-4a3a-a1fb-e946aee5723b"
```
- **智能探测机制**:若 `corp-id` 包含 `$UNITY` 或特殊字符,系统会自动探测代客服务会话接口,解析 13 位过期毫秒时间戳并正确建立凭证映射。
### 多账号清单
```bash
hose-use auth accounts
```
- 查看本地已记录的手机号多账号清单及其关联的企业列表。
---
## 2. 企业租户管理 (`corps`)
### 列出所有企业
```bash
hose-use corps list
hose-use corps list --json
```
### 切换当前活跃企业
```bash
hose-use corps switch uzU7pcWfScck00
```
- 在有状态(stateful)模式下,此命令将更新全局默认企业 ID。
### 查看当前企业
```bash
hose-use corps current
```
---
## 3. 全局配置与模式管理 (`config`)
### 运行模式(有状态 vs 无状态)
- **有状态模式 (Stateful,默认)**:
- 会话状态保存在 `~/.config/hose-use/config.json` 中;
- 执行 `corps switch` 后,后续命令自动继承当前选中的企业。
- **无状态模式 (Stateless,推荐给 Agent)**:
- 不依赖全局状态切换,所有命令通过 `--corp=<id>` 显式指定,防止并发操作相互干扰;
- 通过环境变量 `HOSE_STATELESS=1` 或单次参数 `--stateless` 开启。
```bash
# 查看当前配置
hose-use config show
# 查看多层级配置发现路径诊断
hose-use config paths
# 切换全局运行模式
hose-use config mode stateless
hose-use config mode stateful
```
### 多层级配置发现顺序
1. 环境变量 `HOSE_ENTERPRISES_DIR`(最高优先级)
2. 当前工作区根目录下的 `enterprises/`
3. 用户主目录配置:`~/.config/hose-use/enterprises/`
4. 历史兼容缓存:`~/.cache/ekb-mcp/enterprises/`
---
## 4. 连通性探针 (`probe`)
```bash
# 诊断当前企业的鉴权链路与平台可用性
hose-use probe
# 诊断指定企业的连通性
hose-use probe --corp=uzU7pcWfScck00
```
- **探针行为**:
1. 验证主站 Session 是否有效;
2. 测试 EASO 平台 SSO 握手是否成功;
3. 输出各环节毫秒级延迟与 HTTP 状态。
+95
View File
@@ -0,0 +1,95 @@
# 单据与费用明细指南 (Bill & Expense Guide)
本参考专卷详细说明合思单据检索、费用报销明细下钻、中文标签映射字典以及大报文防爆机制。
---
## 1. 单据列表检索 (`bill list`)
### 基础查询
```bash
# 查看当前企业最近的单据与报销列表 (默认表格格式)
hose-use bill list
# 指定企业查询并以 JSON 输出
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)。
```bash
# 查询审批通过的差旅报销单
hose-use bill list --type=TRAVEL_EXPENSE --status=APPROVED --limit=50
```
---
## 2. 单据详情精准下钻 (`bill get`)
支持传入**单据编号**(如 `CL20260903001`)或合思全局**单据 ID**(如 `n0GMIM0dkQmKbS`):
```bash
hose-use bill get n0GMIM0dkQmKbS
hose-use bill get CL20260903001 --json
```
### 中文字段智能映射字典
合思底层原生单据接口通常返回类似 `c0_1`, `d1_4`, `u_fee_amount` 等混淆字段。
`hose-use` 内置**动态中文 Label 字典转换引擎**:
- 自动提取单据所属模板的中文配置定义;
- 将 `c0_1` 翻译为清晰的 `费用发生日期`;
- 将 `d1_4` 翻译为 `费用类型/科目`;
- 将 `u_fee_amount` 翻译为 `报销金额`;
- 向 AI 与用户同时提供规范化的结构体与原始值对照。
---
## 3. 单据实体元数据字典 (`bill schema`)
用于探查当前企业所有单据实体、字段类型与扩展属性定义:
```bash
hose-use bill schema
hose-use bill schema --json
```
---
## 4. 上下文防爆保护与安全转储
合思复杂的报销单通常携带大量明细行、发票 OCR 原生报文与附件列表,查询结果动辄数万行(几百 KB 到数 MB)。
### 默认 200KB 体积熔断保护
在未附加放行参数时,若序列化报文超过 200,000 字节,`hose-use` 会自动阻断并返回防御提示:
```text
[Output Protected] 输出内容超过 200KB 体积保护阈值 (284,520 bytes)。
为防止过大输出打爆 AI 智能体上下文窗口,建议使用:
-o, --output-file <path> 将全量结果保存至本地文件
--full 强制全量输出
```
### 本地安全转储 (`--output-file` / `-o`)
将巨型报文直接直写到磁盘,终端/AI 仅输出轻量摘要:
```bash
hose-use bill list --json -o /tmp/bills_full.json
```
**返回摘要**:
```json
{
"outputFile": "/tmp/bills_full.json",
"bytes": 284520
}
```
### 强制全量放行 (`--full`)
明确需要捕获全部 stdout 时添加 `--full`:
```bash
hose-use bill list --json --full
```
### 全链路敏感信息脱敏
输出流中的 `accessToken`、`token`、`Bearer` 以及密码、秘钥等均由底层的 `redactSensitiveText` 自动清洗过滤,保障会话与调用日志安全。
+65
View File
@@ -0,0 +1,65 @@
# hose-use 专卷:企业通讯录与人员档案 (Contact Domain)
本文件是 `skills/hose-use/` 的领域参考专卷,详述合思/易快报企业通讯录的人员检索、防爆保护机制与单人档案下钻。
---
## 核心设计与防爆原则
企业通讯录往往包含上千乃至上万名员工。**无节制全量拉取会瞬间冲垮 Agent 上下文,导致会话熔断或崩溃。**
因此,`hose-use` 遵循以下防爆安全原则:
1. **搜索优先 (Search First)**:优先使用 `hose contact search <关键词>` 进行局部模糊匹配(仅返回 1~5 条命中结果);
2. **列表默认限流截断 (Default Limit 20)**:`hose contact list` 默认截断只输出前 20 条,并打印总人数统计和精准检索指引;
3. **大报文转储落地 (`-o / --output-file`)**:若需全量导出通讯录供复杂分析,使用 `-o` 将全量人员安全落盘到磁盘,仅向 Agent 回传精简的文件路径元数据;
4. **全量放行保护 (`--full`)**:仅在确定企业体量较小或明确需要全量时方可显式加上 `--full`。
---
## CLI 命令速查
```bash
# 1. 模糊搜索人员 (支持姓名、邮箱、手机号、staffId)
hose contact search 王硕
hose contact search xiezihao@hosecloud.com
hose contact search 18600612659
# 2. 采样查看企业通讯录 (默认截断前 20 条,防上下文溢出)
hose contact list
hose contact list --limit=50
# 3. 大报文安全落地到磁盘 (返回精简文件元数据,保护 LLM 终端)
hose contact list --json -o /tmp/all_staffs.json
# 4. 精确下钻查看指定人员详细档案
hose contact get ID01MCcOgJl1td:3LsanKdS7Uo000
# 5. 指定特定企业租户检索
hose contact search 李 --corp=ID01MCcOgJl1td
```
---
## MCP 工具调用
在单工具网关模式下,推荐使用 `hose_cli` 触发:
```json
{
"command": "contact search 王硕"
}
```
在全量模式(`HOSE_MCP_MODE=all`)下,提供以下细粒度工具:
- `contact_search(keyword: string, limit?: number)`:返回匹配的员工列表
- `contact_get(staffId: string)`:获取单条员工详情
- `contact_list(limit?: number, allowFull?: boolean)`:带保护的企业通讯录列表
---
## 业务联动典型场景
### 1. 查找某人发起的单据
当用户要求“帮我查一下王硕提交的报销单”时:
1. 先通过 `hose contact search 王硕` 获取其 `staffId`(如 `ID01MCcOgJl1td:3LsanKdS7Uo000`);
2. 再通过 `hose bill list --keyword=王硕` 或根据 `staffId` 过滤单据明细;
3. 获得单据后,通过 `hose bill link <单号>` 生成官方 Web 直达链接反馈给用户。
+105
View File
@@ -0,0 +1,105 @@
# 服务、守护进程与 API 网关指南 (Service & HTTP Gateway Guide)
本参考专卷详细说明 `hose-use` 内置的轻量 HTTP Server、常驻 Service 守护进程、Scalar 交互式文档以及 OpenAPI 规范导出能力。
---
## 1. 常驻 Service 守护进程 (`service`)
常驻守护进程允许 `hose-use` 在后台全天候运行,支持远程/本地无子进程开销调用 CLI,同时持久化存储 PID 与运行日志。
### 常用指令
```bash
# 启动常驻后台守护进程 (自动落盘 PID 到 ~/.config/hose-use/service.pid)
hose-use service start
# 检查常驻服务运行状态、PID、端口与访问端点
hose-use service status
# 查看常驻服务最近运行日志
hose-use service logs
# 重启常驻服务
hose-use service restart
# 优雅停止常驻服务 (清理 PID 文件)
hose-use service stop
# 容器/前台守护运行模式 (供 Dockerfile 或 Supervisor 使用)
hose-use service run
```
### 自愈保护机制
每次执行 `service status` 或 `service start` 时,系统会自动探测记录的 PID:
- 若进程已终止(孤儿 PID)或 PID 被其它非 `hose` 进程复用,系统会自动执行自愈逻辑,清理失效的 PID 文件。
---
## 2. 前台 HTTP 服务 (`http` / `serve`)
在当前终端前台启动 HTTP 服务并输出直观的服务信息面板,按 `Ctrl+C` 即可平滑退出:
```bash
# 启动本地 HTTP 服务 (默认端口 8888,主机 127.0.0.1)
hose-use http
# 指定自定义端口与主机
hose-use http --port=9999 --host=0.0.0.0
```
---
## 3. HTTP 路由端点一览
| 方法 | 端点 | 说明 |
|---|---|---|
| `GET` | `/` | 服务元信息、版本号与端点导航 |
| `GET` | `/health` | 存活健康探针(返回 `{ "status": "ok", "version": "..." }`) |
| `GET` | `/docs` | 基于 **Scalar API Reference** 的沉浸式交互文档界面 |
| `GET` | `/openapi.json` | 包装层标准 OpenAPI 3.1.0 JSON 规范 |
| `GET` | `/raw-openapi.json` | 合思原生下游 OpenAPI 规范 |
| `POST` | `/api/cli` | **CLI 同进程执行网关**(免 spawn 子进程) |
| `GET` | `/v1/corps` | RESTful 风格企业租户列表与运行模式 |
### 同进程 CLI 执行网关 (`POST /api/cli`)
通过 HTTP POST 提交任意 CLI 命令字符串,在主服务进程内部直接分发执行,毫秒级响应,无需拉起 Node/Bun 子进程:
```bash
curl -X POST http://127.0.0.1:8888/api/cli \
-H "Content-Type: application/json" \
-d '{"command": "corps list --json"}'
```
**响应结构**:
```json
{
"success": true,
"stdout": "...",
"stderr": "",
"exitCode": 0,
"data": {
"corporations": [ ... ]
}
}
```
---
## 4. OpenAPI 规范导出 (`openapi`)
```bash
# 查看所有 API 路径与概要一览
hose-use openapi paths
# 查看合思原生下游全量 API 路径
hose-use openapi --raw paths
# 查看 OpenAPI 规范元数据概览
hose-use openapi info
# 输出包装层标准 OpenAPI 3.1.0 JSON (适合导入 Postman/Swagger/Apifox)
hose-use openapi
# 输出原生下游全量 OpenAPI 3.1.0 JSON
hose-use openapi --raw
```
+75
View File
@@ -0,0 +1,75 @@
# 工作流与自建应用指南 (Workflow & Platform Guide)
本参考专卷详细说明合思自建应用(EASO 开放平台)的工作流跨域扫描、任务节点聚合检索与自动化开通。
---
## 1. 自建应用管理 (`platform`)
合思企业支持创建多个自建应用,每个应用承载独立的业务流程与工作流。
```bash
# 列出当前企业下全部已开通的自建应用
hose-use platform list
hose-use platform list --json
```
**输出关键字段**:
- `appId`:应用全局唯一标识
- `appName`:应用中文名称
- `status`:应用运行状态(ENABLE / DISABLE)
- `createdAt` / `updatedAt`:创建与最后更新时间
---
## 2. 跨应用工作流聚合检索 (`workflow list`)
合思官方后台一次只能查看单个自建应用的工作流。`hose-use` 实现了跨应用并发聚合扫描:
```bash
# 查看所有自建应用下的全部工作流汇总
hose-use workflow list
# 查看指定自建应用下的工作流
hose-use workflow list --app-id=app_01j72x...
```
---
## 3. 工作流任务节点精准扫描 (`workflow find`)
用于快速定位企业中部署了特定逻辑节点(如自定义 JS 脚本、飞书推送、钉钉同步等)的工作流:
```bash
# 搜索包含自定义代码节点 (code-js2) 的所有工作流
hose-use workflow find --task=code-js2
# 搜索包含飞书通知节点的工作流
hose-use workflow find --task=feishu-notify
# 模糊搜索包含关键词的工作流
hose-use workflow find --keyword="自动审批"
```
---
## 4. 工作流详情查询 (`workflow get`)
获取工作流的完整节点拓扑、参数配置与表达式定义:
```bash
hose-use workflow get wf_01k83y...
hose-use workflow get wf_01k83y... --json -o /tmp/workflow_detail.json
```
---
## 5. 工作流启用与关闭 (`workflow toggle`)
```bash
# 激活/启用指定工作流
hose-use workflow toggle wf_01k83y... --enable
# 停用指定工作流
hose-use workflow toggle wf_01k83y... --disable
```
+58 -7
View File
@@ -3,6 +3,7 @@ import {
fullSmsLogin,
fullBrowserSyncLogin,
sendSmsVerificationCode,
importCredentials,
importF12Credentials,
parseHeadersOrCurl,
refreshAccountCorporations,
@@ -14,7 +15,7 @@ import {
} from "../../core/auth/account-store.js";
import { createEkbClient } from "../../core/auth/ekb.js";
import { stringOption, booleanOption } from "../parser.js";
import { printJson, printKeyValue, printTable } from "../printer.js";
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
import { prompt } from "../helpers.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
@@ -171,13 +172,41 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
return { stdout: printJson(statusObj), stderr: "", exitCode: 0 };
}
const summary = printKeyValue({
const pairs: Record<string, unknown> = {
"当前活跃账号": activeAccount?.accountId || "未登录",
"当前激活企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "未配置",
"当前员工工号": currentCorp?.credentials.staffId || "-",
"凭证来源类型": currentCorp?.source || "-",
"员工真实姓名": currentCorp?.staffName || currentCorp?.session?.staffName || "-",
"凭证来源类型": formatSourceLabel(currentCorp?.source),
"Token 有效性": sessionValid ? "✅ 有效 (已通过 Session 验证)" : "❌ 无效或未连接",
});
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime),
};
if (currentCorp?.session) {
if (currentCorp.session.loginTime) {
pairs["会话创建时间"] = new Date(currentCorp.session.loginTime).toLocaleString("zh-CN", { hour12: false });
}
if (currentCorp.session.platform) {
pairs["官方平台类型"] = currentCorp.session.platform;
}
if (currentCorp.session.isAssistPlatform) {
pairs["协助调试模式"] = "是 (Assist Platform)";
if (currentCorp.session.operationUserName || currentCorp.session.operationUserId) {
pairs["协助操作人员"] = `${currentCorp.session.operationUserName || ""} (${currentCorp.session.operationUserId || ""})`.trim();
}
if (currentCorp.session.assistId) {
pairs["协助会话 ID"] = currentCorp.session.assistId;
}
}
if (currentCorp.session.cellphone) {
pairs["绑定手机号码"] = currentCorp.session.cellphone;
}
if (currentCorp.session.isAdmin !== undefined) {
pairs["是否企业管理"] = currentCorp.session.isAdmin ? "是" : "否";
}
}
const summary = printKeyValue(pairs);
return {
stdout: `====== 当前登录与企业状态 ======\n${summary}\n`,
@@ -209,7 +238,7 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
let name = stringOption(parsed.options, ["name"]);
if (!raw && !accessToken) {
raw = await prompt("请粘贴 F12 抓包文本 / cURL 命令行 (直接回车则手动逐项输入): ");
raw = await prompt("请粘贴抓包文本 / cURL 命令行 (直接回车则手动逐项输入): ");
}
if (raw) {
@@ -227,7 +256,7 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
return { stdout: "", stderr: "accessToken, corpId, staffId 均为必填!\n", exitCode: 1 };
}
const imported = await importF12Credentials({
const imported = await importCredentials({
accessToken,
corpId,
staffId,
@@ -238,8 +267,30 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
return { stdout: printJson(imported), stderr: "", exitCode: 0 };
}
const summaryPairs: Record<string, unknown> = {
"企业名称": imported.name,
"企业 ID": imported.id,
"员工工号": imported.credentials.staffId,
"员工姓名": imported.staffName || imported.session?.staffName || "-",
"凭证来源": formatSourceLabel(imported.source),
"过期时间": formatExpiresAt(imported.auth?.expiresAt || imported.session?.expTime),
"保存路径": `enterprises/${imported.id}.json`,
};
if (imported.session?.isAssistPlatform) {
summaryPairs["协助平台"] = "是 (Assist Platform 调试授权)";
if (imported.session.operationUserName || imported.session.operationUserId) {
summaryPairs["协助操作人"] = `${imported.session.operationUserName || ""} (${imported.session.operationUserId || ""})`.trim();
}
if (imported.session.assistId) {
summaryPairs["协助会话 ID"] = imported.session.assistId;
}
}
const summaryText = printKeyValue(summaryPairs);
return {
stdout: `[SUCCESS] 成功导入并保存企业凭证!\n企业名称: ${imported.name}\n企业 ID: ${imported.id}\n员工工号: ${imported.credentials.staffId}\n保存路径: enterprises/${imported.id}.json\n`,
stdout: `[SUCCESS] 成功导入并保存企业凭证!\n${summaryText}\n`,
stderr: "",
exitCode: 0,
};
+262
View File
@@ -0,0 +1,262 @@
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { printJson, printTable } from "../printer.js";
import { stringOption, numberOption } from "../parser.js";
import { createEkbClient } from "../../core/auth/ekb.js";
import {
searchAndFormatBills,
getBillByCodeOrId,
getFieldDictionary,
} from "../../domains/bill/tools.js";
export async function handleBillCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const corp = runtime.selectedCorp;
if (!corp) {
throw new Error(
"未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose auth login 登录。"
);
}
const client = await createEkbClient(corp);
const action = parsed.action?.toLowerCase();
const corpId = corp.corpId || corp.id;
switch (action) {
case "list":
case "search":
case undefined: {
const code = stringOption(parsed.options, ["code", "c"]);
const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"]);
const stage = stringOption(parsed.options, ["stage"]);
const state = stringOption(parsed.options, ["state", "s"]);
const count = numberOption(parsed.options, ["count", "limit", "n"], 20);
const result = await searchAndFormatBills(client, corpId, {
code,
keyword,
stage,
state,
count,
});
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId,
corpName: corp.name,
total: result.total,
returned: result.returned,
items: result.items,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "单据编号 (单号)", "单据名称", "阶段", "状态", "金额", "提交时间"];
const rows = result.items.map((b, idx) => [
idx + 1,
b.billCode,
b.billName,
b.stage || "-",
b.state || "-",
b.amount || "-",
b.submitDate || b.createTime || "-",
]);
const tableOutput = printTable(headers, rows);
const title = `====== 单据与费用明细列表 (企业: ${corp.name} | 总数: ${result.total} | 本次返回: ${result.returned}) ======\n`;
const tip = `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`;
return {
stdout: title + tableOutput + tip,
stderr: "",
exitCode: 0,
};
}
case "get":
case "show":
case "find": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) {
throw new Error("请提供要查询的单号或单据 ID: hose-use bill get <单号|ID>");
}
const bills = await getBillByCodeOrId(client, corpId, target);
if (bills.length === 0) {
if (runtime.jsonMode) {
return {
stdout: printJson({ found: false, code: target, message: "未找到匹配单据" }),
stderr: "",
exitCode: 1,
};
}
return {
stdout: "",
stderr: `[NOT FOUND] 在企业 [${corp.name}] 下未找到单号或 ID 为 [${target}] 的单据\n`,
exitCode: 1,
};
}
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId,
corpName: corp.name,
count: bills.length,
bills,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const outputs: string[] = [];
for (let i = 0; i < bills.length; i++) {
const b = bills[i];
outputs.push(`\n====== 单据详情 [${i + 1}/${bills.length}] (单号: ${b.billCode}) ======`);
outputs.push(` 单据 ID : ${b.billId}`);
outputs.push(` 单据名称 : ${b.billName}`);
if (b.title) outputs.push(` 单据标题 : ${b.title}`);
if (b.stage) outputs.push(` 业务阶段 : ${b.stage}`);
if (b.state) outputs.push(` 审批状态 : ${b.state}`);
if (b.amount) outputs.push(` 单据金额 : ${b.amount}`);
if (b.submitterId) outputs.push(` 提交人员 : ${b.submitterId}`);
if (b.submitDate) outputs.push(` 提交时间 : ${b.submitDate}`);
outputs.push(` 创建时间 : ${b.createTime}`);
outputs.push(` 更新时间 : ${b.updateTime}`);
outputs.push(`\n --- 结构化表单字段明细 ---`);
const detailEntries = Object.entries(b.details);
if (detailEntries.length === 0) {
outputs.push(` (无额外字段数据)`);
} else {
const maxKeyLen = Math.max(...detailEntries.map(([k]) => k.length), 0);
for (const [k, v] of detailEntries) {
const formattedVal = typeof v === "object" ? JSON.stringify(v) : String(v);
outputs.push(` ${k.padEnd(maxKeyLen + 2)}: ${formattedVal}`);
}
}
}
return {
stdout: outputs.join("\n") + "\n",
stderr: "",
exitCode: 0,
};
}
case "schema":
case "schemas":
case "entities": {
const { entities } = await getFieldDictionary(client, corpId, true);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId,
corpName: corp.name,
totalEntities: entities.length,
entities,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "实体 ID", "实体名称", "类型", "字段数"];
const rows = entities.map((e, idx) => [
idx + 1,
e.id,
e.name || "-",
e.type || "-",
e.fields.length,
]);
const tableOutput = printTable(headers, rows);
const title = `====== 单据实体与数据模型字典 (企业: ${corp.name} | 共 ${entities.length} 个实体) ======\n`;
return {
stdout: title + tableOutput + "\n",
stderr: "",
exitCode: 0,
};
}
case "link":
case "url": {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id", "c"]);
if (!target) {
return {
stdout: "",
stderr: "用法: hose bill link <单号或ID>",
exitCode: 1,
};
}
const items = await getBillByCodeOrId(client, corpId, target);
if (!items || items.length === 0) {
return {
stdout: "",
stderr: `未找到单据: ${target}`,
exitCode: 1,
};
}
const item = items[0];
const billId = item.billId;
const billCode = item.billCode || target;
const baseUrl = (corp.baseUrl || "https://app.ekuaibao.com").replace(/\/+$/, "");
const webUrl = `${baseUrl}/#/invoice/detail?id=${encodeURIComponent(billId)}&corporationId=${encodeURIComponent(corpId)}`;
if (runtime.jsonMode) {
return {
stdout: printJson(
{
code: billCode,
id: billId,
corpId,
corpName: corp.name,
url: webUrl,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const text = [
`====== 合思单据 Web 直达链接 ======`,
` 单据编号: ${billCode}`,
` 单据 ID : ${billId}`,
` 所属企业: ${corp.name} (${corpId})`,
` 直达链接:`,
` ${webUrl}`,
``,
`Markdown 链接: [查看单据 ${billCode}](${webUrl})`,
].join("\n");
return {
stdout: text + "\n",
stderr: "",
exitCode: 0,
};
}
default:
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号>, schema, link <单号>`);
}
}
+48 -1
View File
@@ -2,6 +2,9 @@ import {
loadGlobalConfig,
saveGlobalConfig,
resolveGlobalConfigFile,
resolveEnterprisesDirs,
resolveWritableEnterprisesDir,
getEnterprisesDirCandidates,
} from "../../core/config/loader.js";
import { printJson, printKeyValue } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
@@ -17,6 +20,10 @@ export async function handleConfigCommand(
case "get":
case "list":
return handleShow(parsed, runtime);
case "paths":
case "path":
case "dirs":
return handlePaths(parsed, runtime);
case "mode":
return handleMode(parsed, runtime);
case "set":
@@ -24,7 +31,7 @@ export async function handleConfigCommand(
default:
return {
stdout: "",
stderr: `未知 config 子命令: ${action}。支持: show, mode <stateful|stateless>, set <key> <val>\n`,
stderr: `未知 config 子命令: ${action}。支持: show, paths, mode <stateful|stateless>, set <key> <val>\n`,
exitCode: 1,
};
}
@@ -125,3 +132,43 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
exitCode: 0,
};
}
async function handlePaths(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const envDir = process.env.HOSE_ENTERPRISES_DIR;
const envUserDir = process.env.HOSE_USER_ENTERPRISES_DIR;
const envConfigFile = process.env.HOSE_CONFIG_FILE;
const existingDirs = resolveEnterprisesDirs();
const writableDir = resolveWritableEnterprisesDir();
const configFile = resolveGlobalConfigFile();
const candidates = getEnterprisesDirCandidates();
const data = {
configFile,
writableDir,
existingDirs,
env: {
HOSE_ENTERPRISES_DIR: envDir || null,
HOSE_USER_ENTERPRISES_DIR: envUserDir || null,
HOSE_CONFIG_FILE: envConfigFile || null,
},
candidates,
};
if (runtime.jsonMode) {
return { stdout: printJson(data), stderr: "", exitCode: 0 };
}
const output = printKeyValue({
"当前生效配置文件": configFile,
"凭证保存写入目录": writableDir,
"已发现企业目录": existingDirs.length ? existingDirs.join("\n ") : "无 (未发现任何有效企业目录)",
"环境变量指定目录": envDir || "未设置 (HOSE_ENTERPRISES_DIR)",
"全部目录候选链": candidates.join("\n "),
});
return {
stdout: `====== 配置路径诊断 (Config Paths) ======\n${output}\n`,
stderr: "",
exitCode: 0,
};
}
+155
View File
@@ -0,0 +1,155 @@
import { numberOption, stringOption } from "../parser.js";
import { printJson, printKeyValue, printTable } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import {
getStaffById,
listStaffsProtected,
searchStaffs,
DEFAULT_STAFF_LIST_LIMIT,
} from "../../domains/contact/tools.js";
export async function handleContactCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const corp = runtime.selectedCorp;
if (!corp) {
return {
stdout: "",
stderr: "未指定或未找到有效企业配置。请运行 'hose corps list' 或指定 '--corp=<id>'",
exitCode: 1,
};
}
const action = parsed.action || parsed.args[0] || "list";
const limit = numberOption(parsed.options, ["limit", "l"]);
// 1. 搜索: hose contact search <keyword> 或 hose contact find <keyword>
if (action === "search" || action === "find") {
const keyword = parsed.args[0] || stringOption(parsed.options, ["keyword", "query", "k"]) || "";
if (!keyword.trim()) {
return {
stdout: "",
stderr: "用法: hose contact search <关键词 (姓名/邮箱/工号)>",
exitCode: 1,
};
}
const results = await searchStaffs(corp, { keyword, limit });
if (runtime.jsonMode) {
return {
stdout: printJson({ count: results.length, keyword, staffs: results }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
if (results.length === 0) {
return {
stdout: `未找到匹配关键词 "${keyword}" 的员工。\n`,
stderr: "",
exitCode: 0,
};
}
const headers = ["姓名", "工号 / staffId", "邮箱", "手机号"];
const rows = results.map((s) => [
s.name || "-",
s.id,
s.email || "-",
s.cellphone || "-",
]);
return {
stdout: `====== 员工搜索结果 (关键词: "${keyword}", 找到 ${results.length} 人) ======\n${printTable(headers, rows)}\n`,
stderr: "",
exitCode: 0,
};
}
// 2. 详情: hose contact get <staffId>
if (action === "get") {
const staffId = parsed.args[0] || stringOption(parsed.options, ["id", "staff-id"]);
if (!staffId) {
return {
stdout: "",
stderr: "用法: hose contact get <staffId>",
exitCode: 1,
};
}
const staff = await getStaffById(corp, staffId);
if (!staff) {
return {
stdout: "",
stderr: `未找到员工档案: ${staffId}`,
exitCode: 1,
};
}
if (runtime.jsonMode) {
return {
stdout: printJson(staff, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const pairs: Record<string, unknown> = {
"员工姓名": staff.name,
"工号/staffId": staff.id,
"电子邮箱": staff.email || "-",
"联系手机": staff.cellphone || "-",
"所属部门": staff.department || "-",
};
return {
stdout: `====== 员工详细档案 ======\n${printKeyValue(pairs)}\n`,
stderr: "",
exitCode: 0,
};
}
// 3. 列表采样: hose contact list (默认限流截断防爆)
if (action === "list") {
const isFull = runtime.outputOptions?.allowFull === true;
const result = await listStaffsProtected(corp, {
limit: limit ?? (isFull ? undefined : DEFAULT_STAFF_LIST_LIMIT),
allowFull: isFull,
});
if (runtime.jsonMode) {
return {
stdout: printJson(result, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const headers = ["姓名", "工号 / staffId", "邮箱", "手机号"];
const rows = result.staffs.map((s) => [
s.name || "-",
s.id,
s.email || "-",
s.cellphone || "-",
]);
let output = `====== 企业通讯录采样 (共 ${result.total} 人,当前显示 ${result.staffs.length} 条) ======\n`;
output += printTable(headers, rows) + "\n";
if (result.hint) {
output += `\n💡 提示: ${result.hint}\n`;
}
return {
stdout: output,
stderr: "",
exitCode: 0,
};
}
return {
stdout: "",
stderr: `未知通讯录子命令: ${action}。支持的子命令: list, search <关键词>, get <staffId>`,
exitCode: 1,
};
}
+43 -11
View File
@@ -1,4 +1,4 @@
import { printJson, printKeyValue, printTable } from "../printer.js";
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleCorpsCommand(
@@ -29,10 +29,13 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
if (runtime.jsonMode) {
return {
stdout: printJson({
activeCorpId: runtime.selectedCorp?.id,
corporations: corps,
}),
stdout: printJson(
{
activeCorpId: runtime.selectedCorp?.id,
corporations: corps,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
@@ -48,11 +51,12 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
c.name,
c.staffId,
c.source || "manual",
formatExpiresAt(c.expiresAt),
c.accountId || "-",
]);
const table = printTable(
["#", "企业 ID", "企业名称", "员工工号", "来源", "所属账号"],
["#", "企业 ID", "企业名称", "员工工号", "来源", "Token 过期时间", "所属账号"],
rows
);
@@ -80,7 +84,7 @@ async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
const current = runtime.corpContext.getCurrent();
if (runtime.jsonMode) {
return { stdout: printJson(current), stderr: "", exitCode: 0 };
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
}
return {
@@ -97,17 +101,45 @@ async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promis
}
if (runtime.jsonMode) {
return { stdout: printJson(current), stderr: "", exitCode: 0 };
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const output = printKeyValue({
const pairs: Record<string, unknown> = {
"企业 ID": current.id,
"企业名称": current.name,
"员工工号": current.credentials.staffId,
"来源类型": current.source || "manual",
"员工姓名": current.staffName || current.session?.staffName || "-",
"凭证来源": formatSourceLabel(current.source),
"Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime),
"所属账号": current.accountId || "-",
"主站地址": current.baseUrl || "https://app.ekuaibao.com",
});
};
if (current.session) {
if (current.session.loginTime) {
pairs["会话创建时间"] = new Date(current.session.loginTime).toLocaleString("zh-CN", { hour12: false });
}
if (current.session.platform) {
pairs["官方平台类型"] = current.session.platform;
}
if (current.session.isAssistPlatform) {
pairs["协助登录模式"] = "是 (Assist Platform)";
if (current.session.operationUserName || current.session.operationUserId) {
pairs["协助操作人员"] = `${current.session.operationUserName || ""} (${current.session.operationUserId || ""})`.trim();
}
if (current.session.assistId) {
pairs["协助会话 ID"] = current.session.assistId;
}
}
if (current.session.cellphone) {
pairs["绑定手机号码"] = current.session.cellphone;
}
if (current.session.isAdmin !== undefined) {
pairs["是否企业管理"] = current.session.isAdmin ? "是" : "否";
}
}
const output = printKeyValue(pairs);
return {
stdout: `====== 当前激活企业 ======\n${output}\n`,
+28
View File
@@ -0,0 +1,28 @@
import { startHttpServer } from "../../http/server.js";
import { numberOption, stringOption } from "../parser.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleHttpCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const port = numberOption(parsed.options, ["port", "p"]);
const host = stringOption(parsed.options, ["host", "h"]);
const server = await startHttpServer({ port, host, silent: runtime.jsonMode });
// Handle graceful shutdown
const shutdown = () => {
server.close(() => {
process.exit(0);
});
};
process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);
// Keep alive in foreground
await new Promise<void>(() => {});
return { stdout: "", stderr: "", exitCode: 0 };
}
+111
View File
@@ -0,0 +1,111 @@
import { getOpenApiSchema, listOpenApiPaths, type OpenApiType } from "../../core/embedded-openapi.js";
import { booleanOption, stringOption } from "../parser.js";
import { printJson, printKeyValue, printTable } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleOpenApiCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const isRaw =
booleanOption(parsed.options, ["raw"]) ||
parsed.action === "raw" ||
parsed.args[0] === "raw";
const type: OpenApiType = isRaw ? "raw" : "wrapped";
const action = parsed.action?.toLowerCase();
switch (action) {
case "paths":
case "list":
case "ls": {
const paths = listOpenApiPaths(type);
if (runtime.jsonMode) {
return {
stdout: printJson({ type, count: paths.length, paths }),
stderr: "",
exitCode: 0,
};
}
const rows = paths.map((p) => [
p.method,
p.path,
p.summary || "-",
p.tags.join(", ") || "-",
]);
const table = printTable(["Method", "Path", "Summary", "Tags"], rows);
const title = isRaw
? "====== 合思/易快报 原生下游 OpenAPI 接口列表 ======"
: "====== hose-use 包装层 OpenAPI 接口列表 ======";
return {
stdout: `${title}\n\n${table}\n\n提示: 运行 hose-use openapi ${isRaw ? "--raw " : ""}可直接输出完整 OpenAPI 3.1.0 JSON\n`,
stderr: "",
exitCode: 0,
};
}
case "info":
case "summary": {
const schema = getOpenApiSchema(type);
const info = (schema.info as Record<string, unknown>) || {};
const servers = ((schema.servers as Array<{ url: string; description?: string }>) || []).map(
(s) => `${s.url} (${s.description || "-"})`
);
const tags = ((schema.tags as Array<{ name: string; description?: string }>) || []).map(
(t) => `${t.name}: ${t.description || ""}`
);
const paths = listOpenApiPaths(type);
const infoObj = {
title: info.title,
version: info.version,
description: info.description,
type,
totalEndpoints: paths.length,
servers,
tags,
};
if (runtime.jsonMode) {
return {
stdout: printJson(infoObj),
stderr: "",
exitCode: 0,
};
}
const out = printKeyValue({
"规范标题": info.title,
"规范版本": info.version,
"规范类型": isRaw ? "原始下游原生 API (Raw Spec)" : "包装层工具 API (Wrapped Spec)",
"接口总数": paths.length,
"描述信息": info.description,
"服务器列表": servers.join("\n "),
"标签分组": tags.join("\n "),
});
return {
stdout: `====== OpenAPI 规范概览 ======\n${out}\n`,
stderr: "",
exitCode: 0,
};
}
case "dump":
case "export":
case "raw":
case undefined:
default: {
const schema = getOpenApiSchema(type);
return {
stdout: `${JSON.stringify(schema, null, 2)}\n`,
stderr: "",
exitCode: 0,
};
}
}
}
+1 -1
View File
@@ -36,7 +36,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
const platforms = await api.listPlatforms(clients.ekbClient, runtime.selectedCorp!.credentials.corpId);
if (runtime.jsonMode) {
return { stdout: printJson(platforms), stderr: "", exitCode: 0 };
return { stdout: printJson(platforms, runtime.outputOptions), stderr: "", exitCode: 0 };
}
if (platforms.length === 0) {
+15 -3
View File
@@ -1,6 +1,6 @@
import { createClientsForCorp } from "../helpers.js";
import * as api from "../../domains/platform/api.js";
import { printJson, printKeyValue } from "../printer.js";
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleProbeCommand(
@@ -79,14 +79,26 @@ export async function handleProbeCommand(
return { stdout: printJson(results), stderr: "", exitCode: 0 };
}
const summary = printKeyValue({
const probePairs: Record<string, unknown> = {
"企业名称": currentCorp.name,
"企业 ID": currentCorp.id,
"员工工号": currentCorp.credentials.staffId,
"员工姓名": currentCorp.staffName || currentCorp.session?.staffName || "-",
"凭证来源": formatSourceLabel(currentCorp.source),
"Token 过期时间": formatExpiresAt(currentCorp.auth?.expiresAt || currentCorp.session?.expTime),
"主站 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} 个自建应用)` : "🔴 失败",
});
};
if (currentCorp.session?.isAssistPlatform) {
probePairs["协助操作人"] = `${currentCorp.session.operationUserName || ""} (${currentCorp.session.operationUserId || ""})`.trim();
if (currentCorp.session.assistId) {
probePairs["协助会话 ID"] = currentCorp.session.assistId;
}
}
const summary = printKeyValue(probePairs);
return {
stdout: `====== 诊断结果 (Enterprise Probe) ======\n${summary}\n`,
+70
View File
@@ -0,0 +1,70 @@
import { homedir } from "node:os";
import { join } from "node:path";
import { VERSION } from "../../version.js";
import { runServiceCommand, ServiceConfig, getPidFile, getLogFile } from "../service.js";
import { printJson, printKeyValue } from "../printer.js";
import { numberOption, stringOption } from "../parser.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export const SERVICE_STATE_DIR = process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
export async function handleServiceCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const action = parsed.action || parsed.args[0] || "status";
const port = numberOption(parsed.options, ["port", "p"]);
const host = stringOption(parsed.options, ["host", "h"]);
const config: ServiceConfig = {
appRoot: runtime.appRoot || process.cwd(),
entryFile: runtime.entryFile || join(runtime.appRoot || process.cwd(), "src", "cli.ts"),
stateDir: SERVICE_STATE_DIR,
version: VERSION,
launcher: runtime.launcher,
port,
host,
};
const result = await runServiceCommand(action, config);
if (result === undefined) {
// 'run' keeps running, resolves on shutdown
return { stdout: "", stderr: "", exitCode: 0 };
}
if (runtime.jsonMode) {
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
}
if (action === "logs" || action === "log") {
const logsResult = result as { logFile: string; lines: string[]; content: string };
return {
stdout: `====== hose-use 守护进程日志 (${logsResult.logFile}) ======\n${logsResult.content}\n`,
stderr: "",
exitCode: 0,
};
}
const status = result as Record<string, unknown>;
const isRunning = Boolean(status.running);
const displayPairs: Record<string, unknown> = {
"服务状态": isRunning ? "🟢 正在运行 (Running)" : "⚪ 已停止 (Stopped)",
...(status.pid ? { "进程 PID": status.pid } : {}),
...(status.url ? { "服务地址": status.url } : {}),
...(status.url ? { "交互式文档": `${status.url}/docs` } : {}),
...(status.url ? { "CLI 网关": `POST ${status.url}/api/cli` } : {}),
"运行版本": status.version || config.version,
"状态目录": status.stateDir || config.stateDir,
"PID 文件": status.pidFile || getPidFile(config),
"日志文件": status.logFile || getLogFile(config),
};
const formatted = printKeyValue(displayPairs);
return {
stdout: `====== hose-use 常驻服务管理 (Service) ======\n${formatted}\n`,
stderr: "",
exitCode: 0,
};
}
+51
View File
@@ -0,0 +1,51 @@
import { describe, expect, test } from "bun:test";
import { compareSemVer, isNewerVersion, matchAssetForPlatform, type GitHubAsset } from "./update.js";
describe("update version comparator", () => {
test("correctly identifies newer semantic versions", () => {
expect(isNewerVersion("0.2.1", "0.2.0")).toBe(true);
expect(isNewerVersion("1.0.0", "0.2.0")).toBe(true);
expect(isNewerVersion("0.3.0", "0.2.1")).toBe(true);
expect(isNewerVersion("0.2.0", "0.2.0")).toBe(false);
expect(isNewerVersion("0.1.9", "0.2.0")).toBe(false);
expect(isNewerVersion("0.2.0", "0.2.1")).toBe(false);
});
test("compareSemVer handles tags, major, minor, and patch", () => {
expect(compareSemVer("v0.2.1", "0.2.0")).toBe(1);
expect(compareSemVer("0.2.0", "v0.2.1")).toBe(-1);
expect(compareSemVer("v0.2.1", "v0.2.1")).toBe(0);
expect(compareSemVer("1.0.0", "0.9.9")).toBe(1);
expect(compareSemVer("0.1.0", "0.2.1")).toBe(-1);
});
});
describe("matchAssetForPlatform", () => {
const assets: GitHubAsset[] = [
{ name: "hose-use-darwin-arm64", downloadUrl: "https://example.com/darwin-arm64", size: 100 },
{ 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", () => {
const matched = matchAssetForPlatform(assets, "darwin", "arm64");
expect(matched?.name).toBe("hose-use-darwin-arm64");
});
test("matches darwin x64", () => {
const matched = matchAssetForPlatform(assets, "darwin", "x64");
expect(matched?.name).toBe("hose-use-darwin-x64");
});
test("matches linux x64 archive", () => {
const matched = matchAssetForPlatform(assets, "linux", "x64");
expect(matched?.name).toBe("hose-use-linux-x64.tar.gz");
});
test("matches windows x64 archive", () => {
const matched = matchAssetForPlatform(assets, "windows", "x64");
expect(matched?.name).toBe("hose-use-windows-x64.zip");
});
});
+812
View File
@@ -0,0 +1,812 @@
import { chmodSync, existsSync, mkdirSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { spawnSync } from "node:child_process";
import { isCompiledBinary, resolveAppRoot } from "../../core/runtime.js";
import { syncGlobalSkillIfPresent } from "../../core/embedded-skill.js";
import { VERSION } from "../../version.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { printJson, printKeyValue } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "../types.js";
const DEFAULT_GITHUB_REPO = "yunyingk/hose-use";
const GITHUB_REPO_ENV = "HOSE_USE_GITHUB_REPO";
export type UpdateOptions = {
checkOnly?: boolean;
changelogOnly?: boolean;
limit?: number;
force?: boolean;
targetVersion?: string;
repo?: string;
};
export async function handleUpdateCommand(
parsed: CliParsedArgs,
runtime: CliRuntime,
runOptions: CliRunOptions = {}
): Promise<CliResult> {
const isChangelog =
parsed.area === "changelog" ||
parsed.action === "changelog" ||
parsed.action === "log" ||
parsed.action === "history" ||
booleanOption(parsed.options, ["changelog", "log", "l"]);
const isCheck =
parsed.action === "check" ||
booleanOption(parsed.options, ["check", "check-only", "c"]);
const targetVersionRaw =
stringOption(parsed.options, ["version", "tag", "target", "t"]) ||
(!isChangelog && !isCheck && parsed.action && !parsed.action.startsWith("-")
? parsed.action
: undefined);
const targetVersion =
targetVersionRaw && targetVersionRaw.toLowerCase() !== "latest"
? targetVersionRaw.replace(/^v/, "")
: undefined;
const repo =
stringOption(parsed.options, ["repo"]) ||
process.env[GITHUB_REPO_ENV]?.trim() ||
DEFAULT_GITHUB_REPO;
const options: UpdateOptions = {
checkOnly: isCheck,
changelogOnly: isChangelog,
limit: numberOption(parsed.options, ["limit", "n"]),
force: booleanOption(parsed.options, ["force", "f"]),
targetVersion,
repo,
};
const appRoot = runOptions.appRoot || resolveAppRoot(runOptions.entryFile);
// Validate targetVersion: prevent downgrade to older versions
if (targetVersion) {
const cmp = compareSemVer(targetVersion, VERSION);
if (cmp < 0 && !options.force) {
const msg = `无法降级 hose-use(当前版本 v${VERSION},目标版本 v${targetVersion})。如需强制重装请使用 --force。`;
if (runtime.jsonMode) {
return {
stdout: printJson({
updated: false,
currentVersion: VERSION,
targetVersion,
mode: isCompiledBinary() ? "binary" : "source",
message: msg,
}),
stderr: "",
exitCode: 1,
};
}
return {
stdout: "",
stderr: `[ERROR] ${msg}\n`,
exitCode: 1,
};
}
if (cmp === 0 && !options.force) {
const msg = `hose-use 当前已是版本 v${VERSION}。如需强制重装请添加 --force。`;
if (runtime.jsonMode) {
return {
stdout: printJson({
updated: false,
currentVersion: VERSION,
targetVersion,
mode: isCompiledBinary() ? "binary" : "source",
message: msg,
}),
stderr: "",
exitCode: 0,
};
}
return {
stdout: `ℹ️ ${msg}\n`,
stderr: "",
exitCode: 0,
};
}
}
// 1. Changelog / Release History query
if (options.changelogOnly) {
const releases = await fetchGitHubReleases(repo, options.limit ?? 10);
if (runtime.jsonMode) {
return {
stdout: printJson({
currentVersion: VERSION,
totalQueried: releases.length,
releases: releases.map((r) => ({
version: r.version,
tagName: r.tagName,
publishedAt: r.publishedAt,
author: r.author,
releaseNotes: r.notes,
releaseUrl: r.htmlUrl,
isCurrent: r.version === VERSION,
isNewer: isNewerVersion(r.version, VERSION),
})),
}),
stderr: "",
exitCode: 0,
};
}
const lines: string[] = [
`====== hose-use 版本发布记录 (当前版本: v${VERSION}) ======`,
"",
];
for (const r of releases) {
const badge = r.version === VERSION ? " [当前版本]" : isNewerVersion(r.version, VERSION) ? " [新版本 ✨]" : "";
lines.push(`• v${r.version} (${r.publishedAt ? r.publishedAt.slice(0, 10) : "未知日期"})${badge}`);
if (r.notes) {
const snippet = r.notes.trim().split("\n").map((l) => ` ${l}`).join("\n");
lines.push(snippet);
}
lines.push("");
}
return {
stdout: lines.join("\n"),
stderr: "",
exitCode: 0,
};
}
// 2. Source development mode (running via bun/node)
if (!isCompiledBinary()) {
if (options.checkOnly) {
const releases = await fetchGitHubReleases(repo, 30);
const latestRelease = releases[0];
const latestVersion = latestRelease?.version ?? VERSION;
const currentRelease = releases.find((r) => r.version === VERSION);
const isUpgrade = isNewerVersion(latestVersion, VERSION);
const pendingReleases = releases.filter((r) => isNewerVersion(r.version, VERSION));
if (runtime.jsonMode) {
return {
stdout: printJson({
updated: false,
updateAvailable: isUpgrade,
currentVersion: VERSION,
currentVersionPublishedAt: currentRelease?.publishedAt,
latestVersion,
latestVersionPublishedAt: latestRelease?.publishedAt,
behindCount: pendingReleases.length,
pendingReleases: pendingReleases.map((r) => ({
version: r.version,
tagName: r.tagName,
publishedAt: r.publishedAt,
author: r.author,
releaseNotes: r.notes,
releaseUrl: r.htmlUrl,
})),
releaseNotes: latestRelease?.notes ?? "",
releaseUrl: latestRelease?.htmlUrl ?? "",
mode: "source",
message: "当前运行于源码开发模式。运行 'hose-use update' 执行 git pull 与依赖更新。",
}),
stderr: "",
exitCode: 0,
};
}
const out = printKeyValue({
"运行模式": "源码开发模式 (Source Mode)",
"当前版本": `v${VERSION}`,
"最新版本": `v${latestVersion} ${isUpgrade ? "(可升级 ✨)" : "(已是最新 ✅)"}`,
"待更新版本数": pendingReleases.length,
"源码路径": appRoot,
});
return {
stdout: `====== hose-use 版本检查 ======\n${out}\n\n${isUpgrade ? `可运行 hose-use update 执行 git pull 与依赖同步` : "已经是最新版本"}\n`,
stderr: "",
exitCode: 0,
};
}
try {
runCommand("git", ["-C", appRoot, "pull", "--ff-only"]);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
console.error(`git pull 提示: ${msg}`);
}
runCommand("bun", ["install"], { cwd: appRoot });
const skillSync = syncGlobalSkillIfPresent();
if (runtime.jsonMode) {
return {
stdout: printJson({
updated: true,
version: VERSION,
mode: "source",
skillSynced: skillSync.synced ? skillSync.targetDir : false,
}),
stderr: "",
exitCode: 0,
};
}
return {
stdout: `[SUCCESS] hose-use 源码与依赖更新成功!\n版本: v${VERSION}\n技能同步: ${skillSync.synced ? "已同步至全局 ✅" : "未同步"}\n`,
stderr: "",
exitCode: 0,
};
}
// 3. Standalone binary mode: check GitHub Releases
const platform = detectPlatform();
const arch = detectArch();
const releases = await fetchGitHubReleases(repo, 30);
const release = targetVersion
? (releases.find((r) => r.version === targetVersion || r.tagName === targetVersion || r.tagName === `v${targetVersion}`) ??
await fetchGitHubRelease(repo, targetVersion))
: (releases[0] ?? await fetchGitHubRelease(repo));
if (!release) {
const errorMsg = `无法从 GitHub 仓库 '${repo}' 获取 Release 列表`;
if (runtime.jsonMode) {
return {
stdout: printJson({
updated: false,
currentVersion: VERSION,
mode: "binary",
message: errorMsg,
}),
stderr: "",
exitCode: 1,
};
}
return {
stdout: "",
stderr: `[ERROR] ${errorMsg}\n`,
exitCode: 1,
};
}
const latestVersion = release.version;
const currentRelease = releases.find((r) => r.version === VERSION);
const isUpgrade = isNewerVersion(latestVersion, VERSION);
const shouldUpdate = isUpgrade || Boolean(options.force);
const pendingReleases = releases.filter((r) => isNewerVersion(r.version, VERSION));
if (options.checkOnly) {
if (runtime.jsonMode) {
return {
stdout: printJson({
updated: false,
updateAvailable: isUpgrade,
currentVersion: VERSION,
currentVersionPublishedAt: currentRelease?.publishedAt,
latestVersion,
latestVersionPublishedAt: release.publishedAt,
behindCount: pendingReleases.length,
pendingReleases: pendingReleases.map((r) => ({
version: r.version,
tagName: r.tagName,
publishedAt: r.publishedAt,
author: r.author,
releaseNotes: r.notes,
releaseUrl: r.htmlUrl,
})),
releaseNotes: release.notes,
releaseUrl: release.htmlUrl,
mode: "binary",
}),
stderr: "",
exitCode: 0,
};
}
const out = printKeyValue({
"运行模式": "独立二进制 (Binary Mode)",
"当前版本": `v${VERSION}`,
"最新版本": `v${latestVersion} ${isUpgrade ? "(可升级 ✨)" : "(已是最新 ✅)"}`,
"发布时间": release.publishedAt ? release.publishedAt.slice(0, 10) : "未知",
"平台架构": `${platform}-${arch}`,
});
return {
stdout: `====== hose-use 版本检查 ======\n${out}\n\n${isUpgrade ? `运行 hose-use update 升级至 v${latestVersion}` : "已经是最新版本"}\n`,
stderr: "",
exitCode: 0,
};
}
if (!shouldUpdate) {
if (runtime.jsonMode) {
return {
stdout: printJson({
updated: false,
currentVersion: VERSION,
currentVersionPublishedAt: currentRelease?.publishedAt,
latestVersion,
latestVersionPublishedAt: release.publishedAt,
mode: "binary",
message: `hose-use 当前已是最新版本 (v${VERSION})`,
}),
stderr: "",
exitCode: 0,
};
}
return {
stdout: `ℹ️ hose-use 当前已是最新版本 (v${VERSION})。如需重装请添加 --force。\n`,
stderr: "",
exitCode: 0,
};
}
// Find matching asset
const asset = matchAssetForPlatform(release.assets, platform, arch);
if (!asset) {
const errorMsg = `未找到适用于 ${platform}-${arch} 平台的 Release 资产 (v${latestVersion})。可用文件: ${release.assets.map((a) => a.name).join(", ")}`;
if (runtime.jsonMode) {
return {
stdout: printJson({ updated: false, error: true, message: errorMsg }),
stderr: "",
exitCode: 1,
};
}
return {
stdout: "",
stderr: `[ERROR] ${errorMsg}\n`,
exitCode: 1,
};
}
const execPath = process.execPath;
const execDir = dirname(execPath);
const tmpDir = join(execDir, `.tmp-update-${Date.now()}`);
mkdirSync(tmpDir, { recursive: true });
try {
const downloadedFile = join(tmpDir, asset.name);
await downloadFile(asset.downloadUrl, downloadedFile, release.tagName, asset.name);
let newBinaryPath = downloadedFile;
if (asset.name.endsWith(".tar.gz") || asset.name.endsWith(".tgz")) {
newBinaryPath = extractTarGz(downloadedFile, tmpDir, platform);
} else if (asset.name.endsWith(".zip")) {
newBinaryPath = extractZip(downloadedFile, tmpDir, platform);
}
chmodSync(newBinaryPath, 0o755);
// Re-sign on macOS ad-hoc if codesign exists
if (process.platform === "darwin") {
try {
spawnSync("/usr/bin/codesign", ["--remove-signature", newBinaryPath], { stdio: "ignore" });
spawnSync("/usr/bin/codesign", ["--force", "--sign", "-", newBinaryPath], { stdio: "ignore" });
} catch {
// ignore
}
}
// Atomic replace
if (process.platform === "win32") {
const oldBinary = `${execPath}.old.${Date.now()}`;
try {
renameSync(execPath, oldBinary);
} catch {
// ignore
}
renameSync(newBinaryPath, execPath);
} else {
renameSync(newBinaryPath, execPath);
}
const skillSync = syncGlobalSkillIfPresent();
if (runtime.jsonMode) {
return {
stdout: printJson({
updated: true,
fromVersion: VERSION,
toVersion: latestVersion,
skillSynced: skillSync.synced ? skillSync.targetDir : false,
mode: "binary",
}),
stderr: "",
exitCode: 0,
};
}
return {
stdout: `[SUCCESS] ✨ hose-use 已成功升级至 v${latestVersion}!\n可执行文件: ${execPath}\nAgent 技能: ${skillSync.synced ? "已自动同步最新版 ✅" : "未同步"}\n`,
stderr: "",
exitCode: 0,
};
} finally {
try {
rmSync(tmpDir, { recursive: true, force: true });
} catch {
// ignore
}
}
}
function detectPlatform(): "darwin" | "linux" | "windows" {
if (process.platform === "darwin") return "darwin";
if (process.platform === "win32") return "windows";
return "linux";
}
function detectArch(): "arm64" | "x64" {
return process.arch === "arm64" ? "arm64" : "x64";
}
export type GitHubAsset = {
name: string;
downloadUrl: string;
size: number;
};
export type GitHubRelease = {
version: string;
tagName: string;
name?: string;
publishedAt?: string;
author?: string;
notes: string;
htmlUrl: string;
assets: GitHubAsset[];
};
export async function fetchGitHubReleases(repo: string, limit = 20): Promise<GitHubRelease[]> {
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
const headers: Record<string, string> = {
"User-Agent": `hose-use/${VERSION}`,
Accept: "application/vnd.github.v3+json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
};
const urls = [
`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${limit}`,
`https://api.github.com/repos/${repo}/releases?per_page=${limit}`,
];
for (const url of urls) {
try {
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
if (!res.ok) continue;
const json = (await res.json()) as Array<{
tag_name?: string;
name?: string;
body?: string;
html_url?: string;
published_at?: string;
author?: { login?: string };
assets?: Array<{ name: string; browser_download_url: string; size?: number }>;
}>;
if (!Array.isArray(json) || json.length === 0) continue;
const list: GitHubRelease[] = [];
for (const item of json) {
const tagName = item.tag_name ?? "";
const version = tagName.replace(/^v/, "");
if (!version) continue;
const assets: GitHubAsset[] = (item.assets ?? []).map((a) => ({
name: a.name,
downloadUrl: a.browser_download_url,
size: a.size ?? 0,
}));
list.push({
version,
tagName,
name: item.name ?? tagName,
publishedAt: item.published_at,
author: item.author?.login,
notes: item.body ?? "",
htmlUrl: item.html_url ?? "",
assets,
});
}
if (list.length > 0) return list;
} catch {
// try next source
}
}
return [];
}
export async function fetchGitHubRelease(
repo: string,
targetVersion?: string
): Promise<GitHubRelease | undefined> {
const tag = targetVersion ? (targetVersion.startsWith("v") ? targetVersion : `v${targetVersion}`) : undefined;
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
const headers: Record<string, string> = {
"User-Agent": `hose-use/${VERSION}`,
Accept: "application/vnd.github.v3+json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
};
const urls = tag
? [
`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/tags/${tag}`,
`https://api.github.com/repos/${repo}/releases/tags/${tag}`,
]
: [
`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest`,
`https://api.github.com/repos/${repo}/releases/latest`,
];
let fallbackRelease: GitHubRelease | undefined;
for (const url of urls) {
try {
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
if (!res.ok) continue;
const json = (await res.json()) as {
tag_name?: string;
name?: string;
body?: string;
html_url?: string;
published_at?: string;
author?: { login?: string };
assets?: Array<{ name: string; browser_download_url: string; size?: number }>;
};
const tagName = json.tag_name ?? "";
const version = tagName.replace(/^v/, "");
if (!version) continue;
const assets: GitHubAsset[] = (json.assets ?? []).map((item) => ({
name: item.name,
downloadUrl: item.browser_download_url,
size: item.size ?? 0,
}));
const candidateRelease: GitHubRelease = {
version,
tagName,
name: json.name ?? tagName,
publishedAt: json.published_at,
author: json.author?.login,
notes: json.body ?? "",
htmlUrl: json.html_url ?? "",
assets,
};
if (assets.length > 0) {
return candidateRelease;
}
if (!fallbackRelease) {
fallbackRelease = candidateRelease;
}
} catch {
// try next source
}
}
return fallbackRelease;
}
export function matchAssetForPlatform(
assets: GitHubAsset[],
platform: "darwin" | "linux" | "windows",
arch: "arm64" | "x64"
): GitHubAsset | undefined {
const platformKeywords: Record<string, string[]> = {
darwin: ["darwin", "macos", "osx", "apple"],
linux: ["linux"],
windows: ["windows", "win32", "win64", ".exe"],
};
const archKeywords: Record<string, string[]> = {
arm64: ["arm64", "aarch64"],
x64: ["x64", "x86_64", "amd64"],
};
const pKeys = platformKeywords[platform] || [];
const aKeys = archKeywords[arch] || [];
const matched = assets.filter((asset) => {
const lower = asset.name.toLowerCase();
const matchesP = pKeys.some((k) => lower.includes(k));
const matchesA = aKeys.some((k) => lower.includes(k));
return matchesP && matchesA;
});
// Prefer direct raw executable over tar.gz / zip if both exist
const directBinary = matched.find(
(asset) =>
!asset.name.endsWith(".tar.gz") &&
!asset.name.endsWith(".tgz") &&
!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];
}
function logProgress(msg: string) {
try {
process.stderr.write(`${msg}\n`);
} catch {
// ignore
}
}
async function downloadFile(url: string, destPath: string, tagName?: string, assetName?: string) {
const candidates: string[] = [];
const tag = tagName ? (tagName.startsWith("v") ? tagName : `v${tagName}`) : undefined;
const fileName = assetName || url.split("/").pop() || "";
// 1. High-speed Gitea direct mirror first
if (tag && fileName) {
candidates.push(`https://git.ying-qing.cn/gitea/hose-use/releases/download/${tag}/${fileName}`);
}
if (url.startsWith("https://git.ying-qing.cn")) {
candidates.push(url);
}
// 2. Fast GitHub CDN proxies and direct GitHub fallback
if (tag && fileName) {
const ghDirectUrl = `https://github.com/${DEFAULT_GITHUB_REPO}/releases/download/${tag}/${fileName}`;
candidates.push(`https://ghfast.top/${ghDirectUrl}`);
candidates.push(`https://ghproxy.net/${ghDirectUrl}`);
candidates.push(`https://gh.ddlc.top/${ghDirectUrl}`);
candidates.push(`https://mirror.ghproxy.com/${ghDirectUrl}`);
candidates.push(ghDirectUrl);
} else if (url.includes("github.com")) {
candidates.push(`https://ghfast.top/${url}`);
candidates.push(`https://ghproxy.net/${url}`);
candidates.push(`https://gh.ddlc.top/${url}`);
candidates.push(`https://mirror.ghproxy.com/${url}`);
candidates.push(url);
} else {
candidates.push(url);
}
const uniqueCandidates = Array.from(new Set(candidates));
let lastError: Error | undefined;
for (let i = 0; i < uniqueCandidates.length; i++) {
const candidate = uniqueCandidates[i]!;
try {
logProgress(`==> [${i + 1}/${uniqueCandidates.length}] 正在下载更新: ${candidate}`);
const res = await fetch(candidate, { signal: AbortSignal.timeout(6000) });
if (!res.ok) {
throw new Error(`HTTP ${res.status} ${res.statusText}`);
}
const totalBytes = Number(res.headers.get("content-length")) || 0;
const reader = res.body?.getReader();
if (!reader) {
const buffer = Buffer.from(await res.arrayBuffer());
if (buffer.length < 1000) {
throw new Error(`下载文件异常(大小仅 ${buffer.length} 字节)`);
}
writeFileSync(destPath, buffer);
logProgress(`✓ 下载完成 (${(buffer.length / 1024 / 1024).toFixed(1)} MB)`);
return;
}
const chunks: Uint8Array[] = [];
let receivedBytes = 0;
let lastReport = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (value) {
chunks.push(value);
receivedBytes += value.length;
const now = Date.now();
if (now - lastReport > 200) {
lastReport = now;
const percent = totalBytes ? Math.round((receivedBytes / totalBytes) * 100) : 0;
const receivedMb = (receivedBytes / (1024 * 1024)).toFixed(1);
const totalMb = totalBytes ? (totalBytes / (1024 * 1024)).toFixed(1) : "?";
try {
process.stderr.write(`\r ↳ 进度: ${percent}% (${receivedMb} / ${totalMb} MB)...`);
} catch {
// ignore
}
}
}
}
try {
process.stderr.write("\n");
} catch {
// ignore
}
const completeBuffer = Buffer.concat(chunks);
if (completeBuffer.length < 1000) {
throw new Error(`下载文件异常(大小仅 ${completeBuffer.length} 字节)`);
}
writeFileSync(destPath, completeBuffer);
logProgress(`✓ 下载完成 (${(completeBuffer.length / 1024 / 1024).toFixed(1)} MB)`);
return;
} catch (err) {
lastError = err instanceof Error ? err : new Error(String(err));
logProgress(` ↳ 节点失败: ${lastError.message}`);
}
}
throw new Error(`所有下载镜像均失败: ${lastError?.message}`);
}
function extractTarGz(archivePath: string, targetDir: string, platform: string): string {
const result = spawnSync("tar", ["-xzf", archivePath, "-C", targetDir], { stdio: "pipe" });
if (result.status !== 0) {
throw new Error(`解压 tar 归档失败: ${result.stderr.toString()}`);
}
unlinkSync(archivePath);
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
.stdout.trim()
.split("\n")
.filter(Boolean);
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
if (exact) return exact;
return files[0] || archivePath;
}
function extractZip(archivePath: string, targetDir: string, platform: string): string {
const result = spawnSync("unzip", ["-q", "-o", archivePath, "-d", targetDir], { stdio: "pipe" });
if (result.status !== 0) {
throw new Error(`解压 zip 归档失败: ${result.stderr.toString()}`);
}
unlinkSync(archivePath);
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
.stdout.trim()
.split("\n")
.filter(Boolean);
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
if (exact) return exact;
return files[0] || archivePath;
}
export function compareSemVer(v1: string, v2: string): number {
const p1 = v1.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
const p2 = v2.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
for (let i = 0; i < Math.max(p1.length, p2.length); i++) {
const a = p1[i] ?? 0;
const b = p2[i] ?? 0;
if (a > b) return 1;
if (a < b) return -1;
}
return 0;
}
export function isNewerVersion(latest: string, current: string): boolean {
return compareSemVer(latest, current) > 0;
}
function runCommand(command: string, args: string[], options: { cwd?: string } = {}) {
const result = spawnSync(command, args, {
cwd: options.cwd,
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
});
if (result.stdout) console.error(result.stdout.trimEnd());
if (result.stderr) console.error(result.stderr.trimEnd());
if (result.status !== 0) {
throw new Error(`${command} ${args.join(" ")} 执行失败 (退出码 ${result.status})`);
}
}
+4 -4
View File
@@ -54,7 +54,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
const result = await listAllWorkflows(clients, { page, pageSize });
if (runtime.jsonMode) {
return { stdout: printJson(result), stderr: "", exitCode: 0 };
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
}
if (result.workflows.length === 0) {
@@ -96,7 +96,7 @@ async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
const detail = await api.getWorkflowDetail(clients.easoClient, pipelineId);
if (runtime.jsonMode) {
return { stdout: printJson(detail), stderr: "", exitCode: 0 };
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const summary = printKeyValue({
@@ -148,7 +148,7 @@ async function handleFind(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
});
if (runtime.jsonMode) {
return { stdout: printJson(result), stderr: "", exitCode: 0 };
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
}
if (result.workflows.length === 0) {
@@ -196,7 +196,7 @@ async function handleToggle(parsed: CliParsedArgs, runtime: CliRuntime): Promise
const result = await api.toggleWorkflow(clients.easoClient, pipelineId, state);
if (runtime.jsonMode) {
return { stdout: printJson(result), stderr: "", exitCode: 0 };
return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
}
return {
+14 -3
View File
@@ -1,10 +1,10 @@
import readline from "readline";
import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js";
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 { CliRuntime } from "./types.js";
import { CliRuntime, OutputOptions } from "./types.js";
export function initCorpRuntime(
options: {
@@ -12,6 +12,13 @@ export function initCorpRuntime(
stateless?: boolean;
stateful?: boolean;
jsonMode?: boolean;
outputOptions?: OutputOptions;
appRoot?: string;
entryFile?: string;
launcher?: {
command: string;
args?: string[];
};
} = {}
): CliRuntime {
const corps = loadCorpConfigs();
@@ -31,7 +38,7 @@ export function initCorpRuntime(
let selectedCorp: CorpConfig | null = null;
try {
selectedCorp = corpContext.resolve(options.corpId);
selectedCorp = corpContext.resolve(options.corpId, getEnterprisesDirCandidates());
} catch {
selectedCorp = null;
}
@@ -40,6 +47,10 @@ export function initCorpRuntime(
corpContext,
selectedCorp,
jsonMode: options.jsonMode ?? false,
outputOptions: options.outputOptions,
appRoot: options.appRoot,
entryFile: options.entryFile,
launcher: options.launcher,
};
}
+54 -7
View File
@@ -1,4 +1,29 @@
import type { CliParsedArgs } from "./types.js";
import type { CliParsedArgs, OutputOptions } from "./types.js";
const KNOWN_BOOLEAN_FLAGS = new Set([
"raw",
"json",
"j",
"help",
"h",
"version",
"v",
"force",
"f",
"stateless",
"stateful",
"check",
"check-only",
"changelog",
"log",
"local",
"workspace",
"external",
"full",
"allow-full",
"allowFull",
"summary",
]);
export function parseArgs(rawArgs: string[]): CliParsedArgs {
const options: Record<string, string | boolean | number> = {};
@@ -20,12 +45,16 @@ export function parseArgs(rawArgs: string[]): CliParsedArgs {
options[key] = val;
} else {
const key = arg.slice(2);
const next = rawArgs[i + 1];
if (next && !next.startsWith("-")) {
options[key] = next;
i++;
} else {
if (KNOWN_BOOLEAN_FLAGS.has(key)) {
options[key] = true;
} else {
const next = rawArgs[i + 1];
if (next && !next.startsWith("-")) {
options[key] = next;
i++;
} else {
options[key] = true;
}
}
}
continue;
@@ -36,7 +65,17 @@ export function parseArgs(rawArgs: string[]): CliParsedArgs {
if (flag === "h") options.help = true;
else if (flag === "j") options.json = true;
else if (flag === "v") options.version = true;
else options[flag] = true;
else if (flag === "o") {
const next = rawArgs[i + 1];
if (next && !next.startsWith("-")) {
options.outputFile = next;
i++;
} else {
options.o = true;
}
} else {
options[flag] = true;
}
continue;
}
@@ -96,3 +135,11 @@ export function numberOption(
}
return fallback;
}
export function outputOptions(options: Record<string, unknown>): OutputOptions {
return {
allowFull: booleanOption(options, ["full", "allow-full", "allowFull"]),
outputFile: stringOption(options, ["output-file", "outputFile", "o"]),
summary: booleanOption(options, ["summary"]),
};
}
+108
View File
@@ -0,0 +1,108 @@
import { describe, expect, test, beforeEach, afterEach } from "bun:test";
import { mkdtempSync, rmSync, existsSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
DEFAULT_OUTPUT_BYTES_LIMIT,
protectLargeOutput,
printJson,
redactSensitiveText,
} from "./printer.js";
describe("cli/printer - 上下文防爆与敏感脱敏", () => {
describe("redactSensitiveText 脱敏处理", () => {
test("脱敏 URL Query 中的 accessToken / token / returnToken", () => {
const input = "https://app.ekuaibao.com/api/test?accessToken=sec_123456&corpId=corpxx&returnToken=ret_789";
const redacted = redactSensitiveText(input);
expect(redacted).not.toContain("sec_123456");
expect(redacted).not.toContain("ret_789");
expect(redacted).toContain("accessToken=<redacted>");
expect(redacted).toContain("returnToken=<redacted>");
expect(redacted).toContain("corpId=corpxx");
});
test("脱敏 Authorization Bearer token", () => {
const input = "Request headers: Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.xyz";
const redacted = redactSensitiveText(input);
expect(redacted).not.toContain("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.xyz");
expect(redacted).toContain("Bearer <redacted>");
});
test("脱敏 password、secret、appSecurity 等键值", () => {
const input = '{"username": "admin", "password": "super_secret_password_123", "appSecurity": "sec_key"}';
const redacted = redactSensitiveText(input);
expect(redacted).not.toContain("super_secret_password_123");
expect(redacted).not.toContain("sec_key");
expect(redacted).toContain('"password": "<redacted>"');
expect(redacted).toContain('"appSecurity": "<redacted>"');
});
});
describe("protectLargeOutput 与 printJson 体积熔断保护", () => {
let tempDir: string;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "hose-printer-test-"));
});
afterEach(() => {
try {
rmSync(tempDir, { recursive: true, force: true });
} catch {
// ignore
}
});
test("正常体积的数据可以直接输出 JSON", () => {
const normalData = { hello: "world", numbers: [1, 2, 3] };
expect(() => protectLargeOutput(normalData)).not.toThrow();
const output = printJson(normalData);
expect(JSON.parse(output)).toEqual(normalData);
});
test("超过 200KB 的巨型数据默认抛出熔断错误", () => {
// 构造超过 200KB 的大数组
const bigArray = Array.from({ length: 1500 }, (_, i) => ({
id: `id-${i}`,
description: "这是一个用于测试大报文熔断拦截的测试长字段内容,模拟企业级海量单据与工作流节点拓扑",
nested: { count: i, payload: "x".repeat(120) },
}));
expect(() => protectLargeOutput(bigArray)).toThrow(
/输出体积过大.*超过安全阈值.*--output-file.*--full/
);
expect(() => printJson(bigArray)).toThrow(/输出体积过大/);
});
test("显式指定 allowFull 时允许全量输出大报文", () => {
const bigArray = Array.from({ length: 1500 }, (_, i) => ({
id: `id-${i}`,
payload: "y".repeat(150),
}));
expect(() => protectLargeOutput(bigArray, { allowFull: true })).not.toThrow();
const output = printJson(bigArray, { allowFull: true });
expect(output.length).toBeGreaterThan(DEFAULT_OUTPUT_BYTES_LIMIT);
});
test("指定 outputFile 时大报文直接落盘并返回精简摘要", () => {
const targetFile = join(tempDir, "exported-bills.json");
const bigArray = Array.from({ length: 1500 }, (_, i) => ({
id: `id-${i}`,
payload: "z".repeat(150),
}));
const resultJson = printJson(bigArray, { outputFile: targetFile });
const summary = JSON.parse(resultJson);
expect(summary.outputFile).toBe(targetFile);
expect(summary.bytes).toBeGreaterThan(DEFAULT_OUTPUT_BYTES_LIMIT);
expect(existsSync(targetFile)).toBe(true);
const savedContent = JSON.parse(readFileSync(targetFile, "utf-8"));
expect(savedContent).toHaveLength(1500);
expect(savedContent[0].id).toBe("id-0");
});
});
});
+102 -9
View File
@@ -1,7 +1,78 @@
import { writeFileSync } from "node:fs";
import { VERSION } from "../version.js";
import type { OutputOptions } from "./types.js";
export function printJson(data: unknown): string {
return JSON.stringify(data, null, 2);
export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
export function redactSensitiveText(value: string): string {
return value
.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s"']+/gi, "$1<redacted>")
.replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1<redacted>")
.replace(/((?:password|passwd|secret|appSecurity)["']?\s*[:=]\s*["']?)[^"',\s}]+/gi, "$1<redacted>");
}
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 参数。`
);
}
}
export function printJson(data: unknown, options: OutputOptions = {}): string {
protectLargeOutput(data, options);
const json = JSON.stringify(data, null, 2);
if (options.outputFile) {
writeFileSync(options.outputFile, json, "utf-8");
return JSON.stringify(
{
outputFile: options.outputFile,
bytes: Buffer.byteLength(json, "utf-8"),
},
null,
2
);
}
return json;
}
export function formatSourceLabel(source?: string): string {
switch (source) {
case "assist":
return "官方协助/代客平台 (Assist Platform)";
case "account":
return "统一认证中心 (IDP 账密/短信)";
case "browser":
return "浏览器会话同步 (WebBridge)";
case "curl":
case "f12":
return "cURL 抓包导入 (cURL/F12)";
case "manual":
return "手动配置";
default:
return source || "未知来源";
}
}
export function formatExpiresAt(expiresAt?: number): string {
if (!expiresAt || expiresAt <= 0) return "长期有效 / 服务端未显式限制";
const diffMs = expiresAt - Date.now();
const dateStr = new Date(expiresAt).toLocaleString("zh-CN", { hour12: false });
if (diffMs <= 0) {
return `${dateStr} (⚠️ 已过期)`;
}
const diffMins = Math.floor(diffMs / 60000);
if (diffMins < 60) {
return `${dateStr} (约剩余 ${diffMins} 分钟)`;
}
const diffHours = (diffMs / 3600000).toFixed(1);
if (Number(diffHours) < 24) {
return `${dateStr} (约剩余 ${diffHours} 小时)`;
}
const diffDays = Math.floor(diffMs / 86400000);
return `${dateStr} (约剩余 ${diffDays} 天)`;
}
export function printKeyValue(pairs: Record<string, unknown>): string {
@@ -46,30 +117,52 @@ export function printHelp(): string {
核心命令域:
auth 认证与凭证管理 (login, status, refresh, import, accounts)
corps 多企业租户管理 (list, switch, current)
config 全局运行模式 (show, mode <stateful|stateless>, set)
config 全局运行模式与路径诊断 (show, paths, mode <stateful|stateless>, set)
workflow 工作流管理 (list, get, find, toggle)
bill 单据与费用明细检索 (list, get <单号|ID>, schema, link <单号|ID>)
contact 企业通讯录与人员检索 (list, search <关键词>, get <staffId>)
platform 自建应用管理 (list)
skill Agent Skill 管理 (install, status, dump)
probe 连通性诊断 (probe [corpId])
update 版本自更新与发布记录 (update, update check, update --changelog)
openapi OpenAPI 3.1.0 规范导出 (openapi, openapi --raw, openapi paths, openapi info)
http 启动轻量 HTTP Server 与交互式文档 (http [--port=8888] [--host=127.0.0.1])
service 常驻守护进程管理 (service start|stop|restart|status|logs)
mcp MCP Server 运行 (serve)
version 查看版本信息
全局选项:
--corp=<id> 临时指定操作的企业/身份 ID (覆盖默认企业)
--json, -j 以 JSON 结构化输出结果 (适合脚本/流水线集成)
--stateless 单次强制以无状态模式执行
--stateful 单次强制以有状态模式执行
--help, -h 查看帮助信息
--corp=<id> 临时指定操作的企业/身份 ID (覆盖默认企业)
--json, -j 以 JSON 结构化输出结果 (适合脚本/流水线集成)
--output-file, -o 将大体积结果直接转储至本地文件并输出精简摘要
--full 允许全量输出大体积 JSON (绕过 200KB 防爆拦截)
--stateless 单次强制以无状态模式执行
--stateful 单次强制以有状态模式执行
--help, -h 查看帮助信息
常用示例:
hose-use auth login --phone=177... --password=... # 纯 API 账密自动登录
hose-use auth status # 查看当前登录状态与活跃企业
hose-use config paths # 查看多级企业配置目录链
hose-use config mode stateless # 切换为无状态模式 (防止 Agent 误操作)
hose-use corps list # 列出名下所有企业
hose-use corps switch uzU7pcWfScck00 # 切换工作企业
hose-use corps switch ID01MCcOgJl1td # 切换工作企业
hose-use contact search 张三 # 模糊搜索员工工号、邮箱与电话
hose-use contact list --limit=20 # 采样查看企业通讯录(带防爆截断保护)
hose-use workflow list # 汇总查看全部工作流
hose-use workflow find --task=code-js2 # 搜索包含自定义脚本的工作流
hose-use bill list # 查看当前企业单据与报销列表
hose-use bill link CL20260901001 # 获取单据 Web 详情直达免密跳转链接
hose-use bill list --json -o /tmp/bills.json # 导出单据报文到本地磁盘并防爆
hose-use bill get n0GMIM0dkQmKbS # 根据单号精准查询单据结构化详情
hose-use http --port=8888 # 启动本地 HTTP 服务与可视化交互文档
hose-use service start # 后台启动常驻守护进程服务
hose-use service status # 查看守护进程运行状态与接口地址
hose-use probe # 诊断当前企业鉴权连通性
hose-use skill install # 安装 Agent 技能到用户目录
hose-use update # 自动检查并升级到最新版本
hose-use update --changelog # 查看版本发布历史
hose-use openapi paths # 查看所有 API 路径与概要一览
hose-use openapi --raw # 导出原生下游全量 OpenAPI 规范
`.trim();
}
+102 -6
View File
@@ -1,6 +1,6 @@
import { VERSION } from "../version.js";
import { parseArgs, stringOption, booleanOption } from "./parser.js";
import { printHelp, printJson } from "./printer.js";
import { parseArgs, stringOption, booleanOption, outputOptions } from "./parser.js";
import { printHelp, printJson, redactSensitiveText } from "./printer.js";
import { initCorpRuntime } from "./helpers.js";
import { handleAuthCommand } from "./commands/auth.js";
import { handleCorpsCommand } from "./commands/corps.js";
@@ -10,9 +10,74 @@ import { handlePlatformCommand } from "./commands/platform.js";
import { handleSkillCommand } from "./commands/skill.js";
import { handleProbeCommand } from "./commands/probe.js";
import { handleMcpCommand } from "./commands/mcp.js";
import { handleUpdateCommand } from "./commands/update.js";
import { handleOpenApiCommand } from "./commands/openapi.js";
import { handleBillCommand } from "./commands/bill.js";
import { handleContactCommand } from "./commands/contact.js";
import { handleServiceCommand } from "./commands/service.js";
import { handleHttpCommand } from "./commands/http.js";
import type { CliResult, CliRunOptions } from "./types.js";
export async function runCli(
const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]);
function isStandingCommand(args: string[]): boolean {
if (!args.length) return false;
const first = args[0]?.toLowerCase();
const second = args[1]?.toLowerCase();
if (STANDING_COMMANDS.has(first)) return true;
if ((first === "service" || first === "daemon") && second === "run") return true;
return false;
}
let runQueue = Promise.resolve<any>(undefined);
export function runCli(
rawArgs: string[],
options: CliRunOptions = {}
): Promise<CliResult> {
if (isStandingCommand(rawArgs)) {
return dispatchCli(rawArgs, options);
}
const run = runQueue.then(() => runCliOnce(rawArgs, options));
runQueue = run.then(
() => undefined,
() => undefined
);
return run;
}
async function runCliOnce(
rawArgs: string[],
options: CliRunOptions = {}
): Promise<CliResult> {
const stdoutChunks: string[] = [];
const stderrChunks: string[] = [];
const originalLog = console.log;
const originalError = console.error;
console.log = (...values: unknown[]) => {
stdoutChunks.push(values.map((v) => (typeof v === "string" ? v : String(v))).join(" "));
};
console.error = (...values: unknown[]) => {
stderrChunks.push(values.map((v) => (typeof v === "string" ? v : String(v))).join(" "));
};
try {
const result = await dispatchCli(rawArgs, options);
const extraStdout = stdoutChunks.length ? `${stdoutChunks.join("\n")}\n` : "";
const extraStderr = stderrChunks.length ? `${stderrChunks.join("\n")}\n` : "";
return {
stdout: redactSensitiveText(extraStdout + (result.stdout || "")),
stderr: redactSensitiveText(extraStderr + (result.stderr || "")),
exitCode: result.exitCode,
};
} finally {
console.log = originalLog;
console.error = originalError;
}
}
async function dispatchCli(
rawArgs: string[],
options: CliRunOptions = {}
): Promise<CliResult> {
@@ -30,12 +95,17 @@ export async function runCli(
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 runtime = initCorpRuntime({
corpId: corpIdOption,
stateless: statelessOption,
stateful: statefulOption,
jsonMode,
outputOptions: outputOpts,
appRoot: options.appRoot,
entryFile: options.entryFile,
launcher: options.launcher,
});
try {
@@ -53,6 +123,18 @@ export async function runCli(
case "workflows":
case "wf":
return await handleWorkflowCommand(parsed, runtime);
case "bill":
case "bills":
case "fee":
case "fees":
case "invoice":
case "invoices":
return await handleBillCommand(parsed, runtime);
case "contact":
case "contacts":
case "staff":
case "staffs":
return await handleContactCommand(parsed, runtime);
case "platform":
case "platforms":
case "app":
@@ -62,11 +144,25 @@ export async function runCli(
case "skills":
return await handleSkillCommand(parsed, runtime);
case "probe":
case "check":
case "diagnose":
return await handleProbeCommand(parsed, runtime);
case "update":
case "upgrade":
case "self-update":
case "changelog":
return await handleUpdateCommand(parsed, runtime, options);
case "openapi":
case "schema":
case "spec":
return await handleOpenApiCommand(parsed, runtime);
case "http":
case "server":
case "web":
return await handleHttpCommand(parsed, runtime);
case "service":
case "daemon":
return await handleServiceCommand(parsed, runtime);
case "mcp":
case "serve":
return await handleMcpCommand(parsed, options);
case undefined:
return { stdout: printHelp() + "\n", stderr: "", exitCode: 0 };
@@ -78,7 +174,7 @@ export async function runCli(
};
}
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
const errorMsg = redactSensitiveText(error instanceof Error ? error.message : String(error));
if (jsonMode) {
return {
stdout: printJson({ error: true, message: errorMsg }),
+83
View File
@@ -0,0 +1,83 @@
import { describe, expect, test, beforeEach, afterEach } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync, existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
serviceStatus,
getPidFile,
getLogFile,
isHoseServiceProcess,
ServiceConfig,
} from "./service.js";
describe("cli/service - 守护进程状态与自愈管理", () => {
let tempDir: string;
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "hose-service-test-"));
});
afterEach(() => {
try {
rmSync(tempDir, { recursive: true, force: true });
} catch {
// ignore
}
});
test("服务未运行时返回 running: false 并生成规范状态对象", () => {
const config: ServiceConfig = {
appRoot: tempDir,
entryFile: join(tempDir, "entry.js"),
stateDir: tempDir,
version: "0.5.0",
port: 8888,
host: "127.0.0.1",
};
const status = serviceStatus(config);
expect(status.running).toBe(false);
expect(status.pid).toBeUndefined();
expect(status.version).toBe("0.5.0");
expect(status.port).toBe(8888);
expect(status.pidFile).toBe(join(tempDir, "service.pid"));
expect(status.logFile).toBe(join(tempDir, "service.log"));
});
test("发现失效的孤儿 PID 时自动自愈清理 pidFile", () => {
const config: ServiceConfig = {
appRoot: tempDir,
entryFile: join(tempDir, "entry.js"),
stateDir: tempDir,
version: "0.5.0",
};
const pidFile = getPidFile(config);
// 写入一个不存在的荒谬 PID
writeFileSync(pidFile, "9999999\n", "utf-8");
expect(existsSync(pidFile)).toBe(true);
const status = serviceStatus(config);
expect(status.running).toBe(false);
// 验证旧文件已被自愈删除
expect(existsSync(pidFile)).toBe(false);
});
test("isHoseServiceProcess 正确识别非 hose 进程", () => {
// 当前测试进程自身不是后台 service run 守护进程
expect(isHoseServiceProcess(process.pid, "/non/existent/path")).toBe(false);
// 不存在的进程
expect(isHoseServiceProcess(9999999, tempDir)).toBe(false);
});
test("路径辅助函数返回规范的子路径", () => {
const config: ServiceConfig = {
appRoot: tempDir,
entryFile: join(tempDir, "entry.js"),
stateDir: tempDir,
};
expect(getPidFile(config)).toBe(join(tempDir, "service.pid"));
expect(getLogFile(config)).toBe(join(tempDir, "service.log"));
});
});
+223
View File
@@ -0,0 +1,223 @@
import { spawn, execFileSync } from "node:child_process";
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { startHttpServer, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST } from "../http/server.js";
export type ServiceConfig = {
appRoot: string;
entryFile: string;
stateDir: string;
version?: string;
launcher?: {
command: string;
args?: string[];
};
port?: number;
host?: string;
};
export async function runServiceCommand(
action: string | undefined,
config: ServiceConfig,
options: { quiet?: boolean } = {}
) {
switch (action) {
case "run":
await runService(config);
return undefined;
case "start":
return startService(config);
case "stop":
return stopService(config, options);
case "restart":
stopService(config, { quiet: true });
return startService(config);
case "logs":
case "log":
return readServiceLogs(config);
case "status":
case undefined:
return serviceStatus(config);
default:
throw new Error("用法: hose service <start|stop|restart|status|logs>");
}
}
export function serviceStatus(config: ServiceConfig) {
const pidFile = getPidFile(config);
const pid = readServicePid(pidFile);
const running = pid ? isHoseServiceProcess(pid, config.appRoot) : false;
if (pid && !running) {
rmSync(pidFile, { force: true });
}
const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
const host = config.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
return {
running,
pid: running ? pid : undefined,
version: config.version,
port,
host,
url: running ? `http://${host}:${port}` : undefined,
appRoot: config.appRoot,
stateDir: config.stateDir,
pidFile,
logFile: getLogFile(config),
};
}
async function runService(config: ServiceConfig) {
const pidFile = getPidFile(config);
const logFile = getLogFile(config);
ensureStateDir(config.stateDir);
writeFileSync(pidFile, `${process.pid}\n`, { mode: 0o600 });
const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
const host = config.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
appendLog(logFile, `service starting on http://${host}:${port} pid=${process.pid}`);
let server: Awaited<ReturnType<typeof startHttpServer>> | null = null;
try {
server = await startHttpServer({ port, host, silent: true });
appendLog(logFile, `service listening pid=${process.pid}`);
} catch (err: unknown) {
appendLog(logFile, `service failed to bind port ${port}: ${err instanceof Error ? err.message : String(err)}`);
if (readServicePid(pidFile) === process.pid) {
rmSync(pidFile, { force: true });
}
throw err;
}
const cleanup = () => {
if (server) {
server.close();
server = null;
}
if (readServicePid(pidFile) === process.pid) {
rmSync(pidFile, { force: true });
}
appendLog(logFile, `service stopped pid=${process.pid}`);
};
await new Promise<void>((resolve) => {
let stopped = false;
const stop = () => {
if (stopped) return;
stopped = true;
cleanup();
process.off("SIGTERM", stop);
process.off("SIGINT", stop);
resolve();
};
process.once("SIGTERM", stop);
process.once("SIGINT", stop);
});
}
function startService(config: ServiceConfig) {
ensureStateDir(config.stateDir);
const current = serviceStatus(config);
if (current.running) {
return current;
}
const launcher = config.launcher ?? { command: process.execPath, args: [config.entryFile] };
const serviceArgs = [...(launcher.args ?? []), "service", "run"];
if (config.port) serviceArgs.push(`--port=${config.port}`);
if (config.host) serviceArgs.push(`--host=${config.host}`);
const child = spawn(launcher.command, serviceArgs, {
cwd: config.appRoot,
detached: true,
stdio: ["ignore", "ignore", "ignore"],
env: process.env,
});
child.unref();
const pidFile = getPidFile(config);
writeFileSync(pidFile, `${child.pid}\n`, { mode: 0o600 });
appendLog(getLogFile(config), `service started pid=${child.pid}`);
return { started: true, ...serviceStatus(config) };
}
function stopService(config: ServiceConfig, options: { quiet?: boolean } = {}) {
const pidFile = getPidFile(config);
const pid = readServicePid(pidFile);
if (!pid || !isHoseServiceProcess(pid, config.appRoot)) {
rmSync(pidFile, { force: true });
return options.quiet ? undefined : { stopped: false, reason: "服务未处于运行状态" };
}
try {
process.kill(pid, "SIGTERM");
} catch {
// ignore
}
rmSync(pidFile, { force: true });
appendLog(getLogFile(config), `service stop requested pid=${pid}`);
return options.quiet ? undefined : { stopped: true, pid };
}
function readServiceLogs(config: ServiceConfig, maxLines = 50) {
const logFile = getLogFile(config);
if (!existsSync(logFile)) {
return { logFile, lines: [], content: "暂无服务运行日志" };
}
const content = readFileSync(logFile, "utf-8");
const lines = content.trim().split("\n").filter(Boolean).slice(-maxLines);
return {
logFile,
lines,
content: lines.join("\n"),
};
}
export function isHoseServiceProcess(pid: number, appRoot: string): boolean {
if (!isProcessRunning(pid)) return false;
try {
const command = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" });
const matchesTarget =
command.includes(appRoot) ||
command.includes("hose-use") ||
command.includes("src/cli.ts");
return matchesTarget && command.includes("service") && command.includes("run");
} catch {
return false;
}
}
function isProcessRunning(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
export function getPidFile(config: ServiceConfig): string {
return join(config.stateDir, "service.pid");
}
export function getLogFile(config: ServiceConfig): string {
return join(config.stateDir, "service.log");
}
export function readServicePid(path: string): number | undefined {
if (!existsSync(path)) return undefined;
const pid = Number(readFileSync(path, "utf-8").trim());
return Number.isInteger(pid) && pid > 0 ? pid : undefined;
}
function ensureStateDir(stateDir: string): void {
mkdirSync(stateDir, { recursive: true, mode: 0o700 });
}
function appendLog(path: string, message: string): void {
writeFileSync(path, `${new Date().toISOString()} ${message}\n`, { flag: "a", mode: 0o600 });
}
+17 -1
View File
@@ -12,7 +12,10 @@ export interface CliParsedArgs {
export interface CliRunOptions {
appRoot?: string;
entryFile?: string;
launcher?: string;
launcher?: {
command: string;
args?: string[];
};
}
export interface CliResult {
@@ -21,8 +24,21 @@ export interface CliResult {
exitCode: number;
}
export interface OutputOptions {
allowFull?: boolean;
outputFile?: string;
summary?: boolean;
}
export interface CliRuntime {
corpContext: CorpContext;
selectedCorp: CorpConfig | null;
jsonMode: boolean;
outputOptions?: OutputOptions;
appRoot?: string;
entryFile?: string;
launcher?: {
command: string;
args?: string[];
};
}
+148 -7
View File
@@ -263,13 +263,35 @@ export function parseHeadersOrCurl(rawInput: string): Partial<F12ImportParams> {
}
}
// 3. 从 URL 中提取 query 参数(例如 ?corpId=xxx 或 &corpId=xxx)
if (!result.corpId) {
const urlCorpMatch = /(?:[?&]corpId=)([^&'"\s]+)/i.exec(rawInput);
if (urlCorpMatch) {
result.corpId = decodeURIComponent(urlCorpMatch[1]);
}
}
// 4. 从 Cookie (-b / Cookie header) 中提取 ekb-access-token 或 corpId
if (!result.accessToken) {
const cookieTokenMatch = /ekb-access-token=([^;'"\s]+)/i.exec(rawInput);
if (cookieTokenMatch) {
result.accessToken = decodeURIComponent(cookieTokenMatch[1]);
}
}
if (!result.corpId) {
const cookieCorpMatch = /(?:^|;\s*)corpId=([^;'"\s]+)/i.exec(rawInput);
if (cookieCorpMatch) {
result.corpId = decodeURIComponent(cookieCorpMatch[1]);
}
}
return result;
}
/**
* 校验并导入单个 F12 抓包/手动凭证,保存到企业配置
* 校验并导入单个抓包/手动凭证,自动探测官方 Session 平台类型并保存到企业配置
*/
export async function importF12Credentials(
export async function importCredentials(
params: F12ImportParams
): Promise<CorpConfig> {
const { accessToken, corpId, staffId } = params;
@@ -279,8 +301,25 @@ export async function importF12Credentials(
throw new AuthenticationError("导入凭证失败:accessToken、corpId、staffId 均为必填项");
}
// 验证凭证有效性并尝试自动获取企业名称
let corpName = params.name;
// 1. 验证凭证有效性并提取官方服务端 Session 元数据
let sessionData: {
id?: string;
userId?: string;
loginStaffId?: string;
corporationId?: string;
platform?: string;
isAssistPlatform?: boolean;
isShortTermToken?: boolean;
assistId?: string;
operationUserId?: string;
operationUserName?: string;
privilege?: string;
deviceType?: string;
loginAccountType?: string;
loginTime?: number;
expTime?: number;
} | undefined;
try {
const res = await ky
.get(`${baseUrl}/api/account/v2/session`, {
@@ -290,20 +329,102 @@ export async function importF12Credentials(
staffid: staffId,
},
})
.json<{ value?: { corporationId?: string; loginStaffId?: string; expTime?: number } }>();
.json<{
value?: {
id?: string;
userId?: string;
loginStaffId?: string;
corporationId?: string;
platform?: string;
isAssistPlatform?: boolean;
isShortTermToken?: boolean;
assistId?: string;
operationUserId?: string;
operationUserName?: string;
privilege?: string;
deviceType?: string;
loginAccountType?: string;
loginTime?: number;
expTime?: number;
};
}>();
if (!res.value?.corporationId) {
sessionData = res.value;
if (!sessionData || (!sessionData.corporationId && !sessionData.id && !sessionData.userId)) {
throw new Error("服务端未返回有效 Session");
}
} catch (err) {
throw new AuthenticationError(`凭证校验失败,请检查 token 是否已过期: ${err instanceof Error ? err.message : String(err)}`);
}
// 2. 尝试通过 $UNITY JWT 获取真实企业名称与员工详细信息 (如果未手动指定)
let corpName = params.name;
let staffName = sessionData?.privilege;
let cellphone: string | undefined;
let isAdmin: boolean | undefined;
let sourceChannel: string | undefined;
let jwtExpMs: number | undefined;
try {
const jwtRes = await ky
.get(`${baseUrl}/api/engine/realm/$UNITY/actions/jwt`, {
searchParams: { corpId },
headers: {
accesstoken: accessToken,
corpid: corpId,
staffid: staffId,
},
})
.json<{ id?: string; value?: string }>();
const token = jwtRes.id || jwtRes.value;
if (token) {
const parts = token.split(".");
if (parts.length >= 2) {
const payload = JSON.parse(Buffer.from(parts[1], "base64").toString("utf-8"));
if (!corpName && payload.corporationName) {
corpName = payload.corporationName;
}
if (payload.staffName) {
staffName = payload.staffName;
}
if (payload.cellphone) {
cellphone = payload.cellphone;
}
if (payload.isAdmin !== undefined) {
isAdmin = payload.isAdmin === "true" || payload.isAdmin === true;
}
if (payload.exp) {
jwtExpMs = Number(payload.exp) * 1000;
}
}
}
} catch {
// 忽略尝试获取企业名失败
}
// 3. 智能判断语义化凭证来源
let source: import("../config/types.js").CredentialSource = "curl";
if (sessionData?.isAssistPlatform || sessionData?.platform === "ASSIST") {
source = "assist";
}
// 4. 计算 Token 过期时间戳 (ms)
let expiresAt: number | undefined;
if (sessionData?.expTime && sessionData.expTime > 0) {
expiresAt = sessionData.expTime;
} else if (jwtExpMs && jwtExpMs > 0) {
expiresAt = jwtExpMs;
} else if (sessionData?.isAssistPlatform && sessionData?.loginTime) {
// 协助平台短期调试 Token 通常 2 小时有效
expiresAt = sessionData.loginTime + 2 * 3600 * 1000;
}
const corpConfig: CorpConfig = {
id: corpId,
name: corpName || `企业-${corpId}`,
baseUrl,
source: "f12",
source,
staffName,
credentials: {
accessToken,
corpId,
@@ -311,6 +432,23 @@ export async function importF12Credentials(
},
auth: {
refreshTtl: 300,
expiresAt,
},
session: {
platform: sessionData?.platform,
isAssistPlatform: sessionData?.isAssistPlatform,
isShortTermToken: sessionData?.isShortTermToken,
assistId: sessionData?.assistId,
operationUserId: sessionData?.operationUserId,
operationUserName: sessionData?.operationUserName,
staffName,
cellphone,
isAdmin,
deviceType: sessionData?.deviceType,
loginAccountType: sessionData?.loginAccountType,
loginTime: sessionData?.loginTime,
expTime: expiresAt || sessionData?.expTime,
sourceChannel,
},
};
@@ -318,6 +456,9 @@ export async function importF12Credentials(
return corpConfig;
}
// 保持历史命名兼容
export const importF12Credentials = importCredentials;
// ── 企业管理与主站 OAuth2 令牌换取 ─────────────────────────────────────────────
/**
+143
View File
@@ -0,0 +1,143 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
loadCorpConfigs,
saveCorpConfig,
resolveEnterprisesDirs,
resolveWritableEnterprisesDir,
loadGlobalConfig,
saveGlobalConfig,
resolveGlobalConfigFile,
} from "./loader.js";
import type { CorpConfig } from "./types.js";
describe("core/config/loader", () => {
let tempDir: string;
const originalEnv = { ...process.env };
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "hose-config-test-"));
});
afterEach(() => {
process.env = { ...originalEnv };
try {
rmSync(tempDir, { recursive: true, force: true });
} catch {
// ignore
}
});
test("resolveEnterprisesDirs prioritizes HOSE_ENTERPRISES_DIR environment variable", () => {
const customDir = join(tempDir, "custom-enterprises");
mkdirSync(customDir, { recursive: true });
process.env.HOSE_ENTERPRISES_DIR = customDir;
const dirs = resolveEnterprisesDirs();
expect(dirs).toEqual([customDir]);
});
test("resolveWritableEnterprisesDir respects HOSE_ENTERPRISES_DIR", () => {
const customDir = join(tempDir, "writable-enterprises");
mkdirSync(customDir, { recursive: true });
process.env.HOSE_ENTERPRISES_DIR = customDir;
expect(resolveWritableEnterprisesDir()).toBe(customDir);
});
const createMockCorp = (id: string, name: string, overrides: Partial<CorpConfig> = {}): CorpConfig => ({
id,
name,
baseUrl: "https://app.ekuaibao.com",
source: "manual",
credentials: {
accessToken: `token-${id}`,
corpId: id,
staffId: `staff-${id}`,
},
...overrides,
});
test("loadCorpConfigs loads valid configs and skips example files", () => {
const dirA = join(tempDir, "dirA");
mkdirSync(dirA, { recursive: true });
const validCorp = createMockCorp("corp-1", "企业1");
// Save valid corp
writeFileSync(join(dirA, "corp-1.json"), JSON.stringify(validCorp));
// Save example corp
writeFileSync(
join(dirA, "example.json"),
JSON.stringify(createMockCorp("example-corp", "模板企业"))
);
const loaded = loadCorpConfigs([dirA]);
expect(loaded).toHaveLength(1);
expect(loaded[0]?.id).toBe("corp-1");
expect(loaded[0]?.name).toBe("企业1");
});
test("loadCorpConfigs merges multiple directories with earlier directory taking precedence", () => {
const dirA = join(tempDir, "dirA");
const dirB = join(tempDir, "dirB");
mkdirSync(dirA, { recursive: true });
mkdirSync(dirB, { recursive: true });
const corpInA = createMockCorp("corp-common", "本地优先企业", {
credentials: { accessToken: "token-a", corpId: "corp-common", staffId: "staff-a" },
});
const corpInB = createMockCorp("corp-common", "全局覆盖企业", {
credentials: { accessToken: "token-b", corpId: "corp-common", staffId: "staff-b" },
});
const corpOnlyB = createMockCorp("corp-b-only", "仅在B的企业", {
credentials: { accessToken: "token-b2", corpId: "corp-b-only", staffId: "staff-b2" },
});
writeFileSync(join(dirA, "corp-common.json"), JSON.stringify(corpInA));
writeFileSync(join(dirB, "corp-common.json"), JSON.stringify(corpInB));
writeFileSync(join(dirB, "corp-b-only.json"), JSON.stringify(corpOnlyB));
const loaded = loadCorpConfigs([dirA, dirB]);
expect(loaded).toHaveLength(2);
const common = loaded.find((c) => c.id === "corp-common");
expect(common?.name).toBe("本地优先企业");
const bOnly = loaded.find((c) => c.id === "corp-b-only");
expect(bOnly?.name).toBe("仅在B的企业");
});
test("saveCorpConfig writes validated JSON to target directory", () => {
const targetDir = join(tempDir, "save-target");
const corp = createMockCorp("corp-save-test", "保存测试企业", {
credentials: { accessToken: "tok-123", corpId: "corp-save-test", staffId: "stf-1" },
});
const filePath = saveCorpConfig(corp, targetDir);
expect(existsSync(filePath)).toBe(true);
const saved = JSON.parse(readFileSync(filePath, "utf-8"));
expect(saved.id).toBe("corp-save-test");
expect(saved.credentials.accessToken).toBe("tok-123");
});
test("loadGlobalConfig and saveGlobalConfig respect HOSE_CONFIG_FILE", () => {
const customConfigFile = join(tempDir, "config.json");
process.env.HOSE_CONFIG_FILE = customConfigFile;
expect(resolveGlobalConfigFile()).toBe(customConfigFile);
const initial = loadGlobalConfig();
expect(initial.stateful).toBe(true);
saveGlobalConfig({ stateful: false, defaultCorpId: "test-corp-123" });
const updated = loadGlobalConfig();
expect(updated.stateful).toBe(false);
expect(updated.defaultCorpId).toBe("test-corp-123");
});
});
+114 -37
View File
@@ -1,30 +1,96 @@
import { readFileSync, readdirSync, writeFileSync, mkdirSync } from "fs";
import { join, dirname } from "path";
import { homedir } from "os";
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
const ENTERPRISES_DIR = "./enterprises";
const GLOBAL_CONFIG_PATH = join(homedir(), ".cache", "ekb-mcp", "config.json");
const ENTERPRISES_DIR = "enterprises";
const CONFIG_ENV = "HOSE_ENTERPRISES_DIR";
const USER_DIR_ENV = "HOSE_USER_ENTERPRISES_DIR";
const GLOBAL_CONFIG_ENV = "HOSE_CONFIG_FILE";
export const PRIMARY_USER_ENTERPRISES_DIR = join(homedir(), ".config", "hose-use", "enterprises");
export const LEGACY_USER_ENTERPRISES_DIR = join(homedir(), ".cache", "ekb-mcp", "enterprises");
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");
function ensureDir(dir: string): void {
mkdirSync(dir, { recursive: true });
}
export function resolveEnterprisesDirs(): string[] {
const configured = process.env[CONFIG_ENV]?.trim();
if (configured) {
return existsSync(configured) ? [configured] : [];
}
const configuredUserDir = process.env[USER_DIR_ENV]?.trim();
if (configuredUserDir) {
return [ENTERPRISES_DIR, configuredUserDir].filter((dir) => existsSync(dir));
}
const dirs = [ENTERPRISES_DIR, PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR];
const uniqueExisting: string[] = [];
for (const d of dirs) {
if (existsSync(d) && !uniqueExisting.includes(d)) {
uniqueExisting.push(d);
}
}
return uniqueExisting;
}
export function resolvePrimaryEnterprisesDir(): string | undefined {
const configured = process.env[CONFIG_ENV]?.trim();
if (configured) return existsSync(configured) ? configured : undefined;
if (existsSync(ENTERPRISES_DIR)) return ENTERPRISES_DIR;
if (existsSync(PRIMARY_USER_ENTERPRISES_DIR)) return PRIMARY_USER_ENTERPRISES_DIR;
if (existsSync(LEGACY_USER_ENTERPRISES_DIR)) return LEGACY_USER_ENTERPRISES_DIR;
return undefined;
}
export function resolveWritableEnterprisesDir(): string {
const configured = process.env[CONFIG_ENV]?.trim();
if (configured) return configured;
const configuredUserDir = process.env[USER_DIR_ENV]?.trim();
if (configuredUserDir) return configuredUserDir;
if (existsSync(ENTERPRISES_DIR)) return ENTERPRISES_DIR;
return PRIMARY_USER_ENTERPRISES_DIR;
}
export function getEnterprisesDirCandidates(): string[] {
return [
`${CONFIG_ENV}=<path>`,
ENTERPRISES_DIR,
PRIMARY_USER_ENTERPRISES_DIR,
LEGACY_USER_ENTERPRISES_DIR,
];
}
export function resolveGlobalConfigFile(): string {
return GLOBAL_CONFIG_PATH;
const configured = process.env[GLOBAL_CONFIG_ENV]?.trim();
if (configured) return configured;
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 loadGlobalConfig(): GlobalConfig {
const file = resolveGlobalConfigFile();
try {
const content = readFileSync(GLOBAL_CONFIG_PATH, "utf-8");
return GlobalConfigSchema.parse(JSON.parse(content));
if (existsSync(file)) {
const content = readFileSync(file, "utf-8");
return GlobalConfigSchema.parse(JSON.parse(content));
}
} catch {
return {
stateful: true,
defaultCorpId: undefined,
defaultAccountId: undefined,
};
// 容错返回默认
}
return {
stateful: true,
defaultCorpId: undefined,
defaultAccountId: undefined,
};
}
export function saveGlobalConfig(config: Partial<GlobalConfig>): GlobalConfig {
@@ -33,50 +99,61 @@ export function saveGlobalConfig(config: Partial<GlobalConfig>): GlobalConfig {
...current,
...config,
});
ensureDir(dirname(GLOBAL_CONFIG_PATH));
writeFileSync(GLOBAL_CONFIG_PATH, JSON.stringify(updated, null, 2), "utf-8");
const configured = process.env[GLOBAL_CONFIG_ENV]?.trim();
const targetFile = configured || PRIMARY_GLOBAL_CONFIG_FILE;
ensureDir(dirname(targetFile));
writeFileSync(targetFile, JSON.stringify(updated, null, 2), "utf-8");
return updated;
}
export function loadCorpConfigs(dir: string = ENTERPRISES_DIR): CorpConfig[] {
let files: string[];
try {
ensureDir(dir);
files = readdirSync(dir).filter((f) => f.endsWith(".json"));
} catch (error) {
console.error(
`[config] failed to read enterprises directory: ${error instanceof Error ? error.message : String(error)}`
);
return [];
}
export function loadCorpConfigs(overrideDirs?: string[]): CorpConfig[] {
const dirs = overrideDirs ? overrideDirs.filter(existsSync) : resolveEnterprisesDirs();
const byId = new Map<string, CorpConfig>();
const configs: CorpConfig[] = [];
for (const file of files) {
for (const dir of dirs) {
try {
const content = readFileSync(join(dir, file), "utf-8");
const parsed = JSON.parse(content);
configs.push(CorpConfigSchema.parse(parsed));
const files = readdirSync(dir)
.filter((item) => item.endsWith(".json"))
.filter((item) => !item.startsWith("example."));
for (const file of files) {
try {
const content = readFileSync(join(dir, file), "utf-8");
const parsed = JSON.parse(content);
const corp = CorpConfigSchema.parse(parsed);
// 相同企业 ID 以先出现的为准(工作区优先于全局,全局优先于历史)
if (!byId.has(corp.id)) {
byId.set(corp.id, corp);
}
} catch (error) {
console.error(
`[config] failed to load ${file} from ${dir}: ${error instanceof Error ? error.message : String(error)}`
);
}
}
} catch (error) {
console.error(
`[config] failed to load ${file}: ${error instanceof Error ? error.message : String(error)}`
`[config] failed to read enterprises directory ${dir}: ${error instanceof Error ? error.message : String(error)}`
);
}
}
return configs;
return Array.from(byId.values());
}
export function saveCorpConfig(config: CorpConfig, dir: string = ENTERPRISES_DIR): string {
ensureDir(dir);
export function saveCorpConfig(config: CorpConfig, dir?: string): string {
const targetDir = dir || resolveWritableEnterprisesDir();
ensureDir(targetDir);
const validated = CorpConfigSchema.parse(config);
const filePath = join(dir, `${validated.id}.json`);
const filePath = join(targetDir, `${validated.id}.json`);
writeFileSync(filePath, JSON.stringify(validated, null, 2), "utf-8");
return filePath;
}
export function saveMultipleCorpConfigs(
configs: CorpConfig[],
dir: string = ENTERPRISES_DIR
dir?: string
): string[] {
return configs.map((config) => saveCorpConfig(config, dir));
}
+16 -8
View File
@@ -9,6 +9,7 @@ export interface CorpSummary {
staffId: string;
baseUrl?: string;
current: boolean;
expiresAt?: number;
}
export function resolveCorpConfig(
@@ -17,7 +18,8 @@ export function resolveCorpConfig(
stateful: boolean;
defaultCorpId?: string;
corpId?: string;
}
},
candidateDirs?: string[]
): CorpConfig {
const requestedCorpId = options.corpId?.trim() || undefined;
const configuredCorpId = options.stateful
@@ -50,7 +52,8 @@ export function resolveCorpConfig(
const firstCorp = corps[0];
if (firstCorp) return firstCorp;
throw new Error("未找到任何企业配置。请先运行 `hose auth login` 或在 enterprises/ 目录下添加配置。");
const hintDirs = candidateDirs?.length ? ` (已检索路径: ${candidateDirs.join(", ")})` : "";
throw new Error(`未找到任何企业配置。请先运行 'hose auth login' 登录或添加企业配置${hintDirs}。`);
}
export class CorpContext {
@@ -109,12 +112,16 @@ export class CorpContext {
return this.corps.get(corpId);
}
resolve(corpId?: string): CorpConfig {
return resolveCorpConfig(Array.from(this.corps.values()), {
stateful: this.stateful,
defaultCorpId: this.defaultCorpId,
corpId,
});
resolve(corpId?: string, candidateDirs?: string[]): CorpConfig {
return resolveCorpConfig(
Array.from(this.corps.values()),
{
stateful: this.stateful,
defaultCorpId: this.defaultCorpId,
corpId,
},
candidateDirs
);
}
upsertCorp(corp: CorpConfig, setCurrent: boolean = false): void {
@@ -145,6 +152,7 @@ export class CorpContext {
staffId: corp.credentials.staffId,
baseUrl: corp.baseUrl,
current: corp.id === this.current?.id,
expiresAt: corp.auth?.expiresAt || corp.session?.expTime,
}));
}
}
+29 -2
View File
@@ -1,6 +1,13 @@
import { z } from "zod";
export const CredentialSourceSchema = z.enum(["account", "manual", "browser", "f12"]);
export const CredentialSourceSchema = z.enum([
"account", // 官方统一认证中心 (IDP) 账密/短信登录
"assist", // 官方协助/代客平台 (Assist Platform) 调试授权会话
"browser", // 浏览器会话 / Cookie 同步
"manual", // 手动配置
"curl", // cURL 抓包 / HTTP Headers 导入
"f12", // 兼容旧版抓包标识
]);
export type CredentialSource = z.infer<typeof CredentialSourceSchema>;
export const CorpCredentialsSchema = z.object({
@@ -15,17 +22,37 @@ export const CorpAuthConfigSchema = z.object({
expiresAt: z.number().optional().describe("AccessToken 到期时间戳 (ms)"),
});
export const CorpSessionInfoSchema = z.object({
platform: z.string().optional().describe("官方会话平台类型 (如 ASSIST, WEB, MOBILE, OPENAPI)"),
isAssistPlatform: z.boolean().optional().describe("是否为官方协助/代客平台登录"),
isShortTermToken: z.boolean().optional().describe("是否为短期临时 Token"),
assistId: z.string().optional().describe("协助会话/工单 ID"),
operationUserId: z.string().optional().describe("协助操作人 ID (如内部运维/实施账号)"),
operationUserName: z.string().optional().describe("协助操作人姓名"),
staffName: z.string().optional().describe("当前员工真实姓名"),
cellphone: z.string().optional().describe("绑定手机号"),
isAdmin: z.boolean().optional().describe("是否管理员"),
deviceType: z.string().optional().describe("设备类型"),
loginAccountType: z.string().optional().describe("登录账号类型"),
loginTime: z.number().optional().describe("登录时间戳 (ms)"),
expTime: z.number().optional().describe("过期时间戳 (ms)"),
sourceChannel: z.string().optional().describe("来源渠道 (如 APP, WEB)"),
});
export type CorpSessionInfo = z.infer<typeof CorpSessionInfoSchema>;
export const CorpConfigSchema = z.object({
id: z.string().describe("配置/身份唯一标识 (默认等于 corpId,同企业多身份时形如 corpId@accountId 或 corpId:staffId)"),
name: z.string().describe("企业名称"),
corpId: z.string().optional().describe("底层企业物理 ID (未填时默认等于 id)"),
userId: z.string().optional().describe("所属用户 ID"),
staffId: z.string().optional().describe("员工工号 (默认取 credentials.staffId)"),
staffName: z.string().optional().describe("员工真实姓名"),
baseUrl: z.string().url().optional().default("https://app.ekuaibao.com"),
source: CredentialSourceSchema.optional().default("manual").describe("凭证来源: account/manual/browser/f12"),
source: CredentialSourceSchema.optional().default("manual").describe("凭证来源: account/assist/browser/manual/curl/f12"),
accountId: z.string().optional().describe("所属主账号标识(如手机号)"),
credentials: CorpCredentialsSchema,
auth: CorpAuthConfigSchema.optional(),
session: CorpSessionInfoSchema.optional().describe("官方服务端 Session 与操作人元数据"),
});
export type CorpCredentials = z.infer<typeof CorpCredentialsSchema>;
+31
View File
@@ -0,0 +1,31 @@
import { describe, expect, test } from "bun:test";
import { getOpenApiSchema, listOpenApiPaths } from "./embedded-openapi.js";
describe("embedded OpenAPI", () => {
test("wrapped OpenAPI contains paths and components", () => {
const wrapped = getOpenApiSchema("wrapped");
expect(wrapped.openapi).toBe("3.1.0");
expect(wrapped.info).toBeDefined();
expect(wrapped.paths).toBeDefined();
expect(Object.keys(wrapped.paths as object).length).toBeGreaterThan(0);
const paths = listOpenApiPaths("wrapped");
expect(paths.length).toBeGreaterThan(0);
expect(paths.some((p) => p.path === "/api/auth/login")).toBe(true);
expect(paths.some((p) => p.path === "/api/workflows")).toBe(true);
});
test("raw downstream OpenAPI contains downstream paths", () => {
const raw = getOpenApiSchema("raw");
expect(raw.openapi).toBe("3.1.0");
expect(raw.info).toBeDefined();
expect(raw.paths).toBeDefined();
expect(Object.keys(raw.paths as object).length).toBeGreaterThan(0);
const paths = listOpenApiPaths("raw");
expect(paths.length).toBeGreaterThan(0);
expect(paths.some((p) => p.path === "/api/common/security/getPublicKey")).toBe(true);
expect(paths.some((p) => p.path === "/api/open/oauth2/token")).toBe(true);
expect(paths.some((p) => p.path === "/api/easo/pipelines/logs")).toBe(true);
});
});
+38
View File
@@ -0,0 +1,38 @@
import wrappedOpenApi from "../../dist/openapi.json" with { type: "json" };
import rawOpenApi from "../../dist/raw-hose-openapi.json" with { type: "json" };
export type OpenApiType = "wrapped" | "raw";
export function getOpenApiSchema(type: OpenApiType = "wrapped"): Record<string, unknown> {
if (type === "raw") {
return rawOpenApi as Record<string, unknown>;
}
return wrappedOpenApi as Record<string, unknown>;
}
export function listOpenApiPaths(type: OpenApiType = "wrapped"): Array<{
path: string;
method: string;
summary: string;
tags: string[];
}> {
const schema = getOpenApiSchema(type);
const paths = (schema.paths as Record<string, Record<string, any>>) || {};
const results: Array<{ path: string; method: string; summary: string; tags: string[] }> = [];
for (const [pathKey, methods] of Object.entries(paths)) {
if (typeof methods !== "object" || methods === null) continue;
for (const [method, def] of Object.entries(methods)) {
if (["get", "post", "put", "delete", "patch"].includes(method.toLowerCase()) && typeof def === "object") {
results.push({
path: pathKey,
method: method.toUpperCase(),
summary: def.summary || def.description || "",
tags: def.tags || [],
});
}
}
}
return results;
}
+49
View File
@@ -0,0 +1,49 @@
import { describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { EMBEDDED_SKILL_FILES, getSkillContent, installSkillFiles } from "./embedded-skill.js";
describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
test("正确内嵌 SKILL.md、agents/openai.yaml 及各领域参考专卷", () => {
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toBeDefined();
expect(EMBEDDED_SKILL_FILES["SKILL.md"]).toContain("name: hose-use");
expect(getSkillContent()).toContain("name: hose-use");
expect(EMBEDDED_SKILL_FILES["agents/openai.yaml"]).toBeDefined();
expect(EMBEDDED_SKILL_FILES["agents/openai.yaml"]).toContain("hose_cli");
expect(EMBEDDED_SKILL_FILES["references/auth.md"]).toBeDefined();
expect(EMBEDDED_SKILL_FILES["references/auth.md"]).toContain("RSA");
expect(EMBEDDED_SKILL_FILES["references/bill.md"]).toBeDefined();
expect(EMBEDDED_SKILL_FILES["references/bill.md"]).toContain("bill get");
expect(EMBEDDED_SKILL_FILES["references/workflow.md"]).toBeDefined();
expect(EMBEDDED_SKILL_FILES["references/workflow.md"]).toContain("workflow find");
expect(EMBEDDED_SKILL_FILES["references/service.md"]).toBeDefined();
expect(EMBEDDED_SKILL_FILES["references/service.md"]).toContain("POST /api/cli");
expect(EMBEDDED_SKILL_FILES["references/contact.md"]).toBeDefined();
expect(EMBEDDED_SKILL_FILES["references/contact.md"]).toContain("contact search");
});
test("installSkillFiles 递归保留层级结构并落盘到目标目录", () => {
const tmp = mkdtempSync(join(tmpdir(), "hose-skill-test-"));
try {
const res = installSkillFiles(tmp);
expect(res.targetDir).toBe(tmp);
expect(res.files.length).toBe(7);
expect(existsSync(join(tmp, "SKILL.md"))).toBe(true);
expect(existsSync(join(tmp, "agents", "openai.yaml"))).toBe(true);
expect(existsSync(join(tmp, "references", "auth.md"))).toBe(true);
expect(existsSync(join(tmp, "references", "bill.md"))).toBe(true);
expect(existsSync(join(tmp, "references", "contact.md"))).toBe(true);
expect(existsSync(join(tmp, "references", "workflow.md"))).toBe(true);
expect(existsSync(join(tmp, "references", "service.md"))).toBe(true);
} finally {
rmSync(tmp, { recursive: true, force: true });
}
});
});
+14 -1
View File
@@ -1,10 +1,23 @@
import { existsSync, mkdirSync, writeFileSync, readFileSync } from "node:fs";
import { mkdirSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import skillMain from "../../skills/hose-use/SKILL.md" with { type: "text" };
import agentOpenAi from "../../skills/hose-use/agents/openai.yaml" with { type: "text" };
import refAuth from "../../skills/hose-use/references/auth.md" with { type: "text" };
import refBill from "../../skills/hose-use/references/bill.md" with { type: "text" };
import refWorkflow from "../../skills/hose-use/references/workflow.md" with { type: "text" };
import refService from "../../skills/hose-use/references/service.md" with { type: "text" };
import refContact from "../../skills/hose-use/references/contact.md" with { type: "text" };
export const EMBEDDED_SKILL_FILES: Record<string, string> = {
"SKILL.md": skillMain,
"agents/openai.yaml": agentOpenAi,
"references/auth.md": refAuth,
"references/bill.md": refBill,
"references/contact.md": refContact,
"references/workflow.md": refWorkflow,
"references/service.md": refService,
};
export function getSkillContent(): string {
+40
View File
@@ -0,0 +1,40 @@
import { dirname } from "node:path";
import { fileURLToPath } from "node:url";
export function isCompiledBinary(execPath = process.execPath, metaUrl = import.meta.url): boolean {
if (metaUrl.includes("/$bunfs/") || metaUrl.includes("\\$bunfs\\")) {
return true;
}
const lower = execPath.toLowerCase().replace(/\\/g, "/");
return !lower.endsWith("/bun") && !lower.endsWith("/bun.exe");
}
export function resolveAppRoot(entryFile?: string, isCompiled = isCompiledBinary()): string {
if (isCompiled) {
return process.cwd();
}
const file = entryFile || fileURLToPath(import.meta.url);
return dirname(dirname(file));
}
export type LauncherConfig = {
command: string;
args?: string[];
};
export function resolveDefaultLauncher(
entryFile: string,
isCompiled = isCompiledBinary(),
execPath = process.execPath
): LauncherConfig {
if (isCompiled) {
return {
command: execPath,
args: [],
};
}
return {
command: execPath,
args: [entryFile],
};
}
+1
View File
@@ -7,6 +7,7 @@
| 域 | 说明 | 详细文档 |
|---|---|---|
| `platform/` | 自建应用(DataLink Platform)与工作流(EASO/Piper) | [README.platform.md](./platform/README.platform.md) |
| `bill/` | 费控单据、报销单、发票与 DataLink 实体字典 | [README.bill.md](./bill/README.bill.md) |
## 分层规则
+24
View File
@@ -0,0 +1,24 @@
# Bill 域说明
本目录负责合思/易快报(ekuaibao)费控单据、报销单、借款单、发票与数据实体元数据字典的检索与格式化。
## 文件结构
```text
src/domains/bill/
├── api.ts # 传输层:调用 /api/v2/invoice/search, /api/v2/invoice, /api/v2/datalink/entity/search
├── tools.ts # 业务编排层:DataLink 字段字典映射、单号匹配、格式化与 MCP tools
├── types.ts # 模型层:Zod Schema 与 TypeScript 类型定义
├── bill.test.ts # 单元测试
└── README.bill.md # 本说明文件
```
## 核心能力
1. **单据检索与分页 (`searchAndFormatBills`)**:
- 跨单据池查询费用明细、报销单、借款单与发票。
- 支持按单号(`code`)、阶段(`stage`)、状态(`state`)、关键字(`keyword`)过滤。
2. **按单号/ID 精确查询 (`getBillByCodeOrId`)**:
- 根据业务单号(如 `n0GMIM0dkQmKbS`)或单据 ID(如 `ID01TRzg7HMLcb`)查询单据。
3. **DataLink 字段元数据字典 (`getFieldDictionary`)**:
- 自动拉取企业全部实体模型定义,将混淆代码字段(如 `E_ae10..._payMoney`)还原为人类友好的中文字段名(如 `报销金额`)。
+71
View File
@@ -0,0 +1,71 @@
import { KyInstance } from "ky";
import {
RawBillSearchResponseSchema,
RawBillBatchGetResponseSchema,
EntityListResponseSchema,
type RawBillSearchResponse,
type RawBillItem,
type EntityMeta,
} from "./types.js";
// ── 原始单据检索 API ──────────────────────────────────────────────────────────
export async function searchRawBills(
client: KyInstance,
corpId: string,
options: { start?: number; count?: number } = {}
): 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 json = await response.json();
return RawBillSearchResponseSchema.parse(json);
}
// ── 按 ID 列表精确拉取单据详情 API ─────────────────────────────────────────────
export async function getRawBillsByIds(
client: KyInstance,
corpId: string,
ids: string[]
): Promise<RawBillItem[]> {
if (ids.length === 0) return [];
const response = await client.post("api/v2/invoice", {
searchParams: { corporationId: corpId, corpId },
json: { ids },
});
const json = await response.json();
const parsed = RawBillBatchGetResponseSchema.parse(json);
return parsed.items;
}
// ── 单据实体与字段元数据字典 API ───────────────────────────────────────────────
export async function listEntitySchemas(
client: KyInstance,
corpId: string,
options: { start?: number; count?: number } = {}
): Promise<EntityMeta[]> {
const response = await client.post("api/v2/datalink/entity/search", {
searchParams: { corporationId: corpId, corpId },
json: {
limit: {
start: options.start ?? 0,
count: options.count ?? 100,
},
},
});
const json = await response.json();
const parsed = EntityListResponseSchema.parse(json);
return parsed.items;
}
+69
View File
@@ -0,0 +1,69 @@
import { describe, it, expect } from "bun:test";
import { formatSingleBill } from "./tools.js";
import { RawBillItemSchema, EntitySchema } from "./types.js";
describe("Bill Domain", () => {
it("validates EntitySchema", () => {
const rawEntity = {
id: "ae1037940b1c304017c0",
code: "FEE_DETAIL",
name: "费用明细",
type: "EXPENSE",
active: true,
fields: [
{
name: "E_ae1037940b1c304017c0_payMoney",
type: "money",
label: "支付金额",
optional: false,
formula: false,
},
],
};
const parsed = EntitySchema.parse(rawEntity);
expect(parsed.id).toBe("ae1037940b1c304017c0");
expect(parsed.fields[0].label).toBe("支付金额");
});
it("validates RawBillItemSchema and formats fields with dictionary", () => {
const rawBill = {
id: "ID01TRzg7HMLcb",
code: "n0GMIM0dkQmKbS",
name: "项目&100",
corporationId: "ID01ofWoOC1wiX",
ownerId: "ID01ofWoOC1wiX:ID01ojZ2n2e0PR",
createTime: 1781682826000,
updateTime: 1781682870000,
form: {
E_test_code: "n0GMIM0dkQmKbS",
E_test_title: "测试单据标题",
E_test_stage: "expense",
E_test_state: "paid",
E_test_amount: {
standard: "100.00",
standardUnit: "元",
standardSymbol: "¥",
standardStrCode: "CNY",
},
E_test_submitterId: "staff-123",
E_test_customField: "VIP客户",
},
};
const parsed = RawBillItemSchema.parse(rawBill);
expect(parsed.id).toBe("ID01TRzg7HMLcb");
const dict = new Map<string, { label: string; type: string }>();
dict.set("E_test_customField", { label: "客户等级", type: "text" });
const formatted = formatSingleBill(parsed, dict);
expect(formatted.billId).toBe("ID01TRzg7HMLcb");
expect(formatted.billCode).toBe("n0GMIM0dkQmKbS");
expect(formatted.title).toBe("测试单据标题");
expect(formatted.stage).toBe("expense");
expect(formatted.state).toBe("paid");
expect(formatted.amount).toBe("¥100.00 CNY");
expect(formatted.details["客户等级"]).toBe("VIP客户");
});
});
+382
View File
@@ -0,0 +1,382 @@
import { z } from "zod";
import { KyInstance } from "ky";
import { searchRawBills, getRawBillsByIds, listEntitySchemas } from "./api.js";
import {
type RawBillItem,
type FormattedBill,
type BillPageResult,
type EntityMeta,
type BillQueryParams,
} from "./types.js";
import { CorpContext } from "../../core/config/manager.js";
import { createEkbClient } from "../../core/auth/ekb.js";
// ── 通用内置字段中文 Label 字典 ───────────────────────────────────────────────
const COMMON_FIELD_LABELS: Record<string, string> = {
code: "单据编号",
name: "单据名称",
stage: "业务阶段",
state: "审批状态",
title: "单据标题",
amount: "单据金额",
expenseMoney: "报销金额",
payMoney: "支付金额",
apportionMoney: "分摊金额",
submitDate: "提交时间",
submitterId: "提交人ID",
ownerId: "归属人ID",
description: "事由说明",
detailType: "明细类型",
entityType: "实体类型",
settleStatus: "结算状态",
settleTime: "结算时间",
billingStatus: "开票状态",
voucherStatus: "凭证状态",
voucherCreateTime: "凭证生成时间",
writtenOffAmount: "已核销金额",
unwrittenOffAmount: "未核销金额",
linkType: "关联类型",
linkId: "关联审批流ID",
detailId: "明细ID",
detailNo: "明细序号",
feeTypeId: "费用类型ID",
attachments: "附件列表",
invoiceForm: "发票表单",
submitCount: "提交次数",
rejectionNum: "驳回次数",
reviewStatus: "审核状态",
preApprovedNodeName: "上一审批节点",
preNodeApprovedTime: "节点审批通过时间",
accountPropertyMoney: "核算属性金额",
accountPropertyDate: "核算属性日期",
flowSpecificationId: "流程规范ID",
feeDetailSpecificationId: "费用明细规范ID",
printState: "打印状态",
printCount: "打印次数",
onlyOwnerPrint: "仅提交人可打印",
ownerAndApproverPrintNodeFlag: "节点打印控制标识",
};
// ── 字段元数据内存缓存 ─────────────────────────────────────────────────────────
const schemaCache = new Map<string, { timestamp: number; dictionary: Map<string, { label: string; type: string }>; entities: EntityMeta[] }>();
const CACHE_TTL_MS = 10 * 60 * 1000; // 10 分钟缓存
export async function getFieldDictionary(
client: KyInstance,
corpId: string,
forceRefresh = false
): Promise<{ dictionary: Map<string, { label: string; type: string }>; entities: EntityMeta[] }> {
const cached = schemaCache.get(corpId);
if (!forceRefresh && cached && Date.now() - cached.timestamp < CACHE_TTL_MS) {
return cached;
}
const entities = await listEntitySchemas(client, corpId, { start: 0, count: 100 });
const dictionary = new Map<string, { label: string; type: string }>();
for (const entity of entities) {
for (const field of entity.fields) {
if (field.name && field.label) {
dictionary.set(field.name, { label: field.label, type: field.type });
}
}
}
const result = { timestamp: Date.now(), dictionary, entities };
schemaCache.set(corpId, result);
return result;
}
// ── 格式化单据数据 ─────────────────────────────────────────────────────────────
export function formatSingleBill(
item: RawBillItem,
dictionary: Map<string, { label: string; type: string }>
): FormattedBill {
const rawForm = item.form || {};
let billCode = item.code || "";
let billName = item.name || "";
let title: string | undefined;
let stage: string | undefined;
let state: string | undefined;
let amountStr: string | undefined;
let submitterId: string | undefined;
let submitDateStr: string | undefined;
const readableDetails: Record<string, any> = {};
for (const [k, v] of Object.entries(rawForm)) {
if (v === null || v === undefined || v === "") continue;
// 提取核心通用业务字段
if (k.endsWith("_code") && typeof v === "string") billCode = billCode || v;
if (k.endsWith("_title") && typeof v === "string") title = v;
if (k.endsWith("_stage") && typeof v === "string") stage = v;
if (k.endsWith("_state") && typeof v === "string") state = v;
if (k.endsWith("_submitterId") && typeof v === "string") submitterId = v;
// 格式化金额
if (k.endsWith("_amount") || k.endsWith("_expenseMoney") || k.endsWith("_payMoney")) {
if (typeof v === "object" && v !== null && (v as any).standard) {
const money = v as any;
const formatted = `${money.standardSymbol || "¥"}${money.standard} ${money.standardStrCode || "CNY"}`.trim();
if (!amountStr || k.endsWith("_amount")) {
amountStr = formatted;
}
}
}
// 格式化提交时间
if (k.endsWith("_submitDate") && typeof v === "number" && v > 1000000000000) {
submitDateStr = new Date(v).toLocaleString("zh-CN");
}
// 字典 Label 还原
const meta = dictionary.get(k);
const bareKey = k.replace(/^E_[^_]+_/, "").replace(/^E_/, "");
let readableKey = meta ? meta.label : (COMMON_FIELD_LABELS[k] || COMMON_FIELD_LABELS[bareKey] || bareKey);
// 格式化字段值
let formattedVal = v;
if (typeof v === "number" && v > 1000000000000 && v < 2500000000000 && !k.endsWith("_code") && !k.endsWith("_No")) {
formattedVal = `${new Date(v).toLocaleString("zh-CN")}`;
} else if (typeof v === "object" && v !== null && (v as any).standard) {
const money = v as any;
formattedVal = `${money.standardSymbol || "¥"}${money.standard} ${money.standardStrCode || "CNY"}`.trim();
}
readableDetails[readableKey] = formattedVal;
}
const createTimeStr = item.createTime > 0
? new Date(item.createTime).toLocaleString("zh-CN")
: "";
const updateTimeStr = item.updateTime > 0
? new Date(item.updateTime).toLocaleString("zh-CN")
: "";
return {
billId: item.id,
billCode: billCode || item.id,
billName: billName || item.id,
title,
stage,
state,
amount: amountStr,
submitterId,
submitDate: submitDateStr,
corporationId: item.corporationId || "",
ownerId: item.ownerId || "",
createTime: createTimeStr,
updateTime: updateTimeStr,
details: readableDetails,
};
}
// ── 业务操作:按单号或 ID 精确查询单据 ─────────────────────────────────────────
export async function getBillByCodeOrId(
client: KyInstance,
corpId: string,
queryCodeOrId: string
): Promise<FormattedBill[]> {
const cleanQuery = queryCodeOrId.trim();
if (!cleanQuery) return [];
const { dictionary } = await getFieldDictionary(client, corpId);
// 1. 如果传入的是 ID 格式(如 ID01...),先尝试走精准 ID 批量接口
if (cleanQuery.startsWith("ID01")) {
try {
const items = await getRawBillsByIds(client, corpId, [cleanQuery]);
if (items.length > 0) {
return items.map((it) => formatSingleBill(it, dictionary));
}
} catch {
// 忽略错误,继续回退到 search 检索
}
}
// 2. 从 search 中匹配单号、flowCode、ID 或关联 LinkId
const searchRes = await searchRawBills(client, corpId, { start: 0, count: 50 });
const matched = searchRes.items.filter((item) => {
if (item.id === cleanQuery) return true;
if (item.code === cleanQuery) return true;
for (const [k, v] of Object.entries(item.form || {})) {
if (typeof v === "string" && v.trim() === cleanQuery) {
if (k.endsWith("_code") || k.endsWith("_flowCode") || k.endsWith("_linkId") || k.endsWith("_detailId")) {
return true;
}
}
}
return false;
});
return matched.map((it) => formatSingleBill(it, dictionary));
}
// ── 业务操作:多条件搜索与分页单据 ─────────────────────────────────────────────
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,
});
let filtered = searchRes.items;
// 客户端辅助精确过滤
if (params.code) {
const target = params.code.trim();
filtered = filtered.filter((it) => {
if (it.code === target) return true;
for (const [k, v] of Object.entries(it.form || {})) {
if (k.endsWith("_code") && v === target) return true;
if (k.endsWith("_flowCode") && v === target) return true;
}
return false;
});
}
if (params.id) {
const target = params.id.trim();
filtered = filtered.filter((it) => it.id === target);
}
if (params.stage) {
const target = params.stage.trim().toLowerCase();
filtered = filtered.filter((it) => {
for (const [k, v] of Object.entries(it.form || {})) {
if (k.endsWith("_stage") && String(v).toLowerCase() === target) return true;
}
return false;
});
}
if (params.state) {
const target = params.state.trim().toLowerCase();
filtered = filtered.filter((it) => {
for (const [k, v] of Object.entries(it.form || {})) {
if (k.endsWith("_state") && String(v).toLowerCase() === target) return true;
}
return false;
});
}
if (params.keyword) {
const kw = params.keyword.trim().toLowerCase();
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;
}
return false;
});
}
const formattedItems = filtered.map((it) => formatSingleBill(it, dictionary));
return {
total: searchRes.count,
returned: formattedItems.length,
items: formattedItems,
};
}
// ── MCP Tools 适配 ────────────────────────────────────────────────────────────
export const billTools = [
{
name: "bill_search",
description: "检索企业名下的费用单据、报销单、借款单与发票列表(已自动将字段代码还原为可读业务名称)",
parameters: z.object({
code: z.string().optional().describe("按单据编号/单号过滤(如 jO1it3cIufDjNS)"),
keyword: z.string().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("拉取记录数"),
}),
handler: async (
{ corpContext }: { corpContext: CorpContext },
params: { code?: string; keyword?: string; stage?: string; state?: string; count?: number }
) => {
const corp = corpContext.getCurrent();
if (!corp) {
throw new Error("未配置活跃企业上下文");
}
const client = await createEkbClient(corp);
const result = await searchAndFormatBills(client, corp.corpId || corp.id, params);
return {
corpId: corp.corpId || corp.id,
corpName: corp.name,
...result,
};
},
},
{
name: "bill_get",
description: "根据单据编号(单号)或单据 ID 精确查询单据详细信息与格式化表单明细",
parameters: z.object({
code: z.string().describe("单据编号(如 jO1it3cIufDjNS)或 单据 ID(如 ID01V0zDDjZNHp)"),
}),
handler: async (
{ corpContext }: { corpContext: CorpContext },
params: { code: string }
) => {
const corp = corpContext.getCurrent();
if (!corp) {
throw new Error("未配置活跃企业上下文");
}
const client = await createEkbClient(corp);
const bills = await getBillByCodeOrId(client, corp.corpId || corp.id, params.code);
if (bills.length === 0) {
return {
found: false,
message: `未找到单号或 ID 为 [${params.code}] 的单据`,
code: params.code,
};
}
return {
found: true,
count: bills.length,
bills,
};
},
},
{
name: "bill_schema",
description: "获取企业全部单据实体的数据模型、表单定义与中文字段 Label 字典",
parameters: z.object({}),
handler: async ({ corpContext }: { corpContext: CorpContext }) => {
const corp = corpContext.getCurrent();
if (!corp) {
throw new Error("未配置活跃企业上下文");
}
const client = await createEkbClient(corp);
const { entities } = await getFieldDictionary(client, corp.corpId || corp.id, true);
return {
corpId: corp.corpId || corp.id,
totalEntities: entities.length,
entities: entities.map((e) => ({
id: e.id,
name: e.name,
type: e.type,
fieldCount: e.fields.length,
fields: e.fields.map((f) => ({
name: f.name,
label: f.label,
type: f.type,
})),
})),
};
},
},
];
+105
View File
@@ -0,0 +1,105 @@
import { z } from "zod";
// ── 字段元数据(DataLink Field Meta)──────────────────────────────────────────
export const FieldMetaSchema = z.object({
name: z.string(),
type: z.string().default("text"),
label: z.string().default(""),
regex: z.string().optional().default(""),
source: z.string().optional().default("dataLink"),
formula: z.boolean().optional().default(false),
optional: z.boolean().optional().default(true),
calculation: z.record(z.string(), z.any()).optional(),
});
export const EntitySchema = z.object({
id: z.string(),
code: z.string().optional().default(""),
name: z.string().default(""),
type: z.string().default(""),
active: z.boolean().default(true),
fields: z.array(FieldMetaSchema).default([]),
});
export const EntityListResponseSchema = z.object({
items: z.array(EntitySchema).default([]),
});
// ── 原始单据条目(Raw Bill Item from /api/v2/invoice/search)─────────────────────
export const RawBillMoneySchema = z.object({
standard: z.string().or(z.number()).transform((v) => String(v)),
standardUnit: z.string().optional().default("元"),
standardScale: z.number().optional().default(2),
standardSymbol: z.string().optional().default("¥"),
standardNumCode: z.string().optional().default("156"),
standardStrCode: z.string().optional().default("CNY"),
});
export const RawBillItemSchema = z.object({
id: z.string(),
code: z.string().default(""),
name: z.string().default(""),
entityId: z.string().optional().default(""),
active: z.boolean().optional().default(true),
ownerId: z.string().optional().default(""),
corporationId: z.string().optional().default(""),
createTime: z.number().default(0),
updateTime: z.number().default(0),
form: z.record(z.string(), z.any()).default({}),
});
export const RawBillSearchResponseSchema = z.object({
count: z.number().default(0),
items: z.array(RawBillItemSchema).default([]),
});
export const RawBillBatchGetResponseSchema = z.object({
items: z.array(RawBillItemSchema).default([]),
});
// ── 格式化后的单据输出(Formatted Bill)───────────────────────────────────────
export const FormattedBillSchema = z.object({
billId: z.string(),
billCode: z.string(),
billName: z.string(),
title: z.string().optional(),
stage: z.string().optional(),
state: z.string().optional(),
amount: z.string().optional(),
submitterId: z.string().optional(),
submitDate: z.string().optional(),
corporationId: z.string(),
ownerId: z.string().optional(),
createTime: z.string(),
updateTime: z.string(),
details: z.record(z.string(), z.any()),
});
export const BillPageResultSchema = z.object({
total: z.number(),
returned: z.number(),
items: z.array(FormattedBillSchema),
});
// ── 类型导出 ──────────────────────────────────────────────────────────────────
export type FieldMeta = z.infer<typeof FieldMetaSchema>;
export type EntityMeta = z.infer<typeof EntitySchema>;
export type RawBillMoney = z.infer<typeof RawBillMoneySchema>;
export type RawBillItem = z.infer<typeof RawBillItemSchema>;
export type RawBillSearchResponse = z.infer<typeof RawBillSearchResponseSchema>;
export type FormattedBill = z.infer<typeof FormattedBillSchema>;
export type BillPageResult = z.infer<typeof BillPageResultSchema>;
export interface BillQueryParams {
code?: string;
id?: string;
keyword?: string;
stage?: string;
state?: string;
start?: number;
count?: number;
}
+14
View File
@@ -0,0 +1,14 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { StaffSchema, type Staff } from "./types.js";
export async function fetchStaffs(
client: KyInstance,
external: boolean = false
): Promise<Staff[]> {
const response = await client.get("api/easo/common/staffs", {
searchParams: { external: String(external) },
});
const json = (await response.json()) as { data: unknown };
return z.array(StaffSchema).parse(json.data ?? []);
}
+52
View File
@@ -0,0 +1,52 @@
import { describe, expect, test } from "bun:test";
import { StaffSchema, type Staff } from "./types.js";
describe("Contact Domain - 通讯录与人员模型", () => {
test("StaffSchema 正确解析包含 null 字段的员工对象", () => {
const raw = {
id: "corp123:staff456",
name: "测试员工",
email: null,
cellphone: null,
department: null,
};
const parsed = StaffSchema.parse(raw);
expect(parsed.id).toBe("corp123:staff456");
expect(parsed.name).toBe("测试员工");
expect(parsed.email).toBeNull();
});
test("StaffSchema 正确解析完整员工信息", () => {
const raw = {
id: "corp123:staff456",
name: "张三",
email: "zhangsan@example.com",
cellphone: "13800138000",
department: "研发部",
};
const parsed = StaffSchema.parse(raw);
expect(parsed.name).toBe("张三");
expect(parsed.email).toBe("zhangsan@example.com");
expect(parsed.cellphone).toBe("13800138000");
expect(parsed.department).toBe("研发部");
});
test("模糊搜索与过滤逻辑可正确按姓名、邮箱、工号匹配", () => {
const list: Staff[] = [
{ id: "corp:001", name: "王硕", email: "wangshuo@test.com", cellphone: "13911112222" },
{ id: "corp:002", name: "李雨笑", email: "liyuxiao@test.com", cellphone: null },
{ id: "corp:003", name: "谢子豪", email: "xiezihao@test.com", cellphone: "13933334444" },
];
const search = (kw: string) => {
const q = kw.toLowerCase();
return list.filter((s) => s.name.includes(q) || (s.email && s.email.includes(q)) || s.id.includes(q));
};
expect(search("王硕").length).toBe(1);
expect(search("wangshuo").length).toBe(1);
expect(search("003").length).toBe(1);
expect(search("003")[0].name).toBe("谢子豪");
expect(search("不存在").length).toBe(0);
});
});
+111
View File
@@ -0,0 +1,111 @@
import { z } from "zod";
import { getEasoClient } from "../../core/auth/easo.js";
import type { CorpConfig } from "../../core/config/types.js";
import { fetchStaffs } from "./api.js";
import type { ContactListResult, ContactSearchOptions, Staff } from "./types.js";
export const DEFAULT_STAFF_LIST_LIMIT = 20;
export async function listStaffsProtected(
corp: CorpConfig,
options: ContactSearchOptions = {}
): Promise<ContactListResult> {
const { client } = await getEasoClient(corp);
const allStaffs = await fetchStaffs(client, options.external ?? false);
const total = allStaffs.length;
const isFull = options.allowFull === true;
const limit = isFull ? total : options.limit ?? DEFAULT_STAFF_LIST_LIMIT;
const staffs = allStaffs.slice(0, limit);
const hasMore = total > staffs.length;
return {
total,
limit,
hasMore,
hint: hasMore
? `企业员工共 ${total} 人,当前仅展示前 ${staffs.length} 条以防止上下文溢出。可使用 'hose contact search <姓名|工号>' 精准检索,或附加 '--limit <数量>' / '-o <文件路径>' / '--full'`
: undefined,
staffs,
};
}
export async function searchStaffs(
corp: CorpConfig,
options: { keyword: string; limit?: number; external?: boolean }
): Promise<Staff[]> {
const { client } = await getEasoClient(corp);
const allStaffs = await fetchStaffs(client, options.external ?? false);
const kw = options.keyword.trim().toLowerCase();
if (!kw) {
return allStaffs.slice(0, options.limit ?? DEFAULT_STAFF_LIST_LIMIT);
}
const matched = allStaffs.filter((s) => {
const name = s.name?.toLowerCase() || "";
const email = s.email?.toLowerCase() || "";
const phone = s.cellphone || "";
const id = s.id?.toLowerCase() || "";
return name.includes(kw) || email.includes(kw) || phone.includes(kw) || id.includes(kw);
});
return matched.slice(0, options.limit ?? 50);
}
export async function getStaffById(
corp: CorpConfig,
staffId: string
): Promise<Staff | null> {
const { client } = await getEasoClient(corp);
const allStaffs = await fetchStaffs(client, false);
const cleanId = staffId.trim();
const found = allStaffs.find(
(s) => s.id === cleanId || s.id.endsWith(`:${cleanId}`) || s.id.split(":")[1] === cleanId
);
return found || null;
}
// ── MCP Tool Definitions ──────────────────────────────────────────────────────
export const contactTools = [
{
name: "contact_search",
description: "在当前企业通讯录中模糊检索员工(支持姓名、邮箱、手机号、工号)",
parameters: z.object({
keyword: z.string().describe("检索关键词,如姓名、邮箱前缀、手机号或工号"),
limit: z.number().optional().describe("最大返回条数,默认 20"),
}),
handler: async (corp: CorpConfig, params: { keyword: string; limit?: number }) => {
const results = await searchStaffs(corp, params);
return { count: results.length, staffs: results };
},
},
{
name: "contact_get",
description: "根据员工 staffId 或工号精准获取员工详细档案",
parameters: z.object({
staffId: z.string().describe("员工的完整 staffId 或 ID"),
}),
handler: async (corp: CorpConfig, params: { staffId: string }) => {
const staff = await getStaffById(corp, params.staffId);
if (!staff) {
throw new Error(`未找到员工: ${params.staffId}`);
}
return staff;
},
},
{
name: "contact_list",
description: "查看企业通讯录(带默认 20 条防爆截断与总数保护)",
parameters: z.object({
limit: z.number().optional().describe("截断返回条数,默认 20"),
allowFull: z.boolean().optional().describe("是否强制全量输出(大企业请谨慎使用)"),
}),
handler: async (corp: CorpConfig, params: { limit?: number; allowFull?: boolean }) => {
return await listStaffsProtected(corp, params);
},
},
];
+26
View File
@@ -0,0 +1,26 @@
import { z } from "zod";
export const StaffSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().nullable().optional(),
cellphone: z.string().nullable().optional(),
department: z.string().nullable().optional(),
});
export type Staff = z.infer<typeof StaffSchema>;
export interface ContactListResult {
total: number;
limit: number;
hasMore: boolean;
hint?: string;
staffs: Staff[];
}
export interface ContactSearchOptions {
keyword?: string;
limit?: number;
allowFull?: boolean;
external?: boolean;
}
+29
View File
@@ -0,0 +1,29 @@
import { VERSION } from "../version.js";
export function renderDocsHtml(): string {
return `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<title>hose-use API Reference (v${VERSION})</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⚡</text></svg>" />
<style>
body {
margin: 0;
padding: 0;
background-color: #0f172a;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
</style>
</head>
<body>
<script
id="api-reference"
data-url="/openapi.json"
data-configuration='{"theme":"purple","layout":"modern","showSidebar":true}'
src="https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.25.101/dist/browser/standalone.js"
></script>
</body>
</html>`;
}
+180
View File
@@ -0,0 +1,180 @@
import type { IncomingMessage, ServerResponse } from "node:http";
import { URL } from "node:url";
import { runCli } from "../cli/runner.js";
import { loadCorpConfigs, loadGlobalConfig } from "../core/config/loader.js";
import { getOpenApiSchema } from "../core/embedded-openapi.js";
import { tokenizeCommand, normalizeCliArgs } from "../server.js";
import { VERSION } from "../version.js";
import { renderDocsHtml } from "./docs.js";
export async function handleHttpRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
// 1. CORS headers
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Hose-Corp");
if (req.method === "OPTIONS") {
res.writeHead(204);
res.end();
return;
}
const host = req.headers.host || "localhost";
const protocol = req.headers["x-forwarded-proto"] || "http";
const url = new URL(req.url || "/", `${protocol}://${host}`);
const pathname = url.pathname.replace(/\/+$/, "") || "/";
const method = (req.method || "GET").toUpperCase();
try {
// 2. Metadata & Health
if (method === "GET" && pathname === "/") {
sendJson(res, 200, {
name: "hose-use",
version: VERSION,
description: "合思/易快报企业级 CLI 工具与底层 SDK HTTP 服务",
docs: "/docs",
openapi: "/openapi.json",
rawOpenapi: "/raw-openapi.json",
health: "/health",
endpoints: {
cli: "POST /api/cli",
corps: "GET /v1/corps",
},
});
return;
}
if (method === "GET" && pathname === "/health") {
sendJson(res, 200, {
status: "ok",
name: "hose-use",
version: VERSION,
timestamp: new Date().toISOString(),
});
return;
}
if (method === "GET" && pathname === "/docs") {
sendHtml(res, 200, renderDocsHtml());
return;
}
if (method === "GET" && pathname === "/openapi.json") {
sendJson(res, 200, getOpenApiSchema("wrapped"));
return;
}
if (method === "GET" && pathname === "/raw-openapi.json") {
sendJson(res, 200, getOpenApiSchema("raw"));
return;
}
// 3. Command Execution Endpoint: POST /api/cli
if (method === "POST" && pathname === "/api/cli") {
const body = (await parseJsonBody(req)) as Record<string, unknown> | null;
const command = (typeof body?.command === "string" ? body.command : "").trim();
if (!command) {
sendError(res, 400, "Missing 'command' property in request body");
return;
}
const tokens = tokenizeCommand(command);
const cliArgs = normalizeCliArgs(tokens);
const result = await runCli(cliArgs);
let parsedData: unknown = undefined;
const trimmedStdout = result.stdout.trim();
try {
if (trimmedStdout.startsWith("{") || trimmedStdout.startsWith("[")) {
parsedData = JSON.parse(trimmedStdout);
}
} catch {
// keep string
}
sendJson(res, result.exitCode === 0 ? 200 : 400, {
success: result.exitCode === 0,
stdout: result.stdout,
stderr: result.stderr,
exitCode: result.exitCode,
...(parsedData !== undefined ? { data: parsedData } : {}),
});
return;
}
// 4. RESTful: GET /v1/corps
if (method === "GET" && pathname === "/v1/corps") {
const configs = loadCorpConfigs();
const globalConfig = loadGlobalConfig();
sendJson(res, 200, {
count: configs.length,
mode: globalConfig.stateful ? "stateful" : "stateless",
defaultCorpId: globalConfig.defaultCorpId,
corps: configs.map((c) => ({
id: c.id,
name: c.name,
source: c.source,
staffId: c.credentials.staffId,
baseUrl: c.baseUrl,
expiresAt: c.auth?.expiresAt || c.session?.expTime,
})),
});
return;
}
sendError(res, 404, `Cannot ${method} ${pathname}. Visit /docs for available endpoints.`);
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
sendError(res, 500, message);
}
}
function sendJson(res: ServerResponse, status: number, data: unknown): void {
if (res.headersSent) return;
const payload = JSON.stringify(data, null, 2);
res.writeHead(status, {
"Content-Type": "application/json; charset=utf-8",
"Content-Length": Buffer.byteLength(payload, "utf-8"),
});
res.end(payload);
}
function sendHtml(res: ServerResponse, status: number, html: string): void {
if (res.headersSent) return;
res.writeHead(status, {
"Content-Type": "text/html; charset=utf-8",
"Content-Length": Buffer.byteLength(html, "utf-8"),
});
res.end(html);
}
function sendError(res: ServerResponse, status: number, message: string): void {
sendJson(res, status, { error: true, message });
}
async function parseJsonBody(req: IncomingMessage): Promise<unknown> {
return new Promise((resolve, reject) => {
let raw = "";
req.on("data", (chunk) => {
raw += chunk;
if (raw.length > 5 * 1024 * 1024) {
// 5MB max payload
reject(new Error("Request payload too large (max 5MB)"));
}
});
req.on("end", () => {
if (!raw.trim()) {
resolve(null);
return;
}
try {
resolve(JSON.parse(raw));
} catch (err) {
reject(new Error(`Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`));
}
});
req.on("error", (err) => {
reject(err);
});
});
}
+96
View File
@@ -0,0 +1,96 @@
import { describe, expect, test, afterAll, beforeAll } from "bun:test";
import type { Server } from "node:http";
import { startHttpServer } from "./server.js";
import { VERSION } from "../version.js";
describe("HTTP Server - 嵌入式服务与 REST 网关", () => {
let server: Server;
const testPort = 18888;
const baseUrl = `http://127.0.0.1:${testPort}`;
beforeAll(async () => {
server = await startHttpServer({ port: testPort, host: "127.0.0.1", silent: true });
});
afterAll(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
});
test("GET / 返回服务概览与 CORS 标头", async () => {
const res = await fetch(`${baseUrl}/`);
expect(res.status).toBe(200);
expect(res.headers.get("access-control-allow-origin")).toBe("*");
const json = (await res.json()) as any;
expect(json.name).toBe("hose-use");
expect(json.version).toBe(VERSION);
expect(json.docs).toBe("/docs");
expect(json.openapi).toBe("/openapi.json");
expect(json.health).toBe("/health");
expect(json.endpoints.cli).toBe("POST /api/cli");
});
test("GET /health 返回存活探针状态", async () => {
const res = await fetch(`${baseUrl}/health`);
expect(res.status).toBe(200);
const json = (await res.json()) as any;
expect(json.status).toBe("ok");
expect(json.name).toBe("hose-use");
expect(json.version).toBe(VERSION);
expect(json.timestamp).toBeDefined();
});
test("GET /openapi.json 返回标准包装层 OpenAPI 规范", async () => {
const res = await fetch(`${baseUrl}/openapi.json`);
expect(res.status).toBe(200);
const json = (await res.json()) as any;
expect(json.openapi).toBe("3.1.0");
expect(json.info.title).toContain("hose-use");
});
test("GET /raw-openapi.json 返回原生下游 OpenAPI 规范", async () => {
const res = await fetch(`${baseUrl}/raw-openapi.json`);
expect(res.status).toBe(200);
const json = (await res.json()) as any;
expect(json.openapi).toBe("3.1.0");
expect(json.info.title).toContain("Downstream");
});
test("GET /docs 返回 Scalar 交互式文档 HTML 页面", async () => {
const res = await fetch(`${baseUrl}/docs`);
expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toContain("text/html");
const html = await res.text();
expect(html).toContain("<html");
expect(html).toContain("api-reference");
expect(html).toContain("data-url=\"/openapi.json\"");
});
test("POST /api/cli 允许同进程执行 CLI 指令", async () => {
const res = await fetch(`${baseUrl}/api/cli`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ command: "version" }),
});
expect(res.status).toBe(200);
const json = (await res.json()) as any;
expect(json.success).toBe(true);
expect(json.exitCode).toBe(0);
expect(json.stdout).toContain(`hose-use v${VERSION}`);
});
test("GET /v1/corps 返回企业列表与运行模式", async () => {
const res = await fetch(`${baseUrl}/v1/corps`);
expect(res.status).toBe(200);
const json = (await res.json()) as any;
expect(json).toHaveProperty("count");
expect(json).toHaveProperty("mode");
expect(Array.isArray(json.corps)).toBe(true);
});
test("OPTIONS /v1/corps 处理 CORS 跨域预检", async () => {
const res = await fetch(`${baseUrl}/v1/corps`, { method: "OPTIONS" });
expect(res.status).toBe(204);
expect(res.headers.get("access-control-allow-methods")).toContain("GET");
expect(res.headers.get("access-control-allow-origin")).toBe("*");
});
});
+46
View File
@@ -0,0 +1,46 @@
import { createServer, type Server } from "node:http";
import { handleHttpRequest } from "./routes.js";
import { VERSION } from "../version.js";
export type HttpServerOptions = {
port?: number;
host?: string;
silent?: boolean;
};
export const DEFAULT_HTTP_PORT = 8888;
export const DEFAULT_HTTP_HOST = "127.0.0.1";
export async function startHttpServer(options: HttpServerOptions = {}): Promise<Server> {
const port = options.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
const host = options.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
const server = createServer(async (req, res) => {
try {
await handleHttpRequest(req, res);
} catch (err) {
if (!res.headersSent) {
res.writeHead(500, { "Content-Type": "application/json; charset=utf-8" });
res.end(JSON.stringify({ error: true, message: err instanceof Error ? err.message : String(err) }));
}
}
});
return new Promise((resolve, reject) => {
server.on("error", (err) => {
reject(err);
});
server.listen(port, host, () => {
if (!options.silent) {
console.error(`\n⚡ hose-use HTTP Server (v${VERSION}) 已启动`);
console.error(` 主服务地址: http://${host}:${port}`);
console.error(` 交互式文档: http://${host}:${port}/docs`);
console.error(` OpenAPI规范: http://${host}:${port}/openapi.json`);
console.error(` CLI执行网关: POST http://${host}:${port}/api/cli`);
console.error(` 企业列表接口: GET http://${host}:${port}/v1/corps\n`);
}
resolve(server);
});
});
}
+182
View File
@@ -0,0 +1,182 @@
import { describe, expect, test } from "bun:test";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import {
createServer,
resolveMcpMode,
HOSE_CLI_TOOL_NAME,
HOSE_MCP_MODE_ENV,
tokenizeCommand,
normalizeCliArgs,
} from "./server.js";
import { VERSION } from "./version.js";
describe("hose-use MCP server & hose_cli single-gate pattern", () => {
test("tokenizes complex CLI arguments with quotes and JSON payloads", () => {
expect(
tokenizeCommand(`hose-use bill query --code "BX20260901001" --corp ID01MCcOgJl1td`)
).toEqual([
"hose-use",
"bill",
"query",
"--code",
"BX20260901001",
"--corp",
"ID01MCcOgJl1td",
]);
expect(
tokenizeCommand(`hose auth import --raw 'curl "https://app.ekuaibao.com/api?corpId=123" -H "accessToken: abc"'`)
).toEqual([
"hose",
"auth",
"import",
"--raw",
`curl "https://app.ekuaibao.com/api?corpId=123" -H "accessToken: abc"`,
]);
});
test("normalizes CLI prefix binary names", () => {
expect(normalizeCliArgs(["hose-use", "version"])).toEqual(["version"]);
expect(normalizeCliArgs(["hose", "corps", "list"])).toEqual(["corps", "list"]);
expect(normalizeCliArgs(["/usr/local/bin/hose", "probe"])).toEqual(["probe"]);
expect(normalizeCliArgs(["corps", "current"])).toEqual(["corps", "current"]);
});
test("resolves HOSE_MCP_MODE from environment variable", () => {
const original = process.env[HOSE_MCP_MODE_ENV];
delete process.env[HOSE_MCP_MODE_ENV];
try {
expect(resolveMcpMode()).toBe("single");
expect(resolveMcpMode("single")).toBe("single");
expect(resolveMcpMode("all")).toBe("all");
expect(resolveMcpMode("both")).toBe("all");
expect(resolveMcpMode("legacy")).toBe("legacy");
} finally {
if (original === undefined) delete process.env[HOSE_MCP_MODE_ENV];
else process.env[HOSE_MCP_MODE_ENV] = original;
}
});
test("advertises only hose_cli in single mode and executes commands in-process", async () => {
const server = createServer({ mode: "single" });
const client = new Client({ name: "hose-use-test-client", version: "1.0.0" });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
try {
await Promise.all([
server.connect(serverTransport),
client.connect(clientTransport),
]);
const listed = await client.listTools();
expect(listed.tools).toHaveLength(1);
expect(listed.tools[0]?.name).toBe(HOSE_CLI_TOOL_NAME);
expect(listed.tools[0]?.inputSchema).toMatchObject({
type: "object",
required: ["command"],
});
// Execute 'version'
const versionResult = await client.callTool({
name: HOSE_CLI_TOOL_NAME,
arguments: { command: "hose-use version" },
});
expect(versionResult.isError).not.toBe(true);
const content = versionResult.content as Array<{ type: "text"; text: string }>;
expect(content[0]?.text).toContain(`hose-use v${VERSION}`);
// Execute 'corps list'
const corpsResult = await client.callTool({
name: HOSE_CLI_TOOL_NAME,
arguments: { command: "corps list" },
});
expect(corpsResult.isError).not.toBe(true);
const corpsContent = corpsResult.content as Array<{ type: "text"; text: string }>;
const text = corpsContent[0]?.text || "";
expect(text.includes("已配置企业列表") || text.includes("未找到任何企业配置")).toBe(true);
// Execute invalid command
const invalidResult = await client.callTool({
name: HOSE_CLI_TOOL_NAME,
arguments: { command: "not-a-real-command-xyz" },
});
expect(invalidResult.isError).toBe(true);
const errContent = invalidResult.content as Array<{ type: "text"; text: string }>;
expect(errContent[0]?.text).toContain("未知命令域");
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
test("advertises both hose_cli and fine-grained tools in all mode", async () => {
const server = createServer({ mode: "all" });
const client = new Client({ name: "hose-use-test-all", version: "1.0.0" });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
try {
await Promise.all([
server.connect(serverTransport),
client.connect(clientTransport),
]);
const listed = await client.listTools();
const toolNames = listed.tools.map((t) => t.name);
expect(toolNames).toContain(HOSE_CLI_TOOL_NAME);
expect(toolNames).toContain("bill_search");
expect(toolNames).toContain("list_corps");
expect(toolNames).toContain("platform_workflow_list_all");
expect(toolNames.length).toBeGreaterThan(5);
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
test("advertises only fine-grained tools in legacy mode", async () => {
const server = createServer({ mode: "legacy" });
const client = new Client({ name: "hose-use-test-legacy", version: "1.0.0" });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
try {
await Promise.all([
server.connect(serverTransport),
client.connect(clientTransport),
]);
const listed = await client.listTools();
const toolNames = listed.tools.map((t) => t.name);
expect(toolNames).not.toContain(HOSE_CLI_TOOL_NAME);
expect(toolNames).toContain("bill_search");
expect(toolNames).toContain("list_corps");
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
test("returns empty tools when MCP is disabled via configuration", async () => {
const server = createServer({ enabled: false });
const client = new Client({ name: "hose-use-test-disabled", version: "1.0.0" });
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
try {
await Promise.all([
server.connect(serverTransport),
client.connect(clientTransport),
]);
const listed = await client.listTools();
expect(listed.tools).toEqual([]);
const callResult = await client.callTool({
name: HOSE_CLI_TOOL_NAME,
arguments: { command: "version" },
});
expect(callResult.isError).toBe(true);
const content = callResult.content as Array<{ type: "text"; text: string }>;
expect(content[0]?.text).toContain("HOSE_USE_MCP_ENABLED=false");
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
});
+267 -25
View File
@@ -5,6 +5,8 @@ import {
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { loadCorpConfigs } from "./core/config/loader.js";
import { CorpContext } from "./core/config/manager.js";
import { createEkbClient } from "./core/auth/ekb.js";
@@ -12,6 +14,126 @@ import { getEasoClient } from "./core/auth/easo.js";
import { AuthenticationError, EkbError, NotLoggedInError } from "./core/errors.js";
import { authTools } from "./core/auth/tools.js";
import { platformTools } from "./domains/platform/tools.js";
import { billTools } from "./domains/bill/tools.js";
import { runCli } from "./cli/runner.js";
import { redactSensitiveText } from "./cli/printer.js";
import { VERSION } from "./version.js";
import type { CliResult } from "./cli/types.js";
export const HOSE_CLI_TOOL_NAME = "hose_cli";
export const HOSE_MCP_MODE_ENV = "HOSE_MCP_MODE"; // "single" | "all" | "legacy"
export const HOSE_MCP_ENABLED_ENV = "HOSE_USE_MCP_ENABLED";
export type HoseMcpMode = "single" | "all" | "legacy";
const serverEntryFile = fileURLToPath(import.meta.url);
const appRoot = serverEntryFile.includes("/dist/mcp/") || serverEntryFile.includes("\\dist\\mcp\\")
? dirname(dirname(dirname(serverEntryFile)))
: dirname(dirname(serverEntryFile));
export function resolveMcpEnabled(value = process.env[HOSE_MCP_ENABLED_ENV]): boolean {
if (value === undefined) return true;
return ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
}
export function resolveMcpMode(value = process.env[HOSE_MCP_MODE_ENV]): HoseMcpMode {
if (!value) return "single";
const normalized = value.trim().toLowerCase();
if (normalized === "all" || normalized === "both" || normalized === "full") return "all";
if (normalized === "legacy" || normalized === "multi") return "legacy";
return "single";
}
export function tokenizeCommand(command: string): string[] {
const tokens: string[] = [];
let token = "";
let quote: "'" | '"' | undefined;
let escaped = false;
let tokenStarted = false;
for (const character of command) {
if (escaped) {
token += character;
escaped = false;
tokenStarted = true;
continue;
}
if (character === "\\" && quote !== "'") {
escaped = true;
tokenStarted = true;
continue;
}
if (quote) {
if (character === quote) {
quote = undefined;
} else {
token += character;
}
tokenStarted = true;
continue;
}
if (character === "'" || character === '"') {
quote = character;
tokenStarted = true;
continue;
}
if (/\s/.test(character)) {
if (tokenStarted) {
tokens.push(token);
token = "";
tokenStarted = false;
}
continue;
}
token += character;
tokenStarted = true;
}
if (escaped) throw new Error("Invalid command: trailing escape");
if (quote) throw new Error("Invalid command: unterminated quote");
if (tokenStarted) tokens.push(token);
return tokens;
}
export function normalizeCliArgs(tokens: string[]): string[] {
const first = tokens[0];
if (!first) return [];
const lower = first.toLowerCase().replace(/\\/g, "/");
if (
lower === "hose-use" ||
lower === "hose" ||
lower.endsWith("/hose-use") ||
lower.endsWith("/hose") ||
lower.endsWith("/hose-use.exe") ||
lower.endsWith("/hose.exe")
) {
return tokens.slice(1);
}
return tokens;
}
export function cliResult(result: CliResult): {
content: Array<{ type: "text"; text: string }>;
isError: boolean;
} {
const isError = result.exitCode !== 0;
let text = isError ? (result.stderr || result.stdout || "Command failed") : (result.stdout || result.stderr || "Success");
text = redactSensitiveText(text);
return {
content: [
{
type: "text",
text: text.trimEnd(),
},
],
isError,
};
}
function formatError(error: unknown): {
content: Array<{ type: "text"; text: string }>;
@@ -45,22 +167,20 @@ function formatError(error: unknown): {
};
}
console.error(error);
return {
content: [{ type: "text", text: error instanceof Error ? error.message : "发生内部错误,请稍后重试" }],
isError: true,
};
}
async function main() {
// 加载企业配置
const corps = loadCorpConfigs();
const corpContext = new CorpContext(corps);
export function createServer(options: { mode?: HoseMcpMode; enabled?: boolean } = {}) {
const enabled = options.enabled ?? resolveMcpEnabled();
const mode = options.mode ?? resolveMcpMode();
const server = new Server(
{
name: "ekb-mcp",
version: "0.1.0",
name: "hose-use",
version: VERSION,
},
{
capabilities: {
@@ -69,26 +189,99 @@ async function main() {
}
);
// 聚合所有工具
const allTools = [...authTools, ...platformTools];
const fineGrainedTools = [...authTools, ...platformTools, ...billTools];
// 注册工具列表
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: allTools.map((t) => ({
name: t.name,
description: t.description,
inputSchema: (t.parameters as any).toJSONSchema(),
})),
};
if (!enabled) {
return { tools: [] };
}
const tools: Array<{ name: string; description?: string; inputSchema: any }> = [];
// 单工具网关
if (mode === "single" || mode === "all") {
tools.push({
name: HOSE_CLI_TOOL_NAME,
description:
"Run hose-use CLI commands (e.g. 'bill query', 'corps list', 'workflow search'). See the hose-use skill for command reference.",
inputSchema: {
type: "object",
properties: {
command: {
type: "string",
description:
"A hose-use CLI command string, with or without the leading 'hose-use' or 'hose'. Example: 'corps list' or 'bill query --code BX20260901001'.",
},
},
required: ["command"],
additionalProperties: false,
},
});
}
// 细粒度工具(仅在 all 或 legacy 模式下保留)
if (mode === "all" || mode === "legacy") {
for (const t of fineGrainedTools) {
tools.push({
name: t.name,
description: t.description,
inputSchema: (t.parameters as any).toJSONSchema(),
});
}
}
return { tools };
});
// 处理工具调用
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (!enabled) {
return cliResult({
stdout: "",
stderr: "hose-use MCP 服务在插件配置中已被禁用 (HOSE_USE_MCP_ENABLED=false)",
exitCode: 1,
});
}
const { name, arguments: args } = request.params;
// 1. 处理 hose_cli 网关工具调用
if (name === HOSE_CLI_TOOL_NAME) {
const command = args && typeof args.command === "string" ? args.command : undefined;
if (!command?.trim()) {
return cliResult({
stdout: "",
stderr: "hose_cli requires a non-empty command string",
exitCode: 1,
});
}
try {
const tokens = tokenizeCommand(command);
const cliArgs = normalizeCliArgs(tokens);
if (!cliArgs.length) {
throw new Error("hose_cli requires a non-empty command string");
}
const result = await runCli(cliArgs, {
appRoot,
entryFile: serverEntryFile,
});
return cliResult(result);
} catch (error) {
return cliResult({
stdout: "",
stderr: error instanceof Error ? error.message : String(error),
exitCode: 1,
});
}
}
// 2. 处理细粒度工具兼容调用
try {
// 1. 检查 Auth 工具
const corps = loadCorpConfigs();
const corpContext = new CorpContext(corps);
// Auth 工具
const authTool = authTools.find((t) => t.name === name);
if (authTool) {
const parsed = authTool.parameters.safeParse(args || {});
@@ -109,21 +302,41 @@ async function main() {
};
}
// 2. 检查 Domain 业务工具(需要当前企业上下文)
// Bill 工具
const billTool = billTools.find((t) => t.name === name);
if (billTool) {
const parsed = billTool.parameters.safeParse(args || {});
if (!parsed.success) {
return {
content: [{ type: "text", text: `参数错误: ${parsed.error.message}` }],
isError: true,
};
}
const result = await billTool.handler({ corpContext }, parsed.data as never);
return {
content: [
{
type: "text",
text: typeof result === "string" ? result : JSON.stringify(result, null, 2),
},
],
};
}
// Platform 业务工具
const currentCorp = corpContext.getCurrent();
if (!currentCorp) {
return {
content: [
{
type: "text",
text: "未配置企业,请先调用 import_f12_corp 导入凭证,或执行 bun run login 登录",
text: "未配置企业,请先调用 auth login 登录或 auth import 导入凭证",
},
],
isError: true,
};
}
// Platform 工具
const platformTool = platformTools.find((t) => t.name === name);
if (platformTool) {
const parsed = platformTool.parameters.safeParse(args || {});
@@ -153,7 +366,7 @@ async function main() {
content: [
{
type: "text",
text: `未知工具: ${name}`,
text: `未知工具: ${name}。在单工具网关模式下,请通过 ${HOSE_CLI_TOOL_NAME} 调用。`,
},
],
isError: true,
@@ -163,9 +376,38 @@ async function main() {
}
});
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("EKB MCP Server running on stdio");
return server;
}
main().catch(console.error);
export async function startServer() {
const server = createServer();
const transport = new StdioServerTransport();
await server.connect(transport);
console.error(`hose-use MCP Server (v${VERSION}) running on stdio [mode: ${resolveMcpMode()}]`);
}
async function runEmbeddedCli() {
const result = await runCli(process.argv.slice(3), {
appRoot,
entryFile: serverEntryFile,
});
if (result.stdout) process.stdout.write(result.stdout);
if (result.stderr) process.stderr.write(`${result.stderr}${result.stderr.endsWith("\n") ? "" : "\n"}`);
process.exitCode = result.exitCode;
}
const isMainModule = Boolean(
(import.meta as any).main ||
(!import.meta.url.includes("$bunfs") && process.argv[1] && resolve(process.argv[1]) === resolve(serverEntryFile))
);
if (isMainModule) {
if (process.argv[2] === "--hose-use-cli" || process.argv[2] === "--hose-cli") {
await runEmbeddedCli();
} else {
startServer().catch((error) => {
console.error(error);
process.exitCode = 1;
});
}
}
+1 -1
View File
@@ -1 +1 @@
export const VERSION = "0.2.0";
export const VERSION = "0.5.2";
+1 -1
View File
@@ -12,7 +12,7 @@
"declaration": true,
"outDir": "./dist",
"rootDir": "./src",
"types": ["node"],
"types": ["node", "bun"],
"paths": {
"@core/*": ["./src/core/*"],
"@domains/*": ["./src/domains/*"]