Compare commits

..
1 Commits
Author SHA1 Message Date
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
22 changed files with 3912 additions and 187 deletions

No files matched your search

+2 -1
View File
@@ -3,7 +3,8 @@ node_modules
# output
out
dist
dist/bin/
dist/hose-use-*
*.tgz
# code coverage
+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.1",
"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
}
}
}
+8 -2
View File
@@ -1,4 +1,4 @@
# hose-use (v0.5.0)
# hose-use (v0.5.1)
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
@@ -78,10 +78,16 @@ hose-use mcp # 启动 MCP Server (默认暴露
`hose-use` 采用 **单工具网关架构 (Single-Gate Pattern)**。在 MCP 环境下默认仅暴露一个 `hose_cli` 工具,接收 `command` 字符串:
- 避免数十个业务工具占用大量 Prompt Tokens;
- 业务语义完全收敛在 `skills/hose-use/SKILL.md` 中,Agent 按需学习;
- 业务语义完全收敛在 `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
+611
View File
@@ -0,0 +1,611 @@
import{createRequire as XN}from"node:module";var uN=Object.create;var{getPrototypeOf:bN,defineProperty:K0,getOwnPropertyNames:IN}=Object;var UN=Object.prototype.hasOwnProperty;function DN($){return this[$]}var wN,WN,TJ=($,i,v)=>{var u=$!=null&&typeof $==="object";if(u){var n=i?wN??=new WeakMap:WN??=new WeakMap,b=n.get($);if(b)return b}v=$!=null?uN(bN($)):{};let I=i||!$||!$.__esModule?K0(v,"default",{value:$,enumerable:!0}):v;for(let U of IN($))if(!UN.call(I,U))K0(I,U,{get:DN.bind($,U),enumerable:!0});if(u)n.set($,I);return I};var S=($,i)=>()=>(i||$((i={exports:{}}).exports,i),i.exports);var gN=($)=>$;function JN($,i){this[$]=gN.bind(null,i)}var Gi=($,i)=>{for(var v in i)K0($,v,{get:i[v],enumerable:!0,configurable:!0,set:JN.bind(i,v)})};var EJ=XN(import.meta.url);var T4=S((WO)=>{Object.defineProperty(WO,"__esModule",{value:!0});WO.regexpCode=WO.getEsmExportName=WO.getProperty=WO.safeStringify=WO.stringify=WO.strConcat=WO.addCodeArg=WO.str=WO._=WO.nil=WO._Code=WO.Name=WO.IDENTIFIER=WO._CodeOrName=void 0;class jb{}WO._CodeOrName=jb;WO.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class wv extends jb{constructor($){super();if(!WO.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}}}WO.Name=wv;class ii extends jb{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 wv)i[v.str]=(i[v.str]||0)+1;return i},{})}}WO._Code=ii;WO.nil=new ii("");function DO($,...i){let v=[$[0]],u=0;while(u<i.length)lW(v,i[u]),v.push($[++u]);return new ii(v)}WO._=DO;var EW=new ii("+");function wO($,...i){let v=[k4($[0])],u=0;while(u<i.length)v.push(EW),lW(v,i[u]),v.push(EW,k4($[++u]));return T3(v),new ii(v)}WO.str=wO;function lW($,i){if(i instanceof ii)$.push(...i._items);else if(i instanceof wv)$.push(i);else $.push(t3(i))}WO.addCodeArg=lW;function T3($){let i=1;while(i<$.length-1){if($[i]===EW){let v=E3($[i-1],$[i+1]);if(v!==void 0){$.splice(i-1,3,v);continue}$[i++]="+"}i++}}function E3($,i){if(i==='""')return $;if($==='""')return i;if(typeof $=="string"){if(i instanceof wv||$[$.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 wv))return`"${$}${i.slice(1)}`;return}function l3($,i){return i.emptyStr()?$:$.emptyStr()?i:wO`${$}${i}`}WO.strConcat=l3;function t3($){return typeof $=="number"||typeof $=="boolean"||$===null?$:k4(Array.isArray($)?$.join(","):$)}function R3($){return new ii(k4($))}WO.stringify=R3;function k4($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}WO.safeStringify=k4;function C3($){return typeof $=="string"&&WO.IDENTIFIER.test($)?new ii(`.${$}`):DO`[${$}]`}WO.getProperty=C3;function _3($){if(typeof $=="string"&&WO.IDENTIFIER.test($))return new ii(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}WO.getEsmExportName=_3;function r3($){return new ii($.toString())}WO.regexpCode=r3});var _W=S((OO)=>{Object.defineProperty(OO,"__esModule",{value:!0});OO.ValueScope=OO.ValueScopeName=OO.Scope=OO.varKinds=OO.UsedValueState=void 0;var R$=T4();class JO extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var Qb;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(Qb||(OO.UsedValueState=Qb={}));OO.varKinds={const:new R$.Name("const"),let:new R$.Name("let"),var:new R$.Name("var")};class RW{constructor({prefixes:$,parent:i}={}){this._names={},this._prefixes=$,this._parent=i}toName($){return $ instanceof R$.Name?$:this.name($)}name($){return new R$.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}}}OO.Scope=RW;class CW extends R$.Name{constructor($,i){super(i);this.prefix=$}setValue($,{property:i,itemIndex:v}){this.value=$,this.scopePath=R$._`.${new R$.Name(i)}[${v}]`}}OO.ValueScopeName=CW;var $z=R$._`\n`;class XO extends RW{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?$z:R$.nil}}get(){return this._scope}name($){return new CW($,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 zO]}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 jO($,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 xW($,i,v))}add($,i){return this._leafNode(new GO($,C$.operators.ADD,i))}code($){if(typeof $=="function")$();else if($!==o.nil)this._leafNode(new LO($));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,o.addCodeArg)(i,u)}return i.push("}"),new o._Code(i)}if($,i,v){if(this._blockNode(new zi($)),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 zi($))}else(){return this._elseNode(new E4)}endIf(){return this._endBlockNode(zi,E4)}_for($,i){if(this._blockNode($),i)this.code(i).endFor();return this}for($,i){return this._for(new KO($),i)}forRange($,i,v,u,n=this.opts.es5?ni.varKinds.var:ni.varKinds.let){let b=this._scope.toName($);return this._for(new HO(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 o.Name?i:this.var("_arr",i);return this.forRange("_i",0,o._`${b}.length`,(I)=>{this.var(n,o._`${b}[${I}]`),v(n)})}return this._for(new rW("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($,o._`Object.keys(${i})`,v);let n=this._scope.toName($);return this._for(new rW("in",u,n,i),()=>v(n))}endFor(){return this._endBlockNode(Wv)}label($){return this._leafNode(new QO($))}break($){return this._leafNode(new YO($))}return($){let i=new Nb;if(this._blockNode(i),this.code($),i.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(Nb)}try($,i,v){if(!i&&!v)throw Error('CodeGen: "try" without "catch" and "finally"');let u=new PO;if(this._blockNode(u),this.code($),i){let n=this.name("e");this._currNode=u.catch=new Lb(n),i(n)}if(v)this._currNode=u.finally=new zb,this.code(v);return this._endBlockNode(Lb,zb)}throw($){return this._leafNode(new NO($))}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=o.nil,v,u){if(this._blockNode(new Yb($,i,v)),u)this.code(u).endFunc();return this}endFunc(){return this._endBlockNode(Yb)}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 zi))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]=$}}C$.CodeGen=FO;function Wn($,i){for(let v in i)$[v]=($[v]||0)+(i[v]||0);return $}function Kb($,i){return i instanceof o._CodeOrName?Wn($,i.names):$}function gv($,i,v){if($ instanceof o.Name)return u($);if(!n($))return $;return new o._Code($._items.reduce((b,I)=>{if(I instanceof o.Name)I=u(I);if(I instanceof o._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 o._Code&&b._items.some((I)=>I instanceof o.Name&&i[I.str]===1&&v[I.str]!==void 0)}}function uz($,i){for(let v in i)$[v]=($[v]||0)-(i[v]||0)}function BO($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:o._`!${fW($)}`}C$.not=BO;var bz=SO(C$.operators.AND);function Iz(...$){return $.reduce(bz)}C$.and=Iz;var Uz=SO(C$.operators.OR);function Dz(...$){return $.reduce(Uz)}C$.or=Dz;function SO($){return(i,v)=>i===o.nil?v:v===o.nil?i:o._`${fW(i)} ${$} ${fW(v)}`}function fW($){return $ instanceof o.Name?$:o._`(${$})`}});var d=S((tO)=>{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 LK({gen:$,parentData:i,parentDataProperty:v},u){$.if(x._`${i} !== undefined`,()=>$.assign(x._`${i}[${v}]`,u))}function pW($,i,v,u=Jv.Correct){let n=u===Jv.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===Jv.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)}}uA.checkDataType=pW;function aW($,i,v,u){if($.length===1)return pW($[0],i,v,u);let n,b=(0,iA.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,pW(I,i,v,u));return n}uA.checkDataTypes=aW;var zK={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:i})=>typeof $=="string"?x._`{type: ${$}}`:x._`{type: ${i}}`};function eW($){let i=KK($);(0,jK.reportError)(i,zK)}uA.reportTypeError=eW;function KK($){let{gen:i,data:v,schema:u}=$,n=(0,iA.schemaRefOrVal)($,u,"type");return{gen:i,keyword:"type",data:v,schema:u.type,schemaCode:n,schemaValue:n,parentSchema:u,params:{},it:$}}});var wA=S((UA)=>{Object.defineProperty(UA,"__esModule",{value:!0});UA.assignDefaults=void 0;var Xv=y(),VK=d();function qK($,i){let{properties:v,items:u}=$.schema;if(i==="object"&&v)for(let n in v)IA($,n,v[n].default);else if(i==="array"&&Array.isArray(u))u.forEach((n,b)=>IA($,b,n.default))}UA.assignDefaults=qK;function IA($,i,v){let{gen:u,compositeRule:n,data:b,opts:I}=$;if(v===void 0)return;let U=Xv._`${b}${(0,Xv.getProperty)(i)}`;if(n){(0,VK.checkStrictMode)($,`default is ignored for: ${U}`);return}let D=Xv._`${U} === undefined`;if(I.useDefaults==="empty")D=Xv._`${D} || ${U} === null || ${U} === ""`;u.if(D,Xv._`${U} = ${(0,Xv.stringify)(v)}`)}});var a$=S((JA)=>{Object.defineProperty(JA,"__esModule",{value:!0});JA.validateUnion=JA.validateArray=JA.usePattern=JA.callValidateCode=JA.schemaProperties=JA.allSchemaProperties=JA.noPropertyInData=JA.propertyInData=JA.isOwnProperty=JA.hasPropFunc=JA.reportMissingProp=JA.checkMissingProp=JA.checkReportMissingProp=void 0;var w$=y(),sW=d(),hi=Ki(),MK=d();function kK($,i){let{gen:v,data:u,it:n}=$;v.if(ig(v,u,i,n.opts.ownProperties),()=>{$.setParams({missingProperty:w$._`${i}`},!0),$.error()})}JA.checkReportMissingProp=kK;function TK({gen:$,data:i,it:{opts:v}},u,n){return(0,w$.or)(...u.map((b)=>(0,w$.and)(ig($,i,b,v.ownProperties),w$._`${n} = ${b}`)))}JA.checkMissingProp=TK;function EK($,i){$.setParams({missingProperty:i},!0),$.error()}JA.reportMissingProp=EK;function WA($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:w$._`Object.prototype.hasOwnProperty`})}JA.hasPropFunc=WA;function $g($,i,v){return w$._`${WA($)}.call(${i}, ${v})`}JA.isOwnProperty=$g;function lK($,i,v,u){let n=w$._`${i}${(0,w$.getProperty)(v)} !== undefined`;return u?w$._`${n} && ${$g($,i,v)}`:n}JA.propertyInData=lK;function ig($,i,v,u){let n=w$._`${i}${(0,w$.getProperty)(v)} === undefined`;return u?(0,w$.or)(n,(0,w$.not)($g($,i,v))):n}JA.noPropertyInData=ig;function gA($){return $?Object.keys($).filter((i)=>i!=="__proto__"):[]}JA.allSchemaProperties=gA;function tK($,i){return gA(i).filter((v)=>!(0,sW.alwaysValidSchema)($,i[v]))}JA.schemaProperties=tK;function RK({schemaCode:$,data:i,it:{gen:v,topSchemaRef:u,schemaPath:n,errorPath:b},it:I},U,D,w){let W=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$._`${W}, ${v.object(...J)}`;return D!==w$.nil?w$._`${U}.call(${D}, ${X})`:w$._`${U}(${X})`}JA.callValidateCode=RK;var CK=w$._`new RegExp`;function _K({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"?CK:(0,MK.useFunc)($,n)}(${v}, ${u})`})}JA.usePattern=_K;function rK($){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:sW.Type.Num},b),i.if((0,w$.not)(b),U)})}}JA.validateArray=rK;function fK($){let{gen:i,schema:v,keyword:u,it:n}=$;if(!Array.isArray(v))throw Error("ajv implementation error");if(v.some((D)=>(0,sW.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 US={keyword:"dependencies",type:"object",schemaType:"object",error:Zj.error,code($){let[i,v]=DS($);Bj($,i),Sj($,v)}};function DS({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 Bj($,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,s4.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,s4.checkReportMissingProp)($,w)});else v.if(Hg._`${D} && (${(0,s4.checkMissingProp)($,U,b)})`),(0,s4.reportMissingProp)($,b),v.else()}}Zj.validatePropertyDeps=Bj;function Sj($,i=$.schema){let{gen:v,data:u,keyword:n,it:b}=$,I=v.name("valid");for(let U in i){if((0,IS.alwaysValidSchema)(b,i[U]))continue;v.if((0,s4.propertyInData)(v,u,U,b.opts.ownProperties),()=>{let D=$.subschema({keyword:n,schemaProp:U},I);$.mergeValidEvaluated(D,I)},()=>v.var(I,!0)),$.ok(I)}}Zj.validateSchemaDeps=Sj;Zj.default=US});var Ej=S((Tj)=>{Object.defineProperty(Tj,"__esModule",{value:!0});var kj=y(),gS=d(),JS={message:"property name must be valid",params:({params:$})=>kj._`{propertyName: ${$.propertyName}}`},XS={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:JS,code($){let{gen:i,schema:v,data:u,it:n}=$;if((0,gS.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,kj.not)(b),()=>{if($.error(!0),!n.allErrors)i.break()})}),$.ok(b)}};Tj.default=XS});var Pg=S((lj)=>{Object.defineProperty(lj,"__esModule",{value:!0});var cb=a$(),bi=y(),AS=Ki(),hb=d(),jS={message:"must NOT have additional properties",params:({params:$})=>bi._`{additionalProperty: ${$.additionalProperty}}`},GS={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:jS,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,hb.alwaysValidSchema)(I,v))return;let w=(0,cb.allSchemaProperties)(u.properties),W=(0,cb.allSchemaProperties)(u.patternProperties);J(),$.ok(bi._`${b} === ${AS.default.errors}`);function J(){i.forIn("key",n,(N)=>{if(!w.length&&!W.length)A(N);else i.if(X(N),()=>A(N))})}function X(N){let L;if(w.length>8){let B=(0,hb.schemaRefOrVal)(I,u.properties,"properties");L=(0,cb.isOwnProperty)(i,B,N)}else if(w.length)L=(0,bi.or)(...w.map((B)=>bi._`${N} === ${B}`));else L=bi.nil;if(W.length)L=(0,bi.or)(L,...W.map((B)=>bi._`${(0,cb.usePattern)($,B)}.test(${N})`));return(0,bi.not)(L)}function O(N){i.code(bi._`delete ${n}[${N}]`)}function A(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,hb.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:hb.Type.Str};if(B===!1)Object.assign(V,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(V,L)}}};lj.default=GS});var _j=S((Cj)=>{Object.defineProperty(Cj,"__esModule",{value:!0});var YS=r4(),tj=a$(),Fg=d(),Rj=Pg(),NS={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)Rj.default.code(new YS.KeywordCxt(b,Rj.default,"additionalProperties"));let I=(0,tj.allSchemaProperties)(v);for(let J of I)b.definedProperties.add(J);if(b.opts.unevaluated&&I.length&&b.props!==!0)b.props=Fg.mergeEvaluated.props(i,(0,Fg.toHash)(I),b.props);let U=I.filter((J)=>!(0,Fg.alwaysValidSchema)(b,v[J]));if(U.length===0)return;let D=i.name("valid");for(let J of U){if(w(J))W(J);else{if(i.if((0,tj.propertyInData)(i,n,J,b.opts.ownProperties)),W(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 W(J){$.subschema({keyword:"properties",schemaProp:J,dataProp:J},D)}}};Cj.default=NS});var cj=S((yj)=>{Object.defineProperty(yj,"__esModule",{value:!0});var rj=a$(),mb=y(),fj=d(),xj=d(),zS={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:i,schema:v,data:u,parentSchema:n,it:b}=$,{opts:I}=b,U=(0,rj.allSchemaProperties)(v),D=U.filter((G)=>(0,fj.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,W=i.name("valid");if(b.props!==!0&&!(b.props instanceof mb.Name))b.props=(0,xj.evalu Line truncated
`)}var Zn=($)=>(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,J$())));throw B6(U,n?.callee),U}return I.value},cv=Zn(l$),Vn=($)=>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,J$())));throw B6(U,n?.callee),U}return I.value},hv=Vn(l$),qn=($)=>(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($??fv)(b.issues.map((I)=>V$(I,n,J$())))}:{success:!0,data:b.value}},Mn=qn(l$),kn=($)=>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,J$())))}:{success:!0,data:b.value}},mv=kn(l$),S6=($)=>(i,v,u)=>{let n=u?{...u,direction:"backward"}:{direction:"backward"};return Zn($)(i,v,n)},xJ=S6(l$),Z6=($)=>(i,v,u)=>{return Zn($)(i,v,u)},yJ=Z6(l$),V6=($)=>async(i,v,u)=>{let n=u?{...u,direction:"backward"}:{direction:"backward"};return Vn($)(i,v,n)},cJ=V6(l$),q6=($)=>async(i,v,u)=>{return Vn($)(i,v,u)},hJ=q6(l$),M6=($)=>(i,v,u)=>{let n=u?{...u,direction:"backward"}:{direction:"backward"};return qn($)(i,v,n)},mJ=M6(l$),k6=($)=>(i,v,u)=>{return qn($)(i,v,u)},oJ=k6(l$),T6=($)=>async(i,v,u)=>{let n=u?{...u,direction:"backward"}:{direction:"backward"};return kn($)(i,v,n)},dJ=T6(l$),E6=($)=>async(i,v,u)=>{return kn($)(i,v,u)},pJ=E6(l$);var y$={};Gi(y$,{xid:()=>r0,uuid7:()=>xN,uuid6:()=>fN,uuid4:()=>rN,uuid:()=>un,uppercase:()=>J1,unicodeEmail:()=>aJ,undefined:()=>W1,ulid:()=>_0,time:()=>v1,string:()=>b1,sha512_hex:()=>W7,sha512_base64url:()=>J7,sha512_base64:()=>g7,sha384_hex:()=>U7,sha384_base64url:()=>w7,sha384_base64:()=>D7,sha256_hex:()=>u7,sha256_base64url:()=>I7,sha256_base64:()=>b7,sha1_hex:()=>i7,sha1_base64url:()=>v7,sha1_base64:()=>n7,rfc5322Email:()=>cN,number:()=>ov,null:()=>w1,nanoid:()=>x0,md5_hex:()=>eN,md5_base64url:()=>$7,md5_base64:()=>sN,mac:()=>p0,lowercase:()=>g1,ksuid:()=>f0,ipv6:()=>d0,ipv4:()=>o0,integer:()=>U1,idnEmail:()=>hN,httpProtocol:()=>$1,html5Email:()=>yN,hostname:()=>dN,hex:()=>aN,guid:()=>c0,extendedDuration:()=>_N,emoji:()=>m0,email:()=>h0,e164:()=>i1,duration:()=>y0,domain:()=>pN,datetime:()=>u1,date:()=>n1,cuid2:()=>C0,cuid:()=>R0,cidrv6:()=>e0,cidrv4:()=>a0,browserEmail:()=>mN,boolean:()=>D1,bigint:()=>I1,base64url:()=>l6,base64:()=>s0});var R0=/^[cC][0-9a-z]{6,}$/,C0=/^[0-9a-z]+$/,_0=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,r0=/^[0-9a-vA-V]{20}$/,f0=/^[A-Za-z0-9]{27}$/,x0=/^[a-zA-Z0-9_-]{21}$/,y0=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,_N=/^[-+]?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)?)??$/,c0=/^([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})$/,un=($)=>{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})$`)},rN=un(4),fN=un(6),xN=un(7),h0=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,yN=/^[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])?)*$/,cN=/^(([^<>()\[\]\\.,;:\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,}))$/,aJ=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,hN=aJ,mN=/^[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])?)*$/,oN="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function m0(){return new RegExp(oN,"u")}var o0=/^(?:(?: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])$/,d0=/^(([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}|:))$/,p0=($)=>{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}$`)},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-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 q1={major:4,minor:4,patch:3};var t=j("$ZodType",($,i)=>{var v;$??($={}),$._zod.def=i,$._zod.bag=$._zod.bag||{},$._zod.version=q1;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),W;for(let J of U){if(J._zod.def.when){if(E0(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(W||O instanceof Promise)W=(W??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(W)return W.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((W)=>$._zod.parse(W,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((W)=>{return b(W,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=Mn($,n);return b.success?{value:b.data}:{issues:b.error?.issues}}catch(b){return mv($,n).then((I)=>I.success?{value:I.data}:{issues:I.error?.issues})}},vendor:"zod",version:1}))}),bn=j("$ZodString",($,i)=>{t.init($,i),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??b1($._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$=j("$ZodStringFormat",($,i)=>{Tn.init($,i),bn.init($,i)}),k1=j("$ZodGUID",($,i)=>{i.pattern??(i.pattern=c0),n$.init($,i)}),T1=j("$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=un(u))}else i.pattern??(i.pattern=un());n$.init($,i)}),E1=j("$ZodEmail",($,i)=>{i.pattern??(i.pattern=h0),n$.init($,i)}),l1=j("$ZodURL",($,i)=>{n$.init($,i),$._zod.check=(v)=>{try{let u=v.value.trim();if(!i.normalize&&i.protocol?.source===$1.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})}}}),t1=j("$ZodEmoji",($,i)=>{i.pattern??(i.pattern=m0()),n$.init($,i)}),R1=j("$ZodNanoID",($,i)=>{i.pattern??(i.pattern=x0),n$.init($,i)}),C1=j("$ZodCUID",($,i)=>{i.pattern??(i.pattern=R0),n$.init($,i)}),_1=j("$ZodCUID2",($,i)=>{i.pattern??(i.pattern=C0),n$.init($,i)}),r1=j("$ZodULID",($,i)=>{i.pattern??(i.pattern=_0),n$.init($,i)}),f1=j("$ZodXID",($,i)=>{i.pattern??(i.pattern=r0),n$.init($,i)}),x1=j("$ZodKSUID",($,i)=>{i.pattern??(i.pattern=f0),n$.init($,i)}),y1=j("$ZodISODateTime",($,i)=>{i.pattern??(i.pattern=u1(i)),n$.init($,i)}),c1=j("$ZodISODate",($,i)=>{i.pattern??(i.pattern=n1),n$.init($,i)}),h1=j("$ZodISOTime",($,i)=>{i.pattern??(i.pattern=v1(i)),n$.init($,i)}),m1=j("$ZodISODuration",($,i)=>{i.pattern??(i.pattern=y0),n$.init($,i)}),o1=j("$ZodIPv4",($,i)=>{i.pattern??(i.pattern=o0),n$.init($,i),$._zod.bag.format="ipv4"}),d1=j("$ZodIPv6",($,i)=>{i.pattern??(i.pattern=d0),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})}}}),p1=j("$ZodMAC",($,i)=>{i.pattern??(i.pattern=p0(i.delimiter)),n$.init($,i),$._zod.bag.format="mac"}),a1=j("$ZodCIDRv4",($,i)=>{i.pattern??(i.pattern=a0),n$.init($,i)}),e1=j("$ZodCIDRv6",($,i)=>{i.pattern??(i.pattern=e0),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 s1($){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=vn,U=!$n.jitless,w=U&&Z0.value,W=i.catchall,J;$._zod.parse=(X,O)=>{J??(J=u.value);let A=X.value;if(!I(A))return X.issues.push({expected:"object",code:"invalid_type",input:A,inst:$}),X;if(U&&w&&O?.async===!1&&O.jitless!==!0){if(!b)b=n(i.shape);if(X=b(X,O),!W)return X;return N8([],A,X,O,J,$)}return v(X,O)}});function u8($,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,J$())))}),i}var ev=j("$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)=>Rv(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 u8(I,u,$,n);return Promise.all(I).then((U)=>{return u8(U,u,$,n)})}});function b8($,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,J$())))});else i.issues.push({code:"invalid_union",input:i.value,inst:v,errors:[],inclusive:!1});return i}var GI=j("$ZodXor",($,i)=>{ev.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 b8(I,u,$,n);return Promise.all(I).then((U)=>{return b8(U,u,$,n)})}}),QI=j("$ZodDiscriminatedUnion",($,i)=>{i.inclusive=!1,ev.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=Bn(()=>{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(!vn(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}}),YI=j("$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 I8(v,D,w)});return I8(v,b,I)}});function M1($,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=M1($[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=M1(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 I8($,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=M1(i.value,v.value);if(!I.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(I.mergeErrorPath)}`);return $.value=I.data,$}var h6=j("$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,W={...w},J=D.ref;if(D.ref=null,J){u(J);let O=$.seen.get(J),A=O.schema;if(A.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))w.allOf=w.allOf??[],w.allOf.push(A);else Object.assign(w,A);if(Object.assign(w,W),U._zod.parent===J)for(let N in w){if(N==="$ref"||N==="allOf")continue;if(!(N in W))delete w[N]}if(A.$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 A in w){if(A==="$ref"||A==="allOf")continue;if(A in O.def&&JSON.stringify(w[A])===JSON.stringify(O.def[A]))delete w[A]}}}$.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:dn(i,"input",$.processors),output:dn(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 PD=($,i={})=>(v)=>{let u=li({...v,processors:i});return $$($,u),ti(u,$),Ri(u,$)},dn=($,i,v={})=>(u)=>{let{libraryOptions:n,target:b}=u??{},I=li({...n??{},target:b,io:i,processors:v});return $$($,I),ti(I,$),Ri(I,$)};var T5={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},FD=($,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=T5[U]??U,n.format==="")delete n.format;if(U==="time")delete n.format}if(w)n.contentEncoding=w;if(D&&D.size>0){let W=[...D];if(W.length===1)n.pattern=W[0].source;else if(W.length>1)n.allOf=[...W.map((J)=>({...i.target==="draft-07"||i.target==="draft-04"||i.target==="openapi-3.0"?{type:"string"}:{},pattern:J.source}))]}},BD=($,i,v,u)=>{let n=v,{minimum:b,maximum:I,format:U,multipleOf:D,exclusiveMaximum:w,exclusiveMinimum:W}=$._zod.bag;if(typeof U==="string"&&U.includes("int"))n.type="integer";else n.type="number";let J=typeof W==="number"&&W>=(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=W,n.exclusiveMinimum=!0;else n.exclusiveMinimum=W;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},SD=($,i,v,u)=>{v.type="boolean"},ZD=($,i,v,u)=>{if(i.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},VD=($,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),nV(i)}clear(){this._buffer=void 0}}function nV($){return aX.parse(JSON.parse($))}function mG($){return JSON.stringify($)+`
`}class xg{constructor($=oG.stdin,i=oG.stdout){this._stdin=$,this._stdout=i,this._readBuffer=new fg,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=mG($);if(this._stdout.write(v))i();else this._stdout.once("drain",i)})}}import{dirname as P6,resolve as iN}from"node:path";import{fileURLToPath as tM}from"node:url";import{existsSync as pi,mkdirSync as UV,readFileSync as pG,readdirSync as DV,writeFileSync as aG}from"node:fs";import{homedir as sb}from"node:os";import{dirname as wV,join as zv}from"node:path";var vV=g.enum(["account","assist","browser","manual","curl","f12"]),uV=g.object({accessToken:g.string().describe("主站访问令牌"),corpId:g.string().describe("企业 ID"),staffId:g.string().describe("员工 ID")}),bV=g.object({refreshTtl:g.number().default(300).describe("提前多少秒刷新,默认 5 分钟"),refreshToken:g.string().optional().describe("OAuth2 Refresh Token"),expiresAt:g.number().optional().describe("AccessToken 到期时间戳 (ms)")}),IV=g.object({platform:g.string().optional().describe("官方会话平台类型 (如 ASSIST, WEB, MOBILE, OPENAPI)"),isAssistPlatform:g.boolean().optional().describe("是否为官方协助/代客平台登录"),isShortTermToken:g.boolean().optional().describe("是否为短期临时 Token"),assistId:g.string().optional().describe("协助会话/工单 ID"),operationUserId:g.string().optional().describe("协助操作人 ID (如内部运维/实施账号)"),operationUserName:g.string().optional().describe("协助操作人姓名"),staffName:g.string().optional().describe("当前员工真实姓名"),cellphone:g.string().optional().describe("绑定手机号"),isAdmin:g.boolean().optional().describe("是否管理员"),deviceType:g.string().optional().describe("设备类型"),loginAccountType:g.string().optional().describe("登录账号类型"),loginTime:g.number().optional().describe("登录时间戳 (ms)"),expTime:g.number().optional().describe("过期时间戳 (ms)"),sourceChannel:g.string().optional().describe("来源渠道 (如 APP, WEB)")}),yg=g.object({id:g.string().describe("配置/身份唯一标识 (默认等于 corpId,同企业多身份时形如 corpId@accountId 或 corpId:staffId)"),name:g.string().describe("企业名称"),corpId:g.string().optional().describe("底层企业物理 ID (未填时默认等于 id)"),userId:g.string().optional().describe("所属用户 ID"),staffId:g.string().optional().describe("员工工号 (默认取 credentials.staffId)"),staffName:g.string().optional().describe("员工真实姓名"),baseUrl:g.string().url().optional().default("https://app.ekuaibao.com"),source:vV.optional().default("manual").describe("凭证来源: account/assist/browser/manual/curl/f12"),accountId:g.string().optional().describe("所属主账号标识(如手机号)"),credentials:uV,auth:bV.optional(),session:IV.optional().describe("官方服务端 Session 与操作人元数据")}),cg=g.object({stateful:g.boolean().default(!0).describe("是否为有状态模式 (true 记忆默认企业,false 无状态需显式传 --corp)"),defaultCorpId:g.string().optional().describe("默认工作企业 ID"),defaultAccountId:g.string().optional().describe("默认主账号")});var n6="enterprises",hg="HOSE_ENTERPRISES_DIR",eG="HOSE_USER_ENTERPRISES_DIR",sG="HOSE_CONFIG_FILE",mg=zv(sb(),".config","hose-use","enterprises"),$Q=zv(sb(),".cache","ekb-mcp","enterprises");var eb=zv(sb(),".config","hose-use","config.json"),dG=zv(sb(),".cache","ekb-mcp","config.json");function iQ($){UV($,{recursive:!0})}function og(){let $=process.env[hg]?.trim();if($)return pi($)?[$]:[];let i=process.env[eG]?.trim();if(i)return[n6,i].filter((n)=>pi(n));let v=[n6,mg,$Q],u=[];for(let n of v)if(pi(n)&&!u.includes(n))u.push(n);return u}function dg(){let $=process.env[hg]?.trim();if($)return $;let i=process.env[eG]?.trim();if(i)return i;if(pi(n6))return n6;return mg}function $0(){return[`${hg}=<path>`,n6,mg,$Q]}function i0(){let $=process.env[sG]?.trim();if($)return $;if(pi(eb))return eb;if(pi(dG))return dG;return eb}function Gn(){let $=i0();try{if(pi($)){let i=pG($,"utf-8");return cg.parse(JSON.parse(i))}}catch{}return{stateful:!0,defaultCorpId:void 0,defaultAccountId:void 0}}function v6($){let i=Gn(),v=cg.parse({...i,...$}),n=process.env[sG]?.trim()||eb;return iQ(wV(n)),aG(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 u6{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 WV(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)v6({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 b6 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 I6 extends Fi{name="NetworkError";request;constructor($,i){super(`Request failed due to a network error: ${$.method} ${$.url}`,i);this.request=$}}class U6 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 Pv extends Fi{name="ForceRetryError";customDelay;code;customRequest;constructor($){let i=$?.cause?$.cause instanceof Error?$.cause:new U6($.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 pg 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 ag=(()=>{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})(),vQ=typeof globalThis.AbortController==="function",n0=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",uQ=typeof globalThis.ReadableStream==="function",bQ=typeof globalThis.FormData==="function",v0=["get","post","put","patch","head","delete"],gV=()=>{return};gV();var IQ={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},Fv=2147483647,UQ=40,u0=Symbol("stop");class b0{options;constructor($){this.options=$}}var DQ=($)=>new b0($),wQ={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},WQ={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 I0=new TextEncoder,JV=($)=>{if(!$)return 0;if($ instanceof FormData){let i=0;for(let[v,u]of $)i+=UQ,i+=I0.encode(`Content-Disposition: form-data; name="${v}"`).byteLength,i+=typeof u==="string"?I0.encode(u).byteLength:u.size;return i}if($ instanceof Blob)return $.size;if($ instanceof ArrayBuffer||ArrayBuffer.isView($))return $.byteLength;if(typeof $==="string")return I0.encode($).byteLength;if($ instanceof URLSearchParams)return I0.encode($.toString()).byteLength;return 0},gQ=($,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 qQ.publicEncrypt({key:v,padding:qQ.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 cV($){let i=$.businessCenterUrl||Qn,v=$.areaCode||"86",u=$.deviceType||"desktop",n=await xV(i),b=yV($.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 W$(I.errorMessage||"账号或密码错误");return{cloudAuthToken:I.data}}async function kQ($){let i=$.businessCenterUrl||Qn,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 W$(n.errorMessage||"发送验证码失败");return{codeId:n.data?.codeId}}async function hV($){let i=$.businessCenterUrl||Qn,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 W$(n.errorMessage||"验证码错误或已过期");return{cloudAuthToken:n.data}}async function mV($={}){let i=$.webbridgeUrl||rV;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 W$("未能从当前浏览器会话中获取到合思登录凭证,请确保网页已登录");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 W$)throw v;throw new W$(`连接浏览器 WebBridge 失败: ${v instanceof Error?v.message:String(v)}`)}}function TQ($){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 EQ($){let{accessToken:i,corpId:v,staffId:u}=$,n=$.baseUrl||fV;if(!i||!v||!u)throw new W$("导入凭证失败: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 W$(`凭证校验失败,请检查 token 是否已过期: ${G instanceof Error?G.message:String(G)}`)}let I=$.name,U=b?.privilege,D,w,W,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 A={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:W}};return Hv(A,$.enterprisesDir),A}async function oV($,i=Qn){let v=await Q$.get(`${i}/cloud-auth/public/auth/list-corporations`,{headers:{"cloud-auth-token":$}}).json();if(!v.data?.items)throw new W$(v.errorMessage||"获取企业列表失败");return[...v.data.items||[],...v.data.externalItems||[]].map((n)=>VQ.parse(n))}async function wJ($,i,v,u=MQ,n=Qn){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 W$(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 W$(`换取企业 ${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 WJ($,i=Qn,v=MQ){let u=$.accountId?DJ($.accountId):Zv();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 wJ(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,Hv($),!0}catch(n){return console.warn(`[auth] 自动续杯刷新企业 ${$.name} 失败:`,n instanceof Error?n.message:String(n)),!1}}async function lQ($){let{cloudAuthToken:i}=await cV($),v=A6($.phone,$.areaCode);return w0(v,i,$)}async function tQ($){let{cloudAuthToken:i}=await hV($),v=A6($.phone,$.areaCode);return w0(v,i,$)}async function RQ($={}){let{cloudAuthToken:i,activeSession:v}=await mV($);if(i)return w0("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 Hv(u,$.enterprisesDir),{selectedCorp:u,allCorps:[u],cloudAuthToken:"",accountId:"browser_ Line truncated
`)}function S$($,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((W)=>(W[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 NJ(){return`
合思/易快报企业级 CLI 工具 (hose-use) v${l}
用法:
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)
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 uzU7pcWfScck00 # 切换工作企业
hose-use workflow list # 汇总查看全部工作流
hose-use workflow find --task=code-js2 # 搜索包含自定义脚本的工作流
hose-use bill list # 查看当前企业单据与报销列表
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 kq from"readline";function DY($={}){let i=Kv(),v=Gn(),u=$.stateless?!1:$.stateful?!0:v.stateful,n=new u6(i,{stateful:u,defaultCorpId:v.defaultCorpId}),b=null;try{b=n.resolve($.corpId,$0())}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 f$($),{client:v}=await g0($);return{corp:$,ekbClient:i,easoClient:v}}function Si($){let i=kq.createInterface({input:process.stdin,output:process.stdout});return new Promise((v)=>{i.question($,(u)=>{i.close(),v(u.trim())})})}async function wY($,i){let v=$.action||"status";switch(v){case"login":return Tq($,i);case"status":case"whoami":return Eq($,i);case"refresh":return lq($,i);case"import":return tq($,i);case"accounts":return Rq($,i);case"switch-account":return Cq($,i);default:return{stdout:"",stderr:`未知 auth 子命令: ${v}。支持: login, status, refresh, import, accounts, switch-account
`,exitCode:1}}}async function Tq($,i){let v=e($.options,["phone","p"]),u=e($.options,["password","pwd"]),n=g$($.options,["sms"]),b=g$($.options,["sync"]),I=g$($.options,["interactive","i"])||!v&&!u&&!n&&!b;if(b){let X=await RQ({saveAll:!0});if(i.jsonMode)return{stdout:E(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 kQ({phone:X})).codeId,console.log("短信验证码已发送!")}catch(N){console.log("若触发了人机验证,请在浏览器中获取验证码后直接在下方输入。")}let A=await Si("请输入收到的 6 位短信验证码: ");if(!A)return{stdout:"",stderr:`验证码不能为空
`,exitCode:1};let G=await tQ({phone:X,code:A,codeId:O,saveAll:!0});if(i.jsonMode)return{stdout:E(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 lQ({phone:U,password:D,saveAll:!0});if(i.jsonMode)return{stdout:E(w),stderr:"",exitCode:0};let W=w.allCorps.map((X,O)=>[O+1,X.id,X.name,X.credentials.staffId]),J=S$(["#","企业 ID","企业名称","员工工号"],W);return{stdout:`[SUCCESS] 账密登录成功!
账号: ${w.accountId}
默认企业: ${w.selectedCorp.name} (${w.selectedCorp.id})
共保存企业配置: ${w.allCorps.length} 家
${J}
`,stderr:"",exitCode:0}}async function Eq($,i){let v=i.selectedCorp,u=Zv(),n=!1,b=null;if(v)try{let W=await(await f$(v)).get("api/account/v2/session").json();n=!!W.value,b=W.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:E(I),stderr:"",exitCode:0};let U={"当前活跃账号":u?.accountId||"未登录","当前激活企业":v?`${v.name} (${v.id})`:"未配置","当前员工工号":v?.credentials.staffId||"-","员工真实姓名":v?.staffName||v?.session?.staffName||"-","凭证来源类型":Yn(v?.source),"Token 有效性":n?"✅ 有效 (已通过 Session 验证)":"❌ 无效或未连接","Token 过期时间":ei(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 lq($,i){let v=e($.options,["account","a"]),u=await CQ(v,{saveAll:!0});if(i.jsonMode)return{stdout:E(u),stderr:"",exitCode:0};return{stdout:`[SUCCESS] 成功批量刷新账号 ${u.accountId} 下的所有企业 AccessToken!
共刷新企业: ${u.allCorps.length} 家
`,stderr:"",exitCode:0}}async function tq($,i){let v=e($.options,["raw","headers","curl"]),u=e($.options,["token","accessToken"]),n=e($.options,["corp","corpId"]),b=e($.options,["staff","staffId"]),I=e($.options,["name"]);if(!v&&!u)v=await Si("请粘贴抓包文本 / cURL 命令行 (直接回车则手动逐项输入): ");if(v){let W=TQ(v);if(W.accessToken)u=W.accessToken;if(W.corpId)n=W.corpId;if(W.staffId)b=W.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 EQ({accessToken:u,corpId:n,staffId:b,name:I});if(i.jsonMode)return{stdout:E(U),stderr:"",exitCode:0};let D={"企业名称":U.name,"企业 ID":U.id,"员工工号":U.credentials.staffId,"员工姓名":U.staffName||U.session?.staffName||"-","凭证来源":Yn(U.source),"过期时间":ei(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 Rq($,i){let v=SQ(),u=Zv();if(i.jsonMode)return{stdout:E({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:`====== 本地已保存账号列表 ======
${S$(["#","账号标识","用户 ID","关联企业数","最近更新时间"],n)}
`,stderr:"",exitCode:0}}async function Cq($,i){let v=$.args[0]||e($.options,["account","a"]);if(!v)return{stdout:"",stderr:`用法: hose auth switch-account <accountId>
`,exitCode:1};if(!ZQ(v))return{stdout:"",stderr:`未找到账号: ${v}
`,exitCode:1};return{stdout:`[SUCCESS] 当前活跃主账号已切换至: ${v}
`,stderr:"",exitCode:0}}async function WY($,i){let v=$.action||"list";switch(v){case"list":return _q($,i);case"switch":case"use":return rq($,i);case"current":return fq($,i);default:return{stdout:"",stderr:`未知 corps 子命令: ${v}。支持: list, switch, current
`,exitCode:1}}}async function _q($,i){let v=i.corpContext.listCorps();if(i.jsonMode)return{stdout:E({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",ei(b.expiresAt),b.accountId||"-"]),n=S$(["#","企业 ID","企业名称","员工工号","来源","Token 过期时间","所属账号"],u);return{stdout:`====== 已配置企业列表 (${v.length} 家) ======
${n}
提示: 使用 hose corps switch <企业ID> 切换工作企业
`,stderr:"",exitCode:0}}async function rq($,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:E(n,i.outputOptions),stderr:"",exitCode:0};return{stdout:`[SUCCESS] 已切换到企业: ${n?.name} (${n?.id})
`,stderr:"",exitCode:0}}async function fq($,i){let v=i.selectedCorp;if(!v)return{stdout:"",stderr:`未选中任何企业
`,exitCode:1};if(i.jsonMode)return{stdout:E(v,i.outputOptions),stderr:"",exitCode:0};let u={"企业 ID":v.id,"企业名称":v.name,"员工工号":v.credentials.staffId,"员工姓名":v.staffName||v.session?.staffName||"-","凭证来源":Yn(v.source),"Token 过期时间":ei(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 gY($,i){let v=$.action||"show";switch(v){case"show":case"get":case"list":return xq($,i);case"paths":case"path":case"dirs":return hq($,i);case"mode":return yq($,i);case"set":return cq($,i);default:return{stdout:"",stderr:`未知 config 子命令: ${v}。支持: show, paths, mode <stateful|stateless>, set <key> <val>
`,exitCode:1}}}async function xq($,i){let v=Gn(),u=i.selectedCorp,n=i0(),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:E(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 yq($,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=v6({stateful:u});if(i.jsonMode)return{stdout:E(n),stderr:"",exitCode:0};return{stdout:`[SUCCESS] 全局运行模式已切换为: ${u?"有状态模式 (Stateful)":"无状态模式 (Stateless)"}
`,stderr:"",exitCode:0}}async function cq($,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=v6(n);if(i.jsonMode)return{stdout:E(b),stderr:"",exitCode:0};return{stdout:`[SUCCESS] 配置已更新: ${v} = ${u}
`,stderr:"",exitCode:0}}async function hq($,i){let v=process.env.HOSE_ENTERPRISES_DIR,u=process.env.HOSE_USER_ENTERPRISES_DIR,n=process.env.HOSE_CONFIG_FILE,b=og(),I=dg(),U=i0(),D=$0(),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:E(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 JY($,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 mq($,i);case"get":case"detail":case"info":return oq($,i);case"find":case"search":return dq($,i);case"toggle":return pq($,i);default:return{stdout:"",stderr:`未知 workflow 子命令: ${u}。支持: list, get, find, toggle
`,exitCode:1}}}async function mq($,i){let v=await Bi(i.selectedCorp),u=m$($.options,["page"])||1,n=m$($.options,["pageSize","size"])||50,b=await G6(v,{page:u,pageSize:n});if(i.jsonMode)return{stdout:E(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=S$(["#","工作流 ID","工作流名称","所属自建应用","状态","节点数"],I);return{stdout:`====== [${i.selectedCorp.name}] 工作流列表 (共 ${b.workflows.length} 条) ======
${U}
`,stderr:"",exitCode:0}}async function oq($,i){let v=$.args[0]||e($.options,["id","pipelineId"]);if(!v)return{stdout:"",stderr:`用法: hose workflow get <pipelineId>
`,exitCode:1};let u=await Bi(i.selectedCorp),n=await qv(u.easoClient,v);if(i.jsonMode)return{stdout:E(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=`
节点结构:
`+S$(["#","节点标识","节点名称","类型","分组"],U)}return{stdout:`====== 工作流详情 ======
${b}
${I}
`,stderr:"",exitCode:0}}async function dq($,i){let v=e($.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=g$($.options,["includeDetail","detail"]),b=m$($.options,["page"])||1,I=m$($.options,["pageSize","size"])||50,U=await pQ(u,v,{page:b,pageSize:I,includeDetail:n});if(i.jsonMode)return{stdout:E(U,i.outputOptions),stderr:"",exitCode:0};if(U.workflows.length===0)return{stdout:`未找到包含节点类型 [${v}] 的工作流
`,stderr:"",exitCode:0};let D=U.workflows.map((W,J)=>[J+1,W.id,W.pipelineName,W.platformName||W.platformId||"-",W.state===1?"\uD83D\uDFE2 启用":"⚪ 停用"]),w=S$(["#","工作流 ID","工作流名称","所属自建应用","状态"],D);return{stdout:`====== 匹配节点类型 [${v}] 的工作流 (共 ${U.workflows.length} 条) ======
${w}
`,stderr:"",exitCode:0}}async function pq($,i){let v=$.args[0]||e($.options,["id","pipelineId"]),u=e($.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 oQ(b.easoClient,v,n);if(i.jsonMode)return{stdout:E(I,i.outputOptions),stderr:"",exitCode:0};return{stdout:`[SUCCESS] 工作流 ${v} 状态已更新为: ${n===1?"\uD83D\uDFE2 启用":"⚪ 停用"}
`,stderr:"",exitCode:0}}async function XY($,i){if(!i.selectedCorp)return{stdout:"",stderr:`未选中企业,请先通过 hose corps switch 或 --corp 指定企业
`,exitCode:1};let u=$.action||"list";switch(u){case"list":case"ls":return aq($,i);default:return{stdout:"",stderr:`未知 platform 子命令: ${u}。支持: list
`,exitCode:1}}}async function aq($,i){let v=await Bi(i.selectedCorp),u=await Vv(v.ekbClient,i.selectedCorp.credentials.corpId);if(i.jsonMode)return{stdout:E(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=S$(["#","自建应用 ID","应用名称","状态"],n);return{stdout:`====== [${i.selectedCorp.name}] 自建应用列表 (共 ${u.length} 个) ======
${b}
`,stderr:"",exitCode:0}}import{existsSync as KJ}from"node:fs";import{join as L6}from"node:path";import{mkdirSync as NY,writeFileSync as uM}from"node:fs";import{homedir as A0}from"node:os";import{dirname as bM,join as Y6}from"node:path";var OY=`---
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.1)
在具备 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) |
| 单据实体模型与字段元数据查询 | \`hose bill schema\` | [references/bill.md](references/bill.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 uzU7pcWfScck00 # 切换工作企业
hose probe # 诊断当前企业接口连通性
# 2. 单据与费用
hose bill list # 查看最新单据与报销记录
hose bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘
hose bill get n0GMIM0dkQmKbS # 精准查询单据详情 (中文字段映射)
hose bill schema # 查询单据实体元数据字典
# 3. 自建应用与工作流
hose platform list # 查看自建应用列表
hose workflow list # 聚合扫描全部应用下的工作流
hose workflow find --task=code-js2 # 查找部署了代码节点的工作流
hose workflow get wf_01k83y... # 查看指定工作流节点拓扑
# 4. 服务与守护进程
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 AY=`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 jY="# 认证、多租户与运行模式指南 (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 GY="# 单据与费用明细指南 (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 YY=`# 服务、守护进程与 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 LY={"SKILL.md":OY,"agents/openai.yaml":AY,"references/auth.md":jY,"references/bill.md":GY,"references/workflow.md":QY,"references/service.md":YY};function zY(){return LY["SKILL.md"]||""}function N6(){return Y6(A0(),".agents","skills","hose-use")}function LJ(){return[Y6(A0(),".agents","skills","hose-use"),Y6(A0(),".gemini","antigravity","skills","hose-use"),Y6(A0(),".codex","skills","hose-use")]}function j0($=N6()){NY($,{recursive:!0});let i=[];for(let[v,u]of Object.entries(LY)){let n=Y6($,v);NY(bM(n),{recursive:!0}),uM(n,u,"utf8"),i.push(v)}return{targetDir:$,files:i}}function zJ(){let $=N6();return j0($),{synced:!0,targetDir:$}}async function KY($,i){let v=$.action||"status";switch(v){case"dump":case"cat":case"show":return{stdout:`${zY()}
`,stderr:"",exitCode:0};case"install":case"init":case"sync":{let u=g$($.options,["local"])||g$($.options,["workspace"]),n=e($.options,["dir","target"])||$.args[0],b=n?n:u?L6(process.cwd(),".agents","skills","hose-use"):N6(),I=j0(b),U=LJ();for(let D of U)if(D!==b)try{j0(D)}catch{}if(i.jsonMode)return{stdout:E({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=N6(),n=L6(process.cwd(),".agents","skills","hose-use"),b=LJ(),I={global:{dir:u,installed:KJ(L6(u,"SKILL.md"))},local:{dir:n,installed:KJ(L6(n,"SKILL.md"))},candidates:b.map((D)=>({dir:D,installed:KJ(L6(D,"SKILL.md"))}))};if(i.jsonMode)return{stdout:E(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 HY($,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 Vv(I.ekbClient,v.credentials.corpId);u.platformAccess={status:"ok",totalPlatforms:U.length};let D=await mQ(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:E(u),stderr:"",exitCode:0};let n={"企业名称":v.name,"企业 ID":v.id,"员工工号":v.credentials.staffId,"员工姓名":v.staffName||v.session?.staffName||"-","凭证来源":Yn(v.source),"Token 过期时间":ei(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 IM}from"child_process";import{join as UM}from"path";async function PY($,i){let v=i.appRoot||process.cwd(),u=UM(v,"src","server.ts");console.error("启动 MCP Server on stdio...");let n=IM("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 wM,mkdirSync as WM,renameSync as HJ,rmSync as gM,unlinkSync as MY,writeFileSync as SY}from"node:fs";import{dirname as JM,join as ZY}from"node:path";import{spawnSync as Nn}from"node:child_process";import{dirname as FY}from"node:path";import{fileURLToPath as DM}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 BY($,i=z6()){if(i)return process.cwd();let v=$||DM(import.meta.url);return FY(FY(v))}var kY="yunyingk/hose-use",XM="HOSE_USE_GITHUB_REPO";async function TY($,i,v={}){let u=$.area==="changelog"||$.action==="changelog"||$.action==="log"||$.action==="history"||g$($.options,["changelog","log","l"]),n=$.action==="check"||g$($.options,["check","check-only","c"]),b=e($.options,["version","tag","target","t"])||(!u&&!n&&$.action&&!$.action.startsWith("-")?$.action:void 0),I=b&&b.toLowerCase()!=="latest"?b.replace(/^v/,""):void 0,U=e($.options,["repo"])||process.env[XM]?.trim()||kY,D={checkOnly:n,changelogOnly:u,limit:m$($.options,["limit","n"]),force:g$($.options,["force","f"]),targetVersion:I,repo:U},w=v.appRoot||BY(v.entryFile);if(I){let C=EY(I,l);if(C<0&&!D.force){let r=`无法降级 hose-use(当前版本 v${l},目标版本 v${I})。如需强制重装请使用 --force。`;if(i.jsonMode)return{stdout:E({updated:!1,currentVersion:l,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${l}。如需强制重装请添加 --force。`;if(i.jsonMode)return{stdout:E({updated:!1,currentVersion:l,targetVersion:I,mode:z6()?"binary":"source",message:r}),stderr:"",exitCode:0};return{stdout:`ℹ️ ${r}
`,stderr:"",exitCode:0}}}if(D.changelogOnly){let C=await PJ(U,D.limit??10);if(i.jsonMode)return{stdout:E({currentVersion:l,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===l,isNewer:kv(s.version,l)}))}),stderr:"",exitCode:0};let r=[`====== hose-use 版本发布记录 (当前版本: v${l}) ======`,""];for(let s of C){let x$=s.version===l?" [当前版本]":kv(s.version,l)?" [新版本 ✨]":"";if(r.push(`• v${s.version} (${s.publishedAt?s.publishedAt.slice(0,10):"未知日期"})${x$}`),s.notes){let si=s.notes.trim().split(`
`).map((Zi)=>` ${Zi}`).join(`
`);r.push(si)}r.push("")}return{stdout:r.join(`
`),stderr:"",exitCode:0}}if(!z6()){if(D.checkOnly){let r=await PJ(U,30),s=r[0],x$=s?.version??l,si=r.find((Di)=>Di.version===l),Zi=kv(x$,l),Pn=r.filter((Di)=>kv(Di.version,l));if(i.jsonMode)return{stdout:E({updated:!1,updateAvailable:Zi,currentVersion:l,currentVersionPublishedAt:si?.publishedAt,latestVersion:x$,latestVersionPublishedAt:s?.publishedAt,behindCount:Pn.length,pendingReleases:Pn.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${l}`,"最新版本":`v${x$} ${Zi?"(可升级 ✨)":"(已是最新 ✅)"}`,"待更新版本数":Pn.length,"源码路径":w})}
${Zi?"可运行 hose-use update 执行 git pull 与依赖同步":"已经是最新版本"}
`,stderr:"",exitCode:0}}try{qY("git",["-C",w,"pull","--ff-only"])}catch(r){let s=r instanceof Error?r.message:String(r);console.error(`git pull 提示: ${s}`)}qY("bun",["install"],{cwd:w});let C=zJ();if(i.jsonMode)return{stdout:E({updated:!0,version:l,mode:"source",skillSynced:C.synced?C.targetDir:!1}),stderr:"",exitCode:0};return{stdout:`[SUCCESS] hose-use 源码与依赖更新成功!
版本: v${l}
技能同步: ${C.synced?"已同步至全局 ✅":"未同步"}
`,stderr:"",exitCode:0}}let W=OM(),J=AM(),X=await PJ(U,30),O=I?X.find((C)=>C.version===I||C.tagName===I||C.tagName===`v${I}`)??await VY(U,I):X[0]??await VY(U);if(!O){let C=`无法从 GitHub 仓库 '${U}' 获取 Release 列表`;if(i.jsonMode)return{stdout:E({updated:!1,currentVersion:l,mode:"binary",message:C}),stderr:"",exitCode:1};return{stdout:"",stderr:`[ERROR] ${C}
`,exitCode:1}}let A=O.version,G=X.find((C)=>C.version===l),N=kv(A,l),L=N||Boolean(D.force),B=X.filter((C)=>kv(C.version,l));if(D.checkOnly){if(i.jsonMode)return{stdout:E({updated:!1,updateAvailable:N,currentVersion:l,currentVersionPublishedAt:G?.publishedAt,latestVersion:A,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${l}`,"最新版本":`v${A} ${N?"(可升级 ✨)":"(已是最新 ✅)"}`,"发布时间":O.publishedAt?O.publishedAt.slice(0,10):"未知","平台架构":`${W}-${J}`})}
${N?`运行 hose-use update 升级至 v${A}`:"已经是最新版本"}
`,stderr:"",exitCode:0}}if(!L){if(i.jsonMode)return{stdout:E({updated:!1,currentVersion:l,currentVersionPublishedAt:G?.publishedAt,latestVersion:A,latestVersionPublishedAt:O.publishedAt,mode:"binary",message:`hose-use 当前已是最新版本 (v${l})`}),stderr:"",exitCode:0};return{stdout:`ℹ️ hose-use 当前已是最新版本 (v${l})。如需重装请添加 --force。
`,stderr:"",exitCode:0}}let V=jM(O.assets,W,J);if(!V){let C=`未找到适用于 ${W}-${J} 平台的 Release 资产 (v${A})。可用文件: ${O.assets.map((r)=>r.name).join(", ")}`;if(i.jsonMode)return{stdout:E({updated:!1,error:!0,message:C}),stderr:"",exitCode:1};return{stdout:"",stderr:`[ERROR] ${C}
`,exitCode:1}}let q=process.execPath,M=JM(q),X$=ZY(M,`.tmp-update-${Date.now()}`);WM(X$,{recursive:!0});try{let C=ZY(X$,V.name);await GM(V.downloadUrl,C,O.tagName,V.name);let r=C;if(V.name.endsWith(".tar.gz")||V.name.endsWith(".tgz"))r=QM(C,X$,W);else if(V.name.endsWith(".zip"))r=YM(C,X$,W);if(wM(r,493),process.platform==="darwin")try{Nn("/usr/bin/codesign",["--remove-signature",r],{stdio:"ignore"}),Nn("/usr/bin/codesign",["--force","--sign","-",r],{stdio:"ignore"})}catch{}if(process.platform==="win32"){let x$=`${q}.old.${Date.now()}`;try{HJ(q,x$)}catch{}HJ(r,q)}else HJ(r,q);let s=zJ();if(i.jsonMode)return{stdout:E({updated:!0,fromVersion:l,toVersion:A,skillSynced:s.synced?s.targetDir:!1,mode:"binary"}),stderr:"",exitCode:0};return{stdout:`[SUCCESS] ✨ hose-use 已成功升级至 v${A}!
可执行文件: ${q}
Agent 技能: ${s.synced?"已自动同步最新版 ✅":"未同步"}
`,stderr:"",exitCode:0}}finally{try{gM(X$,{recursive:!0,force:!0})}catch{}}}function OM(){if(process.platform==="darwin")return"darwin";if(process.platform==="win32")return"windows";return"linux"}function AM(){return process.arch==="arm64"?"arm64":"x64"}async function PJ($,i=20){let v=process.env.GITHUB_TOKEN||process.env.GH_TOKEN,u={"User-Agent":`hose-use/${l}`,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 W=w.tag_name??"",J=W.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:W,name:w.name??W,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 VY($,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/${l}`,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(),W=w.tag_name??"",J=W.replace(/^v/,"");if(!J)continue;let X=(w.assets??[]).map((A)=>({name:A.name,downloadUrl:A.browser_download_url,size:A.size??0})),O={version:J,tagName:W,name:w.name??W,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 jM($,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((W)=>{let J=W.name.toLowerCase(),X=b.some((A)=>J.includes(A)),O=I.some((A)=>J.includes(A));return X&&O}),D=U.find((W)=>!W.name.endsWith(".tar.gz")&&!W.name.endsWith(".tgz")&&!W.name.endsWith(".zip")&&!W.name.endsWith(".sha256"));if(D)return D;return U.find((W)=>W.name.endsWith(".tar.gz")||W.name.endsWith(".tgz")||W.name.endsWith(".zip"))||U[0]}function G0($){try{process.stderr.write(`${$}
`)}catch{}}async function GM($,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/${kY}/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 W=U[w];try{G0(`==> [${w+1}/${U.length}] 正在下载更新: ${W}`);let J=await fetch(W,{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} 字节)`);SY(i,B),G0(`✓ 下载完成 (${(B.length/1024/1024).toFixed(1)} MB)`);return}let A=[],G=0,N=0;while(!0){let{done:B,value:V}=await O.read();if(B)break;if(V){A.push(V),G+=V.length;let q=Date.now();if(q-N>200){N=q;let M=X?Math.round(G/X*100):0,X$=(G/1048576).toFixed(1),C=X?(X/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ 进度: ${M}% (${X$} / ${C} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let L=Buffer.concat(A);if(L.length<1000)throw Error(`下载文件异常(大小仅 ${L.length} 字节)`);SY(i,L),G0(`✓ 下载完成 (${(L.length/1024/1024).toFixed(1)} MB)`);return}catch(J){D=J instanceof Error?J:Error(String(J)),G0(` ↳ 节点失败: ${D.message}`)}}throw Error(`所有下载镜像均失败: ${D?.message}`)}function QM($,i,v){let u=Nn("tar",["-xzf",$,"-C",i],{stdio:"pipe"});if(u.status!==0)throw Error(`解压 tar 归档失败: ${u.stderr.toString()}`);MY($);let n=v==="windows"?"hose-use.exe":"hose-use",b=Nn("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 YM($,i,v){let u=Nn("unzip",["-q","-o",$,"-d",i],{stdio:"pipe"});if(u.status!==0)throw Error(`解压 zip 归档失败: ${u.stderr.toString()}`);MY($);let n=v==="windows"?"hose-use.exe":"hose-use",b=Nn("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 EY($,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 kv($,i){return EY($,i)>0}function qY($,i,v={}){let u=Nn($,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 lY={openapi:"3.1.0",info:{title:"hose-use API & MCP Tools Specification",version:"0.5.1",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=Ln(u),I=b.info||{},U=(b.servers||[]).map((X)=>`${X.url} (${X.description||"-"})`),D=(b.tags||[]).map((X)=>`${X.name}: ${X.description||""}`),w=FJ(u),W={title:I.title,version:I.version,description:I.description,type:u,totalEndpoints:w.length,servers:U,tags:D};if(i.jsonMode)return{stdout:E(W),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=Ln(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 f$(v),n=$.action?.toLowerCase(),b=v.corpId||v.id;switch(n){case"list":case"search":case void 0:{let I=e($.options,["code","c"]),U=e($.options,["keyword","k","q","query"]),D=e($.options,["stage"]),w=e($.options,["state","s"]),W=m$($.options,["count","limit","n"],20),J=await QJ(u,b,{code:I,keyword:U,stage:D,state:w,count:W});if(i.jsonMode)return{stdout:E({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||"-"]),A=S$(X,O),G=`====== 单据与费用明细列表 (企业: ${v.name} | 总数: ${J.total} | 本次返回: ${J.returned}) ======
`,N=`
提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细
`;return{stdout:G+A+N,stderr:"",exitCode:0}}case"get":case"show":case"find":{let I=$.args[0]||e($.options,["code","id"]);if(!I)throw Error("请提供要查询的单号或单据 ID: hose-use bill get <单号|ID>");let U=await GJ(u,b,I);if(U.length===0){if(i.jsonMode)return{stdout:E({found:!1,code:I,message:"未找到匹配单据"}),stderr:"",exitCode:1};return{stdout:"",stderr:`[NOT FOUND] 在企业 [${v.name}] 下未找到单号或 ID 为 [${I}] 的单据
`,exitCode:1}}if(i.jsonMode)return{stdout:E({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 W=U[w];if(D.push(`
====== 单据详情 [${w+1}/${U.length}] (单号: ${W.billCode}) ======`),D.push(` 单据 ID : ${W.billId}`),D.push(` 单据名称 : ${W.billName}`),W.title)D.push(` 单据标题 : ${W.title}`);if(W.stage)D.push(` 业务阶段 : ${W.stage}`);if(W.state)D.push(` 审批状态 : ${W.state}`);if(W.amount)D.push(` 单据金额 : ${W.amount}`);if(W.submitterId)D.push(` 提交人员 : ${W.submitterId}`);if(W.submitDate)D.push(` 提交时间 : ${W.submitDate}`);D.push(` 创建时间 : ${W.createTime}`),D.push(` 更新时间 : ${W.updateTime}`),D.push(`
--- 结构化表单字段明细 ---`);let J=Object.entries(W.details);if(J.length===0)D.push(" (无额外字段数据)");else{let X=Math.max(...J.map(([O])=>O.length),0);for(let[O,A]of J){let G=typeof A==="object"?JSON.stringify(A):String(A);D.push(` ${O.padEnd(X+2)}: ${G}`)}}}return{stdout:D.join(`
`)+`
`,stderr:"",exitCode:0}}case"schema":case"schemas":case"entities":{let{entities:I}=await Q6(u,b,!0);if(i.jsonMode)return{stdout:E({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=S$(U,D);return{stdout:`====== 单据实体与数据模型字典 (企业: ${v.name} | 共 ${I.length} 个实体) ======
`+w+`
`,stderr:"",exitCode:0}}default:throw Error(`未知 bill 子命令: ${n}。支持: list, get <单号>, schema`)}}import{homedir as MM}from"node:os";import{join as pY}from"node:path";import{spawn as FM,execFileSync as BM}from"node:child_process";import{existsSync as yY,mkdirSync as SM,readFileSync as cY,rmSync as H6,writeFileSync as qJ}from"node:fs";import{join as hY}from"node:path";import{createServer as PM}from"node:http";import{URL as zM}from"node:url";function _Y(){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${l})</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 rY($,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 zM($.url||"/",`${u}://${v}`).pathname.replace(/\/+$/,"")||"/",I=($.method||"GET").toUpperCase();try{if(I==="GET"&&b==="/"){zn(i,200,{name:"hose-use",version:l,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:l,timestamp:new Date().toISOString()});return}if(I==="GET"&&b==="/docs"){KM(i,200,_Y());return}if(I==="GET"&&b==="/openapi.json"){zn(i,200,Ln("wrapped"));return}if(I==="GET"&&b==="/raw-openapi.json"){zn(i,200,Ln("raw"));return}if(I==="POST"&&b==="/api/cli"){let U=await HM($),D=(typeof U?.command==="string"?U.command:"").trim();if(!D){BJ(i,400,"Missing 'command' property in request body");return}let w=SJ(D),W=ZJ(w),J=await K6(W),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=Kv(),D=Gn();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}BJ(i,404,`Cannot ${I} ${b}. Visit /docs for available endpoints.`)}catch(U){let D=U instanceof Error?U.message:String(U);BJ(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 KM($,i,v){if($.headersSent)return;$.writeHead(i,{"Content-Type":"text/html; charset=utf-8","Content-Length":Buffer.byteLength(v,"utf-8")}),$.end(v)}function BJ($,i,v){zn($,i,{error:!0,message:v})}async function HM($){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 Q0=8888,Y0="127.0.0.1";async function N0($={}){let i=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):Q0),v=$.host??(process.env.HOST?process.env.HOST:Y0),u=PM(async(n,b)=>{try{await rY(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${l}) 已启动`),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 mY($,i,v={}){switch($){case"run":await ZM(i);return;case"start":return fY(i);case"stop":return xY(i,v);case"restart":return xY(i,{quiet:!0}),fY(i);case"logs":case"log":return VM(i);case"status":case void 0:return VJ(i);default:throw Error("用法: hose service <start|stop|restart|status|logs>")}}function VJ($){let i=Ev($),v=L0(i),u=v?oY(v,$.appRoot):!1;if(v&&!u)H6(i,{force:!0});let n=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):Q0),b=$.host??(process.env.HOST?process.env.HOST:Y0);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:Kn($)}}async function ZM($){let i=Ev($),v=Kn($);dY($.stateDir),qJ(i,`${process.pid}
`,{mode:384});let u=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):Q0),n=$.host??(process.env.HOST?process.env.HOST:Y0);Tv(v,`service starting on http://${n}:${u} pid=${process.pid}`);let b=null;try{b=await N0({port:u,host:n,silent:!0}),Tv(v,`service listening pid=${process.pid}`)}catch(U){if(Tv(v,`service failed to bind port ${u}: ${U instanceof Error?U.message:String(U)}`),L0(i)===process.pid)H6(i,{force:!0});throw U}let I=()=>{if(b)b.close(),b=null;if(L0(i)===process.pid)H6(i,{force:!0});Tv(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 fY($){dY($.stateDir);let i=VJ($);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=FM(v.command,u,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});n.unref();let b=Ev($);return qJ(b,`${n.pid}
`,{mode:384}),Tv(Kn($),`service started pid=${n.pid}`),{started:!0,...VJ($)}}function xY($,i={}){let v=Ev($),u=L0(v);if(!u||!oY(u,$.appRoot))return H6(v,{force:!0}),i.quiet?void 0:{stopped:!1,reason:"服务未处于运行状态"};try{process.kill(u,"SIGTERM")}catch{}return H6(v,{force:!0}),Tv(Kn($),`service stop requested pid=${u}`),i.quiet?void 0:{stopped:!0,pid:u}}function VM($,i=50){let v=Kn($);if(!yY(v))return{logFile:v,lines:[],content:"暂无服务运行日志"};let n=cY(v,"utf-8").trim().split(`
`).filter(Boolean).slice(-i);return{logFile:v,lines:n,content:n.join(`
`)}}function oY($,i){if(!qM($))return!1;try{let v=BM("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 qM($){try{return process.kill($,0),!0}catch{return!1}}function Ev($){return hY($.stateDir,"service.pid")}function Kn($){return hY($.stateDir,"service.log")}function L0($){if(!yY($))return;let i=Number(cY($,"utf-8").trim());return Number.isInteger(i)&&i>0?i:void 0}function dY($){SM($,{recursive:!0,mode:448})}function Tv($,i){qJ($,`${new Date().toISOString()} ${i}
`,{flag:"a",mode:384})}var kM=process.env.HOSE_STATE_DIR||pY(MM(),".config","hose-use");async function aY($,i){let v=$.action||$.args[0]||"status",u=m$($.options,["port","p"]),n=e($.options,["host","h"]),b={appRoot:i.appRoot||process.cwd(),entryFile:i.entryFile||pY(i.appRoot||process.cwd(),"src","cli.ts"),stateDir:kM,version:l,launcher:i.launcher,port:u,host:n},I=await mY(v,b);if(I===void 0)return{stdout:"",stderr:"",exitCode:0};if(i.jsonMode)return{stdout:E(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||Kn(b)};return{stdout:`====== hose-use 常驻服务管理 (Service) ======
${j$(w)}
`,stderr:"",exitCode:0}}async function eY($,i){let v=m$($.options,["port","p"]),u=e($.options,["host","h"]),n=await N0({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 TM=new Set(["http","server","web","mcp"]);function EM($){if(!$.length)return!1;let i=$[0]?.toLowerCase(),v=$[1]?.toLowerCase();if(TM.has(i))return!0;if((i==="service"||i==="daemon")&&v==="run")return!0;return!1}var sY=Promise.resolve(void 0);function K6($,i={}){if(EM($))return $N($,i);let v=sY.then(()=>lM($,i));return sY=v.then(()=>{return},()=>{return}),v}async function lM($,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 $N($,i),U=v.length?`${v.join(`
`)}
`:"",D=u.length?`${u.join(`
`)}
`:"";return{stdout:Mv(U+(I.stdout||"")),stderr:Mv(D+(I.stderr||"")),exitCode:I.exitCode}}finally{console.log=n,console.error=b}}async function $N($,i={}){let v=bY($);if(g$(v.options,["help","h"])||v.area==="help")return{stdout:NJ()+`
`,stderr:"",exitCode:0};if(g$(v.options,["version","v"])||v.area==="version")return{stdout:`hose-use v${l}
`,stderr:"",exitCode:0};let u=g$(v.options,["json","j"]),n=e(v.options,["corp","c"]),b=g$(v.options,["stateless"]),I=g$(v.options,["stateful"]),U=IY(v.options),D=DY({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 wY(v,D);case"corps":case"corp":return await WY(v,D);case"config":case"mode":return await gY(v,D);case"workflow":case"workflows":case"wf":return await JY(v,D);case"bill":case"bills":case"fee":case"fees":case"invoice":case"invoices":return await CY(v,D);case"platform":case"platforms":case"app":case"apps":return await XY(v,D);case"skill":case"skills":return await KY(v,D);case"probe":case"diagnose":return await HY(v,D);case"update":case"upgrade":case"self-update":case"changelog":return await TY(v,D,i);case"openapi":case"schema":case"spec":return await RY(v,D);case"http":case"server":case"web":return await eY(v,D);case"service":case"daemon":return await aY(v,D);case"mcp":return await PY(v,i);case void 0:return{stdout:NJ()+`
`,stderr:"",exitCode:0};default:return{stdout:"",stderr:`未知命令域: ${v.area}。运行 hose --help 查看帮助
`,exitCode:1}}}catch(w){let W=Mv(w instanceof Error?w.message:String(w));if(u)return{stdout:E({error:!0,message:W}),stderr:"",exitCode:1};return{stdout:"",stderr:`[ERROR] ${W}
`,exitCode:1}}}var MJ="hose_cli",RM="HOSE_MCP_MODE",CM="HOSE_USE_MCP_ENABLED",Hn=tM(import.meta.url),nN=Hn.includes("/dist/mcp/")||Hn.includes("\\dist\\mcp\\")?P6(P6(P6(Hn))):P6(P6(Hn));function _M($=process.env[CM]){if($===void 0)return!0;return["1","true","yes","on"].includes($.trim().toLowerCase())}function vN($=process.env[RM]){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 SJ($){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 ZJ($){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 z0($){let i=$.exitCode!==0,v=i?$.stderr||$.stdout||"Command failed":$.stdout||$.stderr||"Success";return v=Mv(v),{content:[{type:"text",text:v.trimEnd()}],isError:i}}function rM($){if($ instanceof IJ)return{content:[{type:"text",text:"未配置企业,请先添加企业配置或登录"}],isError:!0};if($ instanceof W$)return{content:[{type:"text",text:`认证失败: ${$.message}`}],isError:!0};if($ instanceof X6)return{content:[{type:"text",text:`错误 [${$.code}]: ${$.message}`}],isError:!0};if($ instanceof g.ZodError)return{content:[{type:"text",text:`参数错误: ${$.message}`}],isError:!0};return{content:[{type:"text",text:$ instanceof Error?$.message:"发生内部错误,请稍后重试"}],isError:!0}}function fM($={}){let i=$.enabled??_M(),v=$.mode??vN(),u=new rg({name:"hose-use",version:l},{capabilities:{tools:{}}}),n=[...JJ,...OJ,...YJ];return u.setRequestHandler(SW,async()=>{if(!i)return{tools:[]};let b=[];if(v==="single"||v==="all")b.push({name:MJ,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(Z4,async(b)=>{if(!i)return z0({stdout:"",stderr:"hose-use MCP 服务在插件配置中已被禁用 (HOSE_USE_MCP_ENABLED=false)",exitCode:1});let{name:I,arguments:U}=b.params;if(I===MJ){let D=U&&typeof U.command==="string"?U.command:void 0;if(!D?.trim())return z0({stdout:"",stderr:"hose_cli requires a non-empty command string",exitCode:1});try{let w=SJ(D),W=ZJ(w);if(!W.length)throw Error("hose_cli requires a non-empty command string");let J=await K6(W,{appRoot:nN,entryFile:Hn});return z0(J)}catch(w){return z0({stdout:"",stderr:w instanceof Error?w.message:String(w),exitCode:1})}}try{let D=Kv(),w=new u6(D),W=JJ.find((A)=>A.name===I);if(W){let A=W.parameters.safeParse(U||{});if(!A.success)return{content:[{type:"text",text:`参数错误: ${A.error.message}`}],isError:!0};let G=await W.handler({corpContext:w},A.data);return{content:[{type:"text",text:typeof G==="string"?G:JSON.stringify(G,null,2)}]}}let J=YJ.find((A)=>A.name===I);if(J){let A=J.parameters.safeParse(U||{});if(!A.success)return{content:[{type:"text",text:`参数错误: ${A.error.message}`}],isError:!0};let G=await J.handler({corpContext:w},A.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=OJ.find((A)=>A.name===I);if(O){let A=O.parameters.safeParse(U||{});if(!A.success)return{content:[{type:"text",text:`参数错误: ${A.error.message}`}],isError:!0};let G=await f$(X),{client:N}=await g0(X),L=await O.handler({corp:X,ekbClient:G,easoClient:N},A.data);return{content:[{type:"text",text:typeof L==="string"?L:JSON.stringify(L,null,2)}]}}return{content:[{type:"text",text:`未知工具: ${I}。在单工具网关模式下,请通过 ${MJ} 调用。`}],isError:!0}}catch(D){return rM(D)}}),u}async function xM(){let $=fM(),i=new xg;await $.connect(i),console.error(`hose-use MCP Server (v${l}) running on stdio [mode: ${vN()}]`)}async function yM(){let $=await K6(process.argv.slice(3),{appRoot:nN,entryFile:Hn});if($.stdout)process.stdout.write($.stdout);if($.stderr)process.stderr.write(`${$.stderr}${$.stderr.endsWith(`
`)?"":`
`}`);process.exitCode=$.exitCode}var cM=Boolean(EJ.main==EJ.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&iN(process.argv[1])===iN(Hn));if(cM)if(process.argv[2]==="--hose-use-cli"||process.argv[2]==="--hose-cli")await yM();else xM().catch(($)=>{console.error($),process.exitCode=1});export{SJ as tokenizeCommand,xM as startServer,vN as resolveMcpMode,_M as resolveMcpEnabled,ZJ as normalizeCliArgs,fM as createServer,z0 as cliResult,RM as HOSE_MCP_MODE_ENV,CM as HOSE_MCP_ENABLED_ENV,MJ 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
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: hose-use API & MCP Tools Specification
version: 0.5.0
version: 0.5.1
description: >-
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
servers:
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.5.0",
"version": "0.5.1",
"module": "src/server.ts",
"type": "module",
"bin": {
@@ -18,6 +18,7 @@
"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"
+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}`);
+9
View File
@@ -63,6 +63,15 @@ if (existsSync(openapiPath)) {
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)) {
+61 -178
View File
@@ -1,205 +1,88 @@
---
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.1)
`hose-use` 是面向合思/易快报 SaaS、开发者与 AI 智能体的高性能交互工具。
## 核心架构原则
- **纯 API 认证**:内置 RSA PKCS#1 密码加密与统一认证中心握手,无需浏览器滑块即可登录。
- **全自动无感续杯**:内置 401 拦截与预检换票机制,Token 到期自动刷新并重试,零人工介入。
- **多账号与多身份分层**:支持一个手机号管理 13+ 家企业;支持同一企业下多身份(`corpId@accountId`)共存。
- **有状态 / 无状态双模式**:
- **有状态 (Stateful)**:自动记忆默认企业,命令无需反复加 `--corp`。
- **无状态 (Stateless)**:严格要求 `--corp <corpId>`,防止多租户或 Agent 误操作。
- **MCP 单工具网关架构**:统一暴露 `hose_cli` 工具,避免数十个细粒度工具膨胀污染 Agent 的上下文,零子进程同构执行。
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
---
## 调用通道与执行协议
## Agent 执行原则 (First Rules)
`hose-use` 同时支持 **MCP 工具** 与 **Shell CLI** 两种调用通道:
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>`),避免多任务并发切换全局状态发生冲突。
- **MCP 工具通道 (AI Agent 优先推荐)**:在具备 MCP 的智能体环境中,优先调用 `hose_cli` 工具网关:
```json
{
"command": "corps list"
}
```
或者执行业务检索:
```json
{
"command": "bill query --code BX20260901001 --corp ID01MCcOgJl1td"
}
```
- **Shell CLI 通道 (运维/终端/脚本)**:在终端或子进程环境中,直接执行:
```bash
hose corps list
# 或
hose-use bill query --code BX20260901001
```
---
## 意图路由导航 (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) |
| 单据实体模型与字段元数据查询 | `hose bill schema` | [references/bill.md](references/bill.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 uzU7pcWfScck00 # 切换工作企业
hose probe # 诊断当前企业接口连通性
# 导入 F12 抓包复制的 cURL 或 Request Headers
hose-use auth import --raw="curl ..."
# 2. 单据与费用
hose bill list # 查看最新单据与报销记录
hose bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘
hose bill get n0GMIM0dkQmKbS # 精准查询单据详情 (中文字段映射)
hose bill schema # 查询单据实体元数据字典
# 查看当前登录状态与活跃账号
hose-use auth status
# 3. 自建应用与工作流
hose platform list # 查看自建应用列表
hose workflow list # 聚合扫描全部应用下的工作流
hose workflow find --task=code-js2 # 查找部署了代码节点的工作流
hose workflow get wf_01k83y... # 查看指定工作流节点拓扑
# 一键批量刷新名下所有企业的最新 30 天 AccessToken
hose-use auth refresh
# 查看已保存的全部主账号
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
# 查看多级企业目录发现路径与诊断
hose-use config paths
# 切换为无状态模式 (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. 单据与费用明细检索 (`hose-use bill`)
```bash
# 查看企业单据与报销列表 (支持分页/阶段/状态过滤)
hose-use bill list
hose-use bill list --stage=expense --state=paid --count=10
# 大数据量防爆落盘: 使用 -o / --output-file 将完整 JSON 转储至本地文件 (推荐 Agent 处理海量数据时使用)
hose-use bill list --json -o /tmp/bills.json
# 确需向终端输出完整大报文时附加 --full (跳过 200KB 防爆限制)
hose-use bill list --json --full
# 根据单号或 ID 精确查询单据结构化详情 (DataLink 字典自动还原)
hose-use bill get n0GMIM0dkQmKbS
hose-use bill get ID01TRzg7HMLcb
# 查看企业全部单据实体与数据模型字典
hose-use bill schema
```
### 6. 诊断与 MCP 服务 (`hose-use probe` / `hose-use mcp`)
```bash
# 连通性与 EASO 平台鉴权诊断
hose-use probe
hose-use probe --corp=uzU7pcWfScck00
# 启动极简 MCP stdio 服务
hose-use mcp serve
```
### 7. OpenAPI 规范导出 (`hose-use 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/Agent)
hose-use openapi
# 输出原生下游全量 OpenAPI 3.1.0 JSON
hose-use openapi --raw
```
### 8. HTTP 服务与常驻守护进程 (`hose-use http` / `hose-use service`)
```bash
# 启动本地轻量 HTTP 服务并打开 Scalar 交互式文档 (http://127.0.0.1:8888/docs)
hose-use http --port=8888
# 后台启动常驻守护进程服务
hose-use service start
# 查看常驻守护进程运行状态与端点
hose-use service status
# 查看常驻守护进程最近运行日志
hose-use service logs
# 停止后台常驻守护进程
hose-use service stop
```
### 9. 自更新与版本历史 (`hose-use update`)
```bash
# 检查最新可用版本与 Release Notes
hose-use update --check
# 一键自动下载并升级到最新版本(多源 CDN 加速 + 自动同步 Agent 技能)
hose-use update
# 查看最近版本发布历史与更新说明
hose-use update --changelog
# 4. 服务与守护进程
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` 自动清洗过滤,保障会话与调用日志安全。
+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
```
+45
View File
@@ -0,0 +1,45 @@
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");
});
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(6);
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", "workflow.md"))).toBe(true);
expect(existsSync(join(tmp, "references", "service.md"))).toBe(true);
} finally {
rmSync(tmp, { recursive: true, force: true });
}
});
});
+12 -1
View File
@@ -1,10 +1,21 @@
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" };
export const EMBEDDED_SKILL_FILES: Record<string, string> = {
"SKILL.md": skillMain,
"agents/openai.yaml": agentOpenAi,
"references/auth.md": refAuth,
"references/bill.md": refBill,
"references/workflow.md": refWorkflow,
"references/service.md": refService,
};
export function getSkillContent(): string {
+26
View File
@@ -153,4 +153,30 @@ describe("hose-use MCP server & hose_cli single-gate pattern", () => {
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()]);
}
});
});
+21 -2
View File
@@ -22,11 +22,19 @@ 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 = dirname(dirname(serverEntryFile));
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";
@@ -165,7 +173,8 @@ function formatError(error: unknown): {
};
}
export function createServer(options: { mode?: HoseMcpMode } = {}) {
export function createServer(options: { mode?: HoseMcpMode; enabled?: boolean } = {}) {
const enabled = options.enabled ?? resolveMcpEnabled();
const mode = options.mode ?? resolveMcpMode();
const server = new Server(
@@ -184,6 +193,9 @@ export function createServer(options: { mode?: HoseMcpMode } = {}) {
// 注册工具列表
server.setRequestHandler(ListToolsRequestSchema, async () => {
if (!enabled) {
return { tools: [] };
}
const tools: Array<{ name: string; description?: string; inputSchema: any }> = [];
// 单工具网关
@@ -223,6 +235,13 @@ export function createServer(options: { mode?: HoseMcpMode } = {}) {
// 处理工具调用
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 网关工具调用
+1 -1
View File
@@ -1 +1 @@
export const VERSION = "0.5.0";
export const VERSION = "0.5.1";