@baocang/zentao-cli 0.5.1-enh.1 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +0 -3
- package/README.md +0 -3
- package/dist/index.js +101 -105
- package/package.json +4 -7
- package/skills/zentao-cli/SKILL.md +4 -26
- package/skills/zentao-cli/agents/openai.yaml +5 -0
- package/skills/zentao-cli/references/writes.md +0 -10
- package/skills/zentao-tour/SKILL.md +2 -2
- package/skills/zentao-tour/roles/dev.md +2 -2
- package/skills/zentao-tour/roles/test.md +1 -1
package/dist/index.js
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
var E=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(o){n=[o]}if(n)throw n[0];return t};function l(e,...t){if(typeof e!=="string")return e.reduce((n,o,r)=>n+l(o)+(r<t.length?String(t[r]):""),"");return dn(e,void 0)}function dn(e,t){if(!t)return e;let n=t;return e.replace(/https:\/\/www\.zentao\.net\//g,n.homepage).replace(/zentao-api/g,"\x00sdk\x00").replace(/ZenTao-Action-Assistant/g,"\x00assistant-header\x00").replace(/zentao-cli/g,n.packageName).replace(/禅道|禪道|ZenTao|Zentao/g,n.displayName).replace(/ZENTAO/g,n.commandName.toUpperCase()).replace(/zentao/g,n.commandName).replace(/\u0000sdk\u0000/g,"zentao-api").replace(/\u0000assistant-header\u0000/g,"ZenTao-Action-Assistant")}function je(e,t=!1,n=void 0){if(!n||e===null||typeof e!=="object")return t&&typeof e==="string"?dn(e,n):e;let o=mr.get(n);if(!o)mr.set(n,o=new WeakMap);if(!t&&o.has(e))return o.get(e);let r=Array.isArray(e)?e.map((i)=>je(i,t,n)):Object.fromEntries(Object.entries(e).map(([i,s])=>[i,typeof s==="string"&&(t||["display","description","label","title"].includes(i))?dn(s,n):je(s,t||i==="examples"||i==="example",n)]));if(Object.freeze(r),!t)o.set(e,r);return r}function Pt(e,t){return(void 0)?.logoSvg?(void 0).logoSvg.replace("<svg ",`<svg class="${t}" aria-hidden="true" `):e}function gr(e,...t){return e.raw.reduce((n,o,r)=>n+l(o)+(r<t.length?String(t[r]):""),"")}var ke=void 0,mr;var L=E(()=>{mr=new WeakMap});import{extendModuleAction as qi,getModule as hr,getModuleAction as yr,getModuleNames as br,getObjectProps as Wi,getModuleActionParams as Gi}from"zentao-api";function me(e){if(!e)return;try{return je(hr(e))}catch{return}}function wr(){return br()}function vr(){return br().map((e)=>je(hr(e)))}function kr(e){return Object.fromEntries(Object.entries(Wi(e)??{}).map(([t,n])=>[t,l(n)]))}function De(e,t){return je(yr(e.name,t))}var ge=(e,t,n)=>{let o=Gi(e,t,n);if(o.some((r)=>r.role==="body"&&r.textType==="html")&&!o.some((r)=>r.name==="uid")){let r=yr(e,t),i=r.method?.toUpperCase();if((i==="POST"||i==="PUT")&&(r.requestBody?.mediaType??"application/json")==="application/json")o.push({name:"uid",role:"body",type:"string",required:!1,description:"预上传图片的批次标识。使用上传时的 Token 和 uid 保存单个对象以绑定图片。需 23.0 / biz14.0 / max9.0 / ipd6.0 或更新版本。"})}return je(o)};var xe=E(()=>{L();qi("file","get",(e)=>{let t=e.beforeRequest;return{...e,beforeRequest(n){let o=n.params.fileID;if(n.params.id===void 0&&typeof o==="string"&&!/^\d+$/.test(o))n.path=e.path.replace("{fileID}",o);return t(n)}}})});import{ERRORS as Vi}from"zentao-api";function xr(e){if(!e||typeof e!=="object")return!1;let t=e.code;return typeof t==="string"&&t.startsWith("E_")}function ln(e){return typeof e==="number"&&Number.isSafeInteger(e)&&e>0}function zr(e){return typeof e==="string"&&e.length>0&&!/[^A-Za-z0-9_-]/.test(e)}function X(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e,n=zr(t.uid)?t.uid:void 0,o=Array.isArray(t.fileIDs)?t.fileIDs.filter(ln):[],r=[];if(Array.isArray(t.fileWarnings))for(let i of t.fileWarnings){if(!i||typeof i!=="object")continue;let{stage:s,code:a,message:d}=i;if(s!=="resolve"&&s!=="upload"&&s!=="cleanup"||typeof a!=="string"||typeof d!=="string")continue;let u={stage:s,code:a,message:d};for(let m of["field","path","name","objectType"])if(typeof i[m]==="string")u[m]=i[m];if(ln(i.fileID))u.fileID=i.fileID;if(ln(i.objectID))u.objectID=i.objectID;if(zr(i.uid))u.uid=i.uid;r.push(u)}if(!n&&!o.length&&!r.length)return;return{...n&&{uid:n},...o.length>0&&{fileIDs:o},...r.length>0&&{fileWarnings:r}}}function N(e,t=!1){if(e instanceof c)return e;if(!xr(e))return e;let{code:n,message:o,details:r}=e,i=e.params??{},s=r&&typeof r==="object"?r:{};switch(n){case"E_HTTP_ERROR":{let a=Number(s.status),d=typeof s.url==="string"?s.url:"";if(a===401)return new c("E1004",void 0,r);if(a===403)return new c("E2006",void 0,r);if(a===404)return new c("E2002",{object:d},r);return new c("E2008",{url:d,status:String(s.status??""),serverResponse:typeof s.body==="string"?s.body:String(s.body??"")},r)}case"E_TIMEOUT":return new c("E5001",void 0,r);case"E_ABORTED":return new c("E5003",void 0,r);case"E_NETWORK_ERROR":{let a=(typeof s.message==="string"?s.message:o)??"";if(a.includes("SSL")||a.includes("TLS")||a.includes("certificate"))return new c("E5002",void 0,r);return new c("E1002",{url:""},r)}case"E_API_FAILED":return new c("E2008",{url:"",status:"",serverResponse:String(i.message??s.message??"")},r);case"E_LOGIN_FAILED":return new c("E1003",void 0,r);case"E_UNSUPPORTED_ZENTAO_VERSION":return new c("E2010",{action:String(s.action??""),version:String(s.version??""),minVersion:Array.isArray(s.minVersion)?s.minVersion.join(" / "):String(s.minVersion??"")},r);case"E_INVALID_ZENTAO_VERSION":return new c("E2011",{version:String(i.version??"")},r);case"E_INVALID_ZENTAO_CONFIG":return new c("E2012",void 0,r);case"E_FILE_RESOLVE_FAILED":return new c("E2013",{path:String(i.path??"")},X(r));case"E_FILE_UPLOAD_FAILED":return new c("E2014",void 0,X(r));case"E_FILE_SESSION_CHANGED":return new c("E2015",void 0,X(r));case"E_FILE_SAVE_UNCONFIRMED":{let a=X(r);if(!t)return new c("E2016",void 0,a);let d=e,u=new Set;while(!u.has(d)&&xr(d.cause)&&d.cause.code===n)u.add(d),d=d.cause;return new c("E2016",void 0,{response:d.details,...a})}case"E_MISSING_PARAM":return new c("E2003",{fields:String(i.param??""),module:""},r);case"E_INVALID_PARAM":{let a=String(i.param??""),d=String(i.value??"");return new c("E2004",{field:a??"",value:d??""},r)}case"E_INVALID_MODULE":return new c("E2001",{module:String(i.module??"")},r);case"E_INVALID_ACTION":case"E_INVALID_REQUEST_NAME":return new c("E2005",{module:""},r);case"E_NO_PROFILE":case"E_NO_GLOBAL_CLIENT":return new c("E1006",void 0,r);case"E_PROFILE_NOT_FOUND":return new c("E1007",void 0,r);default:return new c("E2008",{url:"",status:"",serverResponse:Ki(e)},r)}}function Ki(e){let t=Vi[e.code];if(!t)return e.message??String(e.code);return Tr(l(t),e.params)}function Tr(e,t){return e.replace(/\{([^{}]+)\}/g,(n,o)=>t&&Object.hasOwn(t,o)?String(t[o]):n)}function It(e,t){if(t==="json"||t==="raw"){let i={ok:!1,error:{code:e.code,message:e.message}};if(e.details)i.error={...i.error,details:e.details};return JSON.stringify(i,null,4)}let n=`Error(E${e.code}): ${e.message}`,o=X(e.details);if(!o?.uid&&!o?.fileIDs?.length)return n;let r=[o.uid&&`uid=${o.uid}`,o.fileIDs?.length&&`fileIDs=${o.fileIDs.join(",")}`].filter(Boolean).join(",");return`${n}
|
|
2
|
-
附件上传批次(${r})。重试前请先核对对象的保存结果和附件归属。`}var Ji,c;var T=E(()=>{L();Ji={E1001:l("必须提供有效的禅道服务地址、用户名和密码或 TOKEN"),E1002:l("所提供的禅道服务地址 {url} 无法访问"),E1003:"当前用户名和密码不正确",E1004:"所提供的 Token 已失效,请提供密码重新登录,或提供新的 TOKEN",E1005:"配置文件损坏或无法读取,请检查 {path}",E1006:l("未找到可用的用户配置,请执行 `zentao login --web` 在浏览器中登录;终端登录使用 `zentao login --no-browser`"),E1007:l("指定的用户配置不存在,请通过 `zentao profile list` 查看可用配置"),E1008:"浏览器登录已取消",E1009:l("浏览器登录等待超时,请重新执行 `zentao login --web`"),E1010:l("无法启动本地登录服务,请检查本机网络权限,或使用 `zentao login --no-browser`"),E1011:"配置文件写入失败,请检查 {path} 的目录权限和磁盘空间",E1012:l("未能确认远端会话已撤销,已保留本地登录记录,请重试或联系禅道管理员"),E1013:"Token 所属账号为 {actual},与指定账号 {account} 不一致",E2001:l("未找到指定的模块 {module},请通过 `zentao help` 查看支持的模块"),E2002:"未找到指定的对象 {object},请检查对象 ID 是否正确",E2003:l("缺少必要参数 {fields},请通过 `zentao {module} --help` 查看必要参数"),E2004:"{field} 参数值 {value} 无效,请检查参数格式是否正确",E2005:l("不支持的操作,请通过 `zentao {module} --help` 查看支持的操作"),E2006:"当前用户没有权限执行此操作",E2007:"`--data` 参数中的 JSON 数据格式无效",E2008:l("禅道服务端返回错误(Url:{url},Status:{status}),请查看详细错误信息:{serverResponse}"),E2009:"选项 {option} 的值无效,{reason}",E2010:l("操作 {action} 不支持当前禅道版本 {version},最低版本要求:{minVersion},请升级对应系列的禅道版本"),E2011:l("无法识别禅道版本 {version},仅支持点分数字的正式版本(如 22.5、biz13.5、max8.5、ipd5.5)"),E2012:l("无法识别禅道服务端配置,请检查站点根地址的 ?mode=getconfig 是否返回包含 version 的 JSON 对象"),E2013:"无法解析富文本图片引用 {path}",E2014:"上传响应未提供有效的附件 ID",E2015:"图片上传期间登录会话已改变,本次操作已中止",E2016:"服务端未确认本次对象的保存结果",E5001:l("请求超时,请检查网络连接或禅道服务是否正常"),E5002:l("SSL/TLS 证书验证失败,请检查禅道服务地址是否正确"),E5003:"请求已取消",E5004:"无法启动 MCP HTTP 服务:{reason}",E5005:"无法写入附件 {path}:{reason}"};c=class c extends Error{code;details;constructor(e,t,n){let o=Tr(Ji[e],t);super(o);this.name=l("ZentaoError"),this.code=e.replace("E",""),this.details=n}}});function ut(e){return e.replace(/^[a-zA-Z]+_(\d+)$/,"$1")}function he(e){return Object.keys(e.pathParams??{}).find((t)=>t.endsWith("ID")&&t!=="scopeID")}function Je(e){return["get","update","delete","action"].includes(e.type)&&Boolean(he(e))}function Ot(e,t,n){let o=(a)=>{throw new c("E2009",{option:"ids",reason:a})},r=he(e);for(let a of["id",...Object.keys(e.pathParams??{}).filter((d)=>d.endsWith("ID"))])if(t[a]!==void 0&&(Array.isArray(t[a])||String(t[a]).includes(",")))o("单个目标不接受多个 ID,请使用 --ids");if(t.id!==void 0&&!r)o("此操作没有对象 ID");if(n===void 0)return;if(!Je(e))o("此操作不支持批量对象操作");if(t.id!==void 0||r&&t[r]!==void 0)o("--ids 不能与单个目标同时使用");let i=n.split(",").map((a)=>ut(a.trim()));if(!i.length||i.some((a)=>!/^\d+$/.test(a)||!Number.isSafeInteger(Number(a))||Number(a)<1))o("每个 ID 必须为正安全整数");let s=[...new Set(i.map(Number))];if(s.length>1&&(t.uid!==void 0||t.data&&typeof t.data==="object"&&Object.hasOwn(t.data,"uid")))o("同一预上传 uid 只能绑定一个对象,请为每个对象分别上传和保存");return s}var Ke=E(()=>{T()});import{extractFileIdFromUrl as Yi}from"zentao-api";function ae(e,t){return e==="file"&&(t==="get"||t==="read")}function un(){return new c("E2009",{option:"url",reason:"请提供当前站点的附件读取或下载链接"})}function Ne(e,t){let n=Yi(e,t);if(n===void 0)throw un();return n}function Cr(e,t){if(!/^(?:https?:)?\/\//i.test(e.trim()))return Ne(e);if(!t)throw un();let n;try{n=new URL(e,"https://zentao.invalid/").origin}catch{throw un()}let o=Ne(e,n);return t(e),o}var Ye=E(()=>{T()});function Oe(e){return e.replace(/IDs\b/g,"Ids").replace(/([A-Z]+)([A-Z][a-z])/g,"$1-$2").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function Xi(e){let t=Oe(e);return`--${["deadline","timeout","profile","config","format","color","input","yes","quiet","insecure","assistant","data","ids","fields","markdown","all","max-items","filter","sort","search"].includes(t)?"data-":""}${t}`}function pn(e,t,n){if(!n.endsWith("ID"))return;return e.name==="file"&&t.name==="get"&&n==="fileID"?["integer","string"]:"integer"}function Sr(e,t,n=ge(e.name,t.name)){let o=t.requestBody?.schema.properties;return n.map((r)=>({...r,...r.role==="body"?o?.[r.name]:{},type:(r.role==="body"?o?.[r.name]?.type:void 0)??r.type??(r.role==="path"?pn(e,t,r.name):void 0)??"string"}))}function _e(e,t,n){if(t.type!=="list"||!t.pagerGetter)return;let o=n??Sr(e,t),r=o.find((s)=>["pageID","page"].includes(s.name)),i=o.find((s)=>["recPerPage","limit"].includes(s.name));return r&&i?{page:r,size:i}:void 0}function pt(e,t){return t.type==="update"&&!(e.name==="file"&&t.name==="update")&&e.actions.some((n)=>n.type==="get"&&n.path===t.path)}function fn(e){if(!e)return[];if(e==="user")return["id","account","realname","dept","role","status"];return["id","title","name","status",...e==="bug"?["severity"]:[],"assignedTo"]}function mn(e,t,n=ge(e,t)){return n.filter((o)=>o.role==="body"&&o.type==="string"&&(o.textType==="html"||e==="weekly"&&t==="update"&&o.name==="content")).map((o)=>o.name)}function Me(e,t,n=ge(e.name,t.name)){let o=Sr(e,t,n),r=_e(e,t,o),i=o.find((a)=>a.role==="path"&&!["scope","scopeID"].includes(a.name)),s=t.description;if(ae(e.name,t.name))s=t.name==="get"?"查询附件元数据。位置参数接受数字 ID、Base64 gid 或当前站点的附件 URL。":"读取附件内容。位置参数接受数字 ID 或当前站点的附件 URL。CLI 默认输出 Base64,--format=raw 保留服务端字节或文本。使用 --output <path> 将原始附件流式保存到文件。";return{module:e.name,action:t.name,command:`${e.name} ${Oe(t.name)}`,display:t.display,type:t.type,description:s,path:t.path,method:t.method,minVersion:t.minVersion,parameters:o.map((a)=>({...a,flag:Xi(a.name)})),markdownFields:mn(e.name,t.name,o),target:i?.name,batch:Je(t),pagination:r?{page:r.page.name,pageSize:r.size.name}:null,requestBody:t.requestBody,readOnly:Mt(t),destructive:!Mt(t)&&["update","delete","action"].includes(t.type),autoFill:pt(e,t),resultObjectType:t.resultObjectType,defaultFields:fn(typeof t.resultObjectType==="string"?t.resultObjectType:void 0),localFiles:t.requestBody?.mediaType==="multipart/form-data"}}function Mt(e){return(e.type==="list"||e.type==="get")&&(e.method??"get").toLowerCase()==="get"||e.type==="list"&&["/ai/knowledges/search","/ai/knowledges/embeddingssearch"].includes(e.path)}var Te=E(()=>{xe();Ke();Ye()});import{z as ye}from"zod";var gn,Er,ft,Q;var mt=E(()=>{gn=["table","json","markdown","raw"],Er=ye.number().int().positive().max(1000),ft=ye.object({autoAssistant:ye.boolean(),defaultOutputFormat:ye.enum(gn),defaultRecPerPage:Er,insecure:ye.boolean(),timeout:ye.number().int().positive(),htmlToMarkdown:ye.boolean(),batchFailFast:ye.boolean(),pagers:ye.record(ye.string(),Er),jsonPretty:ye.boolean()}),Q={autoAssistant:!0,defaultOutputFormat:"table",defaultRecPerPage:20,insecure:!1,timeout:1e4,htmlToMarkdown:!0,batchFailFast:!1,pagers:{},jsonPretty:!1}});import{existsSync as os,readFileSync as is}from"node:fs";import{dirname as ss,join as hn}from"node:path";import{fileURLToPath as as}from"node:url";function ce(){return"0.5.1-enh.1"}var Fe=()=>{};function Qe(e){try{if(typeof e!=="string")throw TypeError();new Headers({"ZenTao-Action-Assistant":e})}catch{throw new c("E2009",{option:"assistant",reason:"标记必须是有效的 HTTP 请求头字符串,不能包含换行或中文等非 Latin-1 字符"})}return e}function H(e,t=!0,n="cli"){return e!==void 0?Qe(e):t?cs[n]:""}var yn,cs;var be=E(()=>{L();T();Fe();yn=`${ke?.packageName??"zentao-cli"} ${ce()}`,cs={cli:`CLI <${yn}>`,stdio:`AI <${yn}, mcp: stdio>`,http:`AI <${yn}, mcp: http>`}});function ps(e){return typeof e==="string"&&ds.test(e)&&ls.test(e)&&us.test(e)}function yt(e){if(ps(e))throw new c("E1004",void 0,{responseType:"login-page"})}async function Mr(e){let t=e instanceof Blob?await e.slice(0,ht).arrayBuffer():e.slice(0,ht),n=new TextDecoder().decode(new Uint8Array(t));yt(n)}async function Rr(e){let t=e.headers.get("Content-Disposition")??"";if(/\battachment\b/i.test(t))return;let n=e.headers.get("Content-Type")??"";if(!/\b(?:text\/html|application\/xhtml\+xml)\b/i.test(n))return;let o=e.clone().body?.getReader();if(!o)return;let r=new TextDecoder,i="",s=0;try{while(s<ht){let a=await o.read();if(a.done){yt(i+r.decode());return}let d=ht-s,u=a.value.subarray(0,d);s+=u.byteLength,i+=r.decode(u,{stream:s<ht}),yt(i)}}catch(a){if(a instanceof DOMException&&a.name==="AbortError")throw new c("E5001",void 0,a);throw a}finally{o.cancel().catch(()=>{return})}}var ds,ls,us,ht=65536;var Lr=E(()=>{T();ds=/^\s*<!doctype\s+html\b|^\s*<html\b/i,ls=/(?:id|name)\s*=\s*["']loginForm["']|user-login(?:\.html)?/i,us=/<input\b[^>]*\bname\s*=\s*["']account["'][^>]*>/i});import{ZentaoClient as fs}from"zentao-api";function U(e,t,n){return new $r({baseUrl:e,token:t,insecure:n?.insecure,timeout:n?.timeout,actionAssistant:n?.actionAssistant??H()})}function ee(e,t){if(!t)return e;let n=(r)=>{let i=("signal"in r?r.signal:void 0)??t;if(i.aborted)throw new c("E5003");return{...r,signal:i}},o={request:(r,i={})=>e.request(r,n(i)),fetch:(r,i,s,a)=>e.fetch(r,n(i),s,a),getZentaoConfig:(r={})=>e.getZentaoConfig(n(r))};return new Proxy(e,{get(r,i,s){return Object.hasOwn(o,i)?Reflect.get(o,i):Reflect.get(r,i,s)}})}async function bt(e){try{return await e.getZentaoConfig()}catch(t){throw N(t)}}var $r;var de=E(()=>{be();T();Lr();$r=class $r extends fs{async request(e,t){let n=await super.request(e,t);if(n instanceof Response)await Rr(n);else if(n instanceof ArrayBuffer||n instanceof Blob)await Mr(n);else yt(n);return n}}});import ms from"configstore";import{chmodSync as gs,existsSync as hs,mkdirSync as jr,rmdirSync as ys}from"node:fs";import{dirname as bs,isAbsolute as Dr,join as bn,resolve as ws}from"node:path";import{homedir as wn}from"node:os";import{z as te}from"zod";function ks(){let e=process.env.XDG_CONFIG_HOME;return bn(e&&Dr(e)?e:bn(wn(),".config"),l("zentao"),l("zentao.json"))}function Nr(){if(!Rt)Rt=new ms(l("zentao-cli"),void 0,{configPath:B,clearInvalidConfig:!1});return Rt}function xs(){try{if(hs(B))gs(B,384)}catch{}}function zs(e){try{Nr().set(e),xs()}catch(t){let n=t?.code;throw new c("E1011",{path:B},{operation:"write",reason:"write_failed",path:B,...n?{systemCode:n}:{}})}}function Lt(e){let t=`${B}.lock`,n=!1;try{jr(bs(B),{recursive:!0,mode:448});let o=Date.now()+5000;while(!n)try{jr(t,{mode:448}),n=!0}catch(s){if(s.code!=="EEXIST")throw s;if(Date.now()>=o)throw new c("E1011",{path:B},{reason:"lock_timeout",path:t});Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}let r=Re(),i=e(r);return zs(r),i}catch(o){if(o instanceof c)throw o;throw new c("E1011",{path:B},{operation:"write",reason:"write_failed",path:B,systemCode:o.code})}finally{if(n)ys(t)}}function Ts(e){if(e==="~")return wn();if(e.startsWith("~/")||e.startsWith("~\\"))return bn(wn(),e.slice(2));return e}function _r(e){if(typeof e!=="string"||e.trim()==="")throw Error("setConfigPath: path must be a non-empty string");let t=Ts(e),n=Dr(t)?t:ws(t);if(Rt&&n!==B)throw Error("setConfigPath: cannot change config path after store has been initialized");B=n}function Re(){let e;try{e=Nr().all}catch(t){let n=t?.code;throw new c("E1005",{path:B},{operation:"read",reason:t instanceof SyntaxError?"invalid_json":"unreadable",path:B,...n?{systemCode:n}:{}})}if(!vs.safeParse(e).success)throw new c("E1005",{path:B},{operation:"read",reason:"invalid_structure",path:B});return e}function Z(e,t){return`${e}@${t}`}function V(e){return e.replace(/\/+$/,"")}function we(e=Re()){if(!e.currentProfile||!e.profiles?.length)return;return e.profiles.find((t)=>Z(t.account,t.server)===e.currentProfile)}function et(e,t){let n=Re(),o=V(t);return n.profiles?.find((r)=>r.account===e&&V(r.server)===o)}function J(e,t=Re()){let n=t.profiles??[],o=n.find((i)=>Z(i.account,i.server)===e);if(o)return o;let r=n.filter((i)=>i.account===e||`${i.account}@${new URL(i.server).hostname}`===e);if(r.length>1)throw new c("E2009",{option:"profile",reason:"账号简写不唯一,请指定完整 key"},{candidates:r.map((i)=>Z(i.account,i.server))});return r[0]}function tt(e){Lt((t)=>{let n=V(e.server),o=(d)=>d.account===e.account&&V(d.server)===n,r=t.profiles?.find(o),i={...r,...e,server:n,config:r?.config??e.config,user:r?.user||e.user?{...r?.user,...e.user}:void 0,serverConfig:e.serverConfig??r?.serverConfig},s=t.profiles??[],a=s.findIndex(o);t.profiles=s.filter((d)=>!o(d)),t.profiles.splice(a<0?t.profiles.length:a,0,i)})}function $t(e,t){return Lt((n)=>{let o=n.profiles??[];if(n.profiles=o.filter((r)=>Z(r.account,r.server)!==e||t!==void 0&&r.token!==t),n.currentProfile===e&&!n.profiles.some((r)=>Z(r.account,r.server)===e))n.currentProfile=void 0;return n.profiles.length!==o.length})}function wt(e){return Lt((t)=>{let n=J(e,t);if(!n)return;return t.currentProfile=Z(n.account,n.server),n})}function Fr(){return Re().profiles??[]}function K(e){return{...Q,...e.config}}function vn(e,t,n){Lt((o)=>{let r=o.profiles?.find((i)=>i.account===e.account&&i.server===e.server);if(!r)throw new c("E1007");if(r.config??={},n===void 0)delete r.config[t];else r.config[t]=n})}function jt(){return B}function Ce(e,t,n,o,r,i){let s=new Date().toISOString();return{...i,server:V(e),account:t,token:n,user:i?{...i.user,...r}:r,loginTime:s,lastUsedTime:s,serverConfig:o??i?.serverConfig}}var vs,B,Rt=null;var Y=E(()=>{L();T();mt();vs=te.object({currentProfile:te.string().optional(),profiles:te.array(te.object({server:te.string().url(),account:te.string(),token:te.string(),loginTime:te.string().optional(),lastUsedTime:te.string().optional(),user:te.record(te.string(),te.unknown()).optional(),config:ft.partial().passthrough().optional(),serverConfig:te.object({version:te.string()}).passthrough().optional()}).passthrough()).optional()}).passthrough();B=ks()});function I(){return Dt?.signal}function Ur(){return Nt}function Hr(e){Dt=new AbortController,Nt=void 0;let t=()=>{Nt="interrupt",Dt.abort(new c("E5003"))};process.once("SIGINT",t);let n=e.deadline?setTimeout(()=>{Nt="deadline",Dt.abort(new c("E5001"))},e.deadline):void 0;return n?.unref(),()=>{clearTimeout(n),process.removeListener("SIGINT",t)}}var Dt,Nt;var ne=E(()=>{T()});import{getModuleAction as Cs,request as Br}from"zentao-api";function kn(e){return Boolean(Cs("my","profile",{version:e}))}async function vt(e,t,n){let{version:o}=await bt(e);if(kn(o)){let{data:a}=await Br("my/profile",{},{client:e,throwOnFail:!0,actionAssistant:n});if(typeof a?.account!=="string"||!a.account.trim())throw new c("E2008",{url:e.siteUrl,status:"",serverResponse:"my/profile 未返回当前用户的有效账号"});if(t!==void 0&&t!==a.account)throw new c("E1013",{account:t,actual:a.account});return{user:a,hadUsers:!0}}if(t===void 0)return{hadUsers:!1};let r,i=!1,s;for(let a=1;;a++){let d=await Br("user/list",{browseType:"inside",orderBy:"id_asc",recPerPage:100,pageID:a,filters:[{field:"account",operator:"=",value:t}]},{client:e,throwOnFail:!0,actionAssistant:n}),u=Array.isArray(d.data)?d.data:[];if(i||=u.length>0,r=u.find((p)=>p.account===t),r||!u.length)break;let m=JSON.stringify(u.map((p)=>[p.id,p.account]));if(m===s||d.pager&&d.pager.page!==a)throw new c("E2008",{url:e.siteUrl,status:"",serverResponse:"用户列表分页未向前推进,无法确认当前用户详情"});if(s=m,d.pager?a*d.pager.recPerPage>=d.pager.total:u.length<100)break}return{user:r,hadUsers:i}}var xn=E(()=>{de();T()});import{readFileSync as Ss,statSync as Es}from"node:fs";function nt({password:e,token:t},n=!1){if(e&&(n||!t))return{type:"password",value:e};if(t)return{type:"token",value:t};throw new c("E1001")}async function Ue(e,t,n,o){let r=U(e,void 0,o),i=ee(r,o?.signal),s;try{s=await i.login(t,n)}catch(u){throw N(u)}let a,d=await bt(i);try{({user:a}=await vt(i,t))}catch(u){if(kn(d.version))throw N(u)}if(o?.signal?.aborted)throw new c("E5003");return{client:r,token:s,user:a,serverConfig:d}}async function Zr(e,t){try{let n=await bt(e),{user:o,hadUsers:r}=await vt(e,t);if(!r)throw new c("E1004");return{serverConfig:n,user:o}}catch(n){throw N(n)}}function He(){let e={url:process.env[l("ZENTAO_URL")],account:process.env[l("ZENTAO_ACCOUNT")],password:process.env[l("ZENTAO_PASSWORD")],token:process.env[l("ZENTAO_TOKEN")]},t=process.env[l("ZENTAO_CREDENTIALS_FILE")];if(!t?.trim())return e;let n={};try{let s=Es(t).mode&511;if(process.platform!=="win32"&&s&63)throw new c("E2009",{option:"ZENTAO_CREDENTIALS_FILE",reason:`凭据文件权限过宽 (${s.toString(8)}),仅允许属主读写,请执行 chmod 600 ${t}`});n=Object.fromEntries(Ss(t,"utf8").split(/\r?\n/).map((a)=>a.match(/^\s*(ZENTAO_(?:URL|ACCOUNT|PASSWORD|TOKEN))=(.*)\s*$/)).filter((a)=>a!==null).map((a)=>[a[1],a[2]]))}catch(s){if(s instanceof c)throw s;throw new c("E2009",{option:"ZENTAO_CREDENTIALS_FILE",reason:`无法读取凭据文件: ${t}`},s instanceof Error?s.message:s)}let o=n.ZENTAO_PASSWORD!==void 0||n.ZENTAO_TOKEN!==void 0,r=e.url?V(e.url):void 0,i=n.ZENTAO_URL?V(n.ZENTAO_URL):void 0;if(r&&i&&r!==i||e.account&&n.ZENTAO_ACCOUNT&&e.account!==n.ZENTAO_ACCOUNT||o&&r&&!i)throw new c("E2009",{option:"ZENTAO_CREDENTIALS_FILE",reason:"凭据文件与环境变量的服务器地址或账号不一致(或文件未固定服务器),已拒绝合并,避免把凭据发送到错误的服务器;请统一来源后重试"});return{url:e.url??n.ZENTAO_URL,account:e.account??n.ZENTAO_ACCOUNT,password:e.password??n.ZENTAO_PASSWORD,token:e.token??n.ZENTAO_TOKEN}}var rt=E(()=>{L();xn();de();T();Y()});function Se(e){if(typeof e==="string"){let o=J(e);if(!o)throw new c("E1007");e=o}let t=He();if(!e&&Object.values(t).some(Boolean)&&!(t.url&&t.account&&(t.token||t.password)))throw new c("E1001",{},{reason:"incomplete_environment"});if(!e&&t.url&&t.account&&(t.token||t.password))return{source:"environment",server:V(t.url),account:t.account,token:t.token,password:t.password};let n=e??we();if(n?.token)return{source:"profile",server:n.server,account:n.account,token:n.token,profile:n};throw new c("E1006")}async function le(e,t){let n=e?.signal??I();if(n?.aborted)throw new c("E5003");let o=t??Se(e?.profile),r=o.source==="profile"?K(o.profile):void 0,i={insecure:e?.insecure??r?.insecure,timeout:e?.timeout??r?.timeout,actionAssistant:H(e?.assistant,r?.autoAssistant,e?.assistantSource)};if(o.source==="environment"){let{server:s,account:a}=o,d=nt(o,e?.preferPassword);if(d.type==="token")return{client:ee(U(s,d.value,i),n),profile:Ce(s,a,d.value)};let u=await Ue(s,a,d.value,{...i,signal:n});return{client:ee(u.client,n),profile:Ce(s,a,u.token,u.serverConfig,u.user)}}return{client:ee(U(o.server,o.token,i),n),profile:o.profile}}async function As(e,t){let n=He();if(!n.url||!n.account||!n.password)return;let o;try{o=V(n.url)}catch{return}if(o!==V(e.server)||n.account!==e.account)return;let r=t?.signal??I(),i=await Ue(e.server,e.account,n.password,{insecure:t?.insecure,timeout:t?.timeout,signal:r,actionAssistant:H(t?.assistant,void 0,t?.assistantSource)}),s=Ce(e.server,e.account,i.token,i.serverConfig,i.user),a=et(e.account,e.server);if(a&&a.token===e.token)tt(s);return{client:ee(i.client,r),profile:s}}async function kt(e,t,n){try{return await n(e.client,e.profile)}catch(o){if(o instanceof c&&o.code==="1004"){let r=await As(e.profile,t);if(r)return n(r.client,r.profile)}throw o}}var ot=E(()=>{de();T();Y();ne();rt();be()});import{createLink as Ns,parseLink as to,ZentaoError as ro}from"zentao-api";function ue(e,t){throw new c("E2009",{option:e,reason:t})}function _s(e){let t;try{t=new URL(e)}catch{return ue("server","请提供完整的 HTTP(S) 站点地址")}if(!/^https?:\/\//i.test(e)||t.username||t.password||/[?#]/.test(e))return ue("server","请提供不含凭据、查询参数或片段的 HTTP(S) 站点地址");return t}function Ft(e,t){try{if(!t)return encodeURIComponent(e);return Array.from(e,(n)=>{let o=encodeURIComponent(n);return n===o&&(n==="."||t.includes(n))?"%"+n.charCodeAt(0).toString(16).toUpperCase():o}).join("")}catch{return ue("link","页面参数包含无效的 Unicode 字符")}}function no(e){if(e instanceof ro&&typeof e.params.param==="string"&&e.params.param.startsWith("profile.serverConfig."))return e.params.param.slice(21)}async function Ut(e,t,n){let o=_s(e.server);if(t.action==="parse"){if(!t.url.trim())return ue("url","请提供页面链接");let i;try{i=new URL(t.url,o)}catch{return ue("url","无效的页面链接")}if(i.username||i.password)return ue("url","页面链接中不能包含登录凭据");if(i.origin!==o.origin||!["http:","https:"].includes(i.protocol))return to({server:o.href},t.url,{requestType:"auto"})}else if(!t.module.trim()||!t.method.trim())return ue("link","请提供页面模块名和方法名");let r=(i)=>{let s={server:o.href,serverConfig:i};if(t.action==="parse")return to(s,t.url,{requestType:"auto"});let a=i?.requestType!=="GET"&&typeof i?.requestFix==="string"?i.requestFix:void 0,d=t.vars?.map((m)=>{let p=m.indexOf("=");if(p<1||!m.slice(0,p).trim())return ue("var","请使用 名称=值,可重复传入");return[Ft(m.slice(0,p)),Ft(m.slice(p+1),a)]}),u=Ns(s,{moduleName:Ft(t.module,a),methodName:Ft(t.method,a),vars:d,relative:t.relative??!1});if(new URL(u,o).origin!==o.origin)return ue("link","页面链接超出当前站点");if(/\/(?:\.|%2e){1,2}(?:\/|$)/i.test(u))return ue("var","路径变量不能解析为 . 或 .. 目录");return u};try{let i=r(e.serverConfig);if(!(typeof i==="object"&&i.external&&!e.serverConfig?.requestType))return i}catch(i){let s=no(i);if(!(s&&i instanceof ro&&i.code==="E_MISSING_PARAM")){if(s)return ue("serverConfig",`页面路由配置 ${s} 无效`);throw N(i)}}try{return r(await n())}catch(i){let s=no(i);if(s)return ue("serverConfig",`站点未提供有效的页面路由配置 ${s}`);throw N(i)}}var Tn=E(()=>{T()});function Ht(e={}){if(e.server!==void 0&&e.profile!==void 0)throw new c("E2009",{option:"server/profile",reason:"--server 和 --profile 只能指定一个"});if(e.server!==void 0)return{server:e.server};let t=process.env[l("ZENTAO_URL")];if(e.profile===void 0&&t)return{server:t};let n=e.profile===void 0?we():J(e.profile);if(!n){if(e.profile!==void 0)throw new c("E1007");throw new c("E2009",{option:"server",reason:l("请用 --server 或 ZENTAO_URL 指定站点,或选择已保存的配置")})}return{server:n.server,serverConfig:n.serverConfig,timeout:n.config?.timeout,insecure:n.config?.insecure}}var Cn=E(()=>{L();T();Y()});async function Bt(e,t,n,o){try{let i=await U(e,void 0,o).post("/users/login",{account:t,password:n},{signal:o?.signal});if(i?.status!=="success"||typeof i.token!=="string"||!i.token.trim())throw new c("E1003");return i.token}catch(r){throw N(r)}}var Sn=E(()=>{de();T()});import{isDeepStrictEqual as xa}from"node:util";function Dn(e){return e.length>0&&/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}(?:==)?|[A-Za-z0-9+/]{3}=?)?$/.test(e)}function qe(e,t,n){let o=(i)=>{throw new c("E2009",{option:e,reason:i})},{type:r}=n;if(r&&typeof r!=="string"){if(typeof t==="string"&&!/^\d+$/.test(t)){if(!Dn(t))o("必须为数字 ID 或 Base64 编码的 gid");return}return qe(e,typeof t==="string"?Number(t):t,{type:"integer",minimum:0})}if(r==="number"||r==="integer"){if(typeof t!=="number"||!Number.isFinite(t))o("必须为有限数字");if(r==="integer"&&!Number.isSafeInteger(t))o("必须为安全整数")}else if(r==="array"?!Array.isArray(t):r==="object"?!t||typeof t!=="object"||Array.isArray(t):r&&typeof t!==r)o(`必须为 ${r} 类型`);if(typeof t==="number"){if(n.minimum!==void 0&&t<n.minimum)o(`不能小于 ${n.minimum}`);if(n.maximum!==void 0&&t>n.maximum)o(`不能大于 ${n.maximum}`)}if(typeof t==="string"){let i=[...t].length;if(n.minLength!==void 0&&i<n.minLength)o(`长度不能少于 ${n.minLength}`);if(n.maxLength!==void 0&&i>n.maxLength)o(`长度不能超过 ${n.maxLength}`);if(n.pattern&&!new RegExp(n.pattern).test(t))o(`格式必须符合 ${n.pattern}`)}if(Array.isArray(t)){if(n.minItems!==void 0&&t.length<n.minItems)o(`至少需要 ${n.minItems} 个元素`);if(n.maxItems!==void 0&&t.length>n.maxItems)o(`最多允许 ${n.maxItems} 个元素`);if(n.items)t.forEach((i,s)=>qe(`${e}[${s}]`,i,n.items))}if(n.options?.length){if((Array.isArray(t)?t:[t]).some((s)=>!n.options.some((a)=>a.value===s)))o(`可选值:${n.options.map((s)=>s.value).join(", ")}`)}}function Co(e,t,n,o){if(n.data!==void 0&&(!n.data||typeof n.data!=="object"||Array.isArray(n.data)))throw new c("E2009",{option:"data",reason:"请求体必须为 JSON 对象"});let r=n.data??{},i=Boolean(t.requestBody),s=(m,p)=>{throw new c("E2009",{option:m,reason:p})};if(t.type==="update"&&!["auditplan","baseline","weekly"].includes(e.name)&&(r.comment!==void 0||n.comment!==void 0))s("comment",l`update 请求不支持 comment 字段(服务端会静默丢弃整个更新),添加备注请使用 zentao ${e.name} comment <id> --comment <text>`);for(let m of Object.keys(n)){if(m==="data"&&i)continue;if(!o.some((p)=>p.name===m))s(m,`操作 ${e.name}/${t.name} 不支持此参数`)}for(let m of Object.keys(r)){if(!o.some((p)=>p.name===m&&p.role==="body"))s(`data.${m}`,"不是此操作的请求体字段");if(n[m]!==void 0&&!xa(n[m],r[m]))s(m,"params 与 params.data 中的参数值冲突")}let a=_e(e,t);if(a)for(let[m,p]of[[a.page,void 0],[a.size,a.size.maximum??1000]]){let g=r[m.name]??n[m.name];if(g!==void 0)qe(m.name,g,{...m,type:"integer",minimum:1,maximum:p})}let d=pt(e,t),u=t.requestBody?.schema.properties;for(let m of o){let g=m.role==="body"&&Object.hasOwn(r,m.name)?r[m.name]:n[m.name];if(g===void 0){if(m.required&&m.defaultValue===void 0&&!(m.role==="body"&&d))throw new c("E2003",{fields:m.name,module:e.name});continue}let f=m.role==="path"?pn(e,t,m.name):void 0;if(qe(m.name,g,{...m,type:m.type??f,...m.role==="body"?u?.[m.name]:{}}),m.name==="uid"&&(typeof g!=="string"||!g||/[^A-Za-z0-9_-]/.test(g)||["0","1","used","apiv2"].includes(g)))s("uid","批次标识仅接受英文字母、数字、下划线和连字符,不能为空或使用保留值 0、1、used、apiv2");if(typeof g==="number"){if((f||m.name.endsWith("ID")||["pageID","recPerPage"].includes(m.name))&&(!Number.isSafeInteger(g)||g<0))s(m.name,"必须为非负安全整数");if((m.name==="pageID"||m.name==="recPerPage")&&g<1)s(m.name,"必须为大于 0 的整数");if(m.name==="recPerPage"&&g>1000)s(m.name,"不能超过 1000")}}}var qt=E(()=>{Te();T();L()});function Tt(e,t){if(e.some((n)=>n.role==="path"&&n.name==="scope"&&n.options?.some((o)=>o.value===`${t}s`)))return"scopeID";return[`${t}ID`,t].find((n)=>e.some((o)=>o.name===n&&(o.type==="number"||o.role==="path"&&!o.type&&n.endsWith("ID"))))}function Wt(e,t,n,o){let r={...n.params},i=ge(e.name,t.name),s=Object.keys(t.pathParams??{}),a=s.includes("scope"),d=(p,g)=>{throw new c("E2009",{option:p,reason:g})};if(n.url!==void 0){if(!ae(e.name,t.name))d("url","附件链接仅适用于 file get 和 file read");if(n.id!==void 0||r.id!==void 0||r.fileID!==void 0)d("url","附件链接与文件 ID 只能指定一个");r.fileID=Cr(n.url,o)}let u=(p,g)=>{if(g===void 0)return;let f=r[p],h=typeof f==="string"&&typeof g==="number"&&f===String(g)||typeof f==="number"&&typeof g==="string"&&String(f)===g;if(f!==void 0&&f!==g&&!h)d(p,"简写与 params 中的参数值冲突");r[p]=g};for(let p of["product","project","execution"]){let g=n[p],f=`${p}ID`;if(a){let h=[g,r[p],r[f]].filter((y)=>y!==void 0);if(h.length){u("scope",`${p}s`);for(let y of h)u("scopeID",y);delete r[p],delete r[f]}}else if(g!==void 0){let h=Tt(i,p);if(!h)d(p,`操作 ${e.name}/${t.name} 不支持此数字简写,请按字段类型使用 params`);u(h,g)}}let m=s.find((p)=>p.endsWith("ID")&&p!=="scopeID");if(n.id!==void 0||r.id!==void 0){if(!m)d("id",`操作 ${e.name}/${t.name} 没有可简写的路径 ID`);u(m,n.id),u(m,r.id),delete r.id}if(u("pageID",n.page),u("recPerPage",n.recPerPage),t.requestBody){if(r.data!==void 0&&(!r.data||typeof r.data!=="object"||Array.isArray(r.data)))d("params.data","MCP 请求体必须是 JSON 对象,请勿使用 CLI 字符串或管道语法");r.data??={}}return Co(e,t,r,i),r}var Gt=E(()=>{xe();T();qt();Ye()});import{realpath as Ca}from"node:fs/promises";import{homedir as Sa}from"node:os";import{basename as Eo,resolve as _n}from"node:path";import{fileURLToPath as Ea,pathToFileURL as Aa}from"node:url";function Ct(e){return/^file:(?:\.\.?\/|~\/|\/\/)/i.test(e)}async function Ao(e,t){let n=e.slice(5),o;if(n.startsWith("//"))try{let i=n.slice(2);o=/^(?:\/|localhost(?:\/|$))/i.test(i)?Ea(e):_n(decodeURIComponent(i))}catch{return{url:e,filename:Eo(n)||"图片"}}else o=n.startsWith("~/")?_n(Sa(),"."+n.slice(1)):_n(n);let r=t.get(o);if(!r)r=await Ca(o).catch(()=>o),t.set(o,r);return{url:Aa(r).href,filename:Eo(o)||"图片"}}var Fn=()=>{};import Ua from"turndown";function Ha(){if(!Hn)Hn=new Ua({headingStyle:"atx",codeBlockStyle:"fenced"});return Hn}function Oo(e){return Ba.test(e)}function Za(e){if(!e||!Oo(e))return e;return Ha().turndown(e).trim()}function Bn(e){let t={...e};for(let n of["desc","description","content","steps","spec","verify","comment","bio"]){let o=t[n];if(typeof o==="string"&&Oo(o))t[n]=Za(o)}return t}function Mo(e){return e.map(Bn)}var Hn=null,Ba;var Ro=E(()=>{Ba=/<[a-z][\s\S]*>/i});import{AsyncLocalStorage as qa}from"node:async_hooks";import{realpathSync as Lo}from"node:fs";import{sep as $o}from"node:path";import{extendModuleAction as Wa}from"zentao-api";function st(){return Zn.getStore()===!0}function Do(){let e=Zn.getStore();return e&&e!==!0?e.root:void 0}function Kt(e,t){let n,o;try{n=Lo(e),o=Lo(t)}catch{throw new c("E2009",{option:"file",reason:"文件或根目录不存在"})}if(n!==o&&!n.startsWith(o.endsWith($o)?o:o+$o))throw new c("E2009",{option:"file",reason:"上传路径超出允许的根目录 ZENTAO_MCP_UPLOAD_ROOT"})}function No(e,t){if(!jo)Wa("file","create",(n)=>{let o=n.beforeRequest;return{...n,beforeRequest:async(r)=>{if(st())throw new c("E2009",{option:"file/create",reason:Ge});return o?o(r):{}}}}),jo=!0;return Zn.run(t?{root:t}:!0,e)}var Ge="HTTP MCP 不支持通过本地路径上传服务端文件,请使用本地 CLI 或 stdio MCP",Zn,jo=!1;var Yt=E(()=>{T();Zn=new qa});import{parseFragment as Uo}from"parse5";import{fileURLToPath as Ga}from"node:url";import{extendModuleAction as Va}from"zentao-api";function Xt(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Ja(e){let t=[...Uo(e,{sourceCodeLocationInfo:!0}).childNodes],n=[];while(t.length){let o=t.pop();if(!("tagName"in o))continue;let r="content"in o?o.content.childNodes:o.childNodes;for(let d of r)t.push(d);if(o.tagName!=="img"||o.namespaceURI!=="http://www.w3.org/1999/xhtml")continue;let i=o.sourceCodeLocation?.startTag,s=o.sourceCodeLocation?.attrs?.src,a=o.attrs.find((d)=>d.name==="src")?.value;if(i&&s&&a&&/^file:/i.test(a)&&e[i.endOffset-1]===">")n.push({src:a,alt:o.attrs.find((d)=>d.name==="alt")?.value??"",tag:i,attribute:s})}return n.sort((o,r)=>o.tag.startOffset-r.tag.startOffset)}async function Ka(e,t,n){for(let i of t){if(!Ct(i.src))continue;if(i.local=await Ao(i.src,n),st())throw new c("E2009",{option:"file",reason:Ge});let s=Do();if(s&&i.local.url.startsWith("file:"))Kt(Ga(i.local.url),s)}let o=t.map(({src:i,alt:s,local:a})=>{let d=!a&&s?' alt="'+Xt(s)+'"':"";return'<img src="'+Xt(a?.url??i)+'"'+d+">"}).join("");function r(i){let s=Uo(i).childNodes,a=[],d=0;for(let[u,m]of t.entries()){let p=s[u],g=p&&"tagName"in p&&p.tagName==="img"?p.attrs:[],f=g.find((b)=>b.name==="src")?.value,h=m.local,y=h&&g.some((b)=>b.name==="alt");if(!f||h&&!y&&f===h.url)throw new c("E2014");if(y)a.push(e.slice(d,m.tag.startOffset),"图片未上传:",Xt(m.alt.trim()||h.filename)),d=m.tag.endOffset;else{let{startOffset:b,endOffset:k}=m.attribute,w=e.slice(b,k),v=/^[^=]+=\s*/.exec(w)[0],z=w[v.length]==="'"?"'":'"';a.push(e.slice(d,b),v,z,Xt(f),z),d=k}}return a.push(e.slice(d)),a.join("")}return{workingHtml:o,restore:r}}function qn(e){return typeof e==="string"&&/<img(?=[\t\n\f\r />])/i.test(e)&&/file:|&/i.test(e)}async function Ya(e,t,n,o){if(!n.some((p)=>qn(t[p])))return t;let r=e.action,i=r.requestBody,s=new Map,a=new Map,d=st(),u={...t};for(let[p,g]of o){let f=t[p];if(!qn(f)||!d&&!g)continue;let h=Ja(f);if(!h.some((k)=>Ct(k.src)))continue;if(d)throw new c("E2009",{option:p,reason:Ge});let{workingHtml:y,restore:b}=await Ka(f,h,a);u[p]=y,s.set(p,b)}let m=Object.fromEntries([...o].filter(([,p])=>p).map(([p])=>[p,{textType:"html"}]));if(e.action={...r,requestBody:{...i,schema:{...i.schema,properties:m}}},s.size)u.toJSON=function(){let p={...this,toJSON:t.toJSON};for(let[g,f]of s)p[g]=f(this[g]);return p};return u}function Ho(e,t,n,o){if(!t.requestBody||(t.requestBody.mediaType??"application/json")!=="application/json"||!["post","put"].includes(t.method?.toLowerCase()??""))return!1;let r=mn(e,t.name);if(!r.length)return!1;let i=n.data??{},s=e==="doc"&&(i.contentType??n.contentType)!=="html",a=new Map(r.filter((u)=>!(s&&u==="content")).map((u)=>[u,Object.hasOwn(i,u)||Object.hasOwn(n,u)])),d=o&&r.some((u)=>a.get(u)&&qn(i[u]??n[u]));if(n[_o]={fields:a,rawWithImages:d},t.beforeRequest&&Fo.has(t.beforeRequest))return d;return Va(e,t.name,(u)=>{let m=async(p)=>{let g=await u.beforeRequest?.(p)??{},f=p.params[_o];if(!f)return g;if(Object.assign(p,g),f.rawWithImages){let h=p.action.request;if(p.action={...p.action,resultGetter:(y)=>y},h)p.action.request=(y)=>(y.options={...y.options,raw:!0,throwOnFail:!0},h(y))}if(p.data)p.data=await Ya(p,p.data,r,f.fields);return{}};return Fo.add(m),{...u,beforeRequest:m}}),d}var _o,Fo;var Bo=E(()=>{T();Fn();Te();Yt();_o=Symbol("supplied HTML fields"),Fo=new WeakSet});import{request as Wn,processData as Xa}from"zentao-api";function Zo(e){let t=e?.split(",").map((n)=>n.trim()).filter(Boolean);return t&&t.length>0?t:void 0}function ec(e){let t=e.split(",").map((n)=>n.trim()).find((n)=>!Qa.test(n));if(t!==void 0)throw new c("E2009",{option:"sort",reason:`无效的排序表达式 "${t}",示例 id:asc 或 pri_desc;多字段用逗号分隔`})}function tc(e){let t=e.match(/^(.+?):(?:asc|desc)$/i);if(t)return[t[1]];let n=e.match(/^(.+?)_(?:asc|desc)$/i);return n?[e,n[1]]:[e]}async function St(e,t,n,o,r,i){let s=De(t,n);if(!s)throw new c("E2005",{module:t.name});if(r.sort)ec(r.sort);let a={...o};if(t.name==="relation"&&s.name==="unlink"){let S=["objectType","objectID","relatedObjectType","relatedObjectID","relationName"].filter((M)=>Object.hasOwn(a,M));if(S.length)throw new c("E2009",{option:S.join(", "),reason:"解除关联已改用关系记录 relationID,请从 relation list 的返回结果获取,不能用对象 ID 或 relationKey 代替"})}let d=`${t.name}/${s.name}`,u=Zo(r.pick),m=r.format??i.defaultOutputFormat??"table",p=m==="raw",g=r.htmlToMarkdown??(m!=="json"&&i.htmlToMarkdown!==!1);if(p&&(r.all||r.maxItems||r.pick||r.filter?.length||r.search?.length||r.sort||r.searchFields))throw new c("E2009",{option:"raw",reason:"原始响应不能与本地处理或自动翻页组合"});let f=_e(t,s);if(r.all&&!f)throw new c("E2009",{option:"all",reason:"此操作不支持分页"});let h=a.data??{},y=(S)=>h[S]??a[S],b=(S,M)=>{if(a[S]=M,Object.hasOwn(h,S))h[S]=M};if(f){let S=Number(y(f.page.name)??r.page??1),M=Number(y(f.size.name)??r.recPerPage??i.pagers?.[t.name]??i.defaultRecPerPage??20);qe("page",S,{...f.page,type:"integer",minimum:1}),qe("page-size",M,{...f.size,type:"integer",minimum:1,maximum:f.size.maximum??1000}),b(f.page.name,S),b(f.size.name,M)}let k=!p,w=k&&s.type==="list",v=k&&s.type==="get",z=[],F=Ho(t.name,s,a,p),C={client:e,actionAssistant:r.assistant,autoFill:pt(t,s),throwOnFail:!0,continueOnFileUploadError:!st(),onFileError:p?(S)=>{z.push(S)}:void 0,recPerPage:f?String(y(f.size.name)):void 0,timeout:r.timeout,insecure:r.insecure,convert:w&&g?Mo:void 0,convertSingle:v&&g?Bn:void 0,filter:w?r.filter:void 0,search:w?r.search:void 0,searchFields:w?Zo(r.searchFields):void 0,sort:w?r.sort:void 0,limit:w?r.maxItems:void 0,pick:w||v?u:void 0},x,A=[],O,D=0,_=0;try{if(p){let M,fe={...C,onWriteOutcome:(se)=>{M=se}},G=F?(await Wn(d,a,{...fe,raw:!1,throwOnFail:!1})).data:await Wn(d,a,{...fe,raw:!0}),ie=G&&typeof G==="object"?G:void 0;if(M==="unknown"){let se=X({uid:y("uid"),fileWarnings:z});throw new c("E2016",void 0,{response:G,...se})}let Ie=!M&&(ie?.status==="fail"||s.requestBody&&(ie?.status==="error"||ie?.result==="fail"||ie?.result==="error"));if(M==="rejected"||Ie){let se=M==="rejected"&&t.name==="file"&&ie?.data?G:ie?.message;throw new c("E2008",{url:"",status:"",serverResponse:typeof se==="string"?se:JSON.stringify(se??G)},z.length?{response:G,fileWarnings:z}:G)}return{action:s,data:G,rawResponse:G,fields:u,isList:s.type==="list",...z.length?{fileWarnings:z}:{}}}let S;for(;;){if(x=await Wn(d,a,{...C,raw:!1,convert:void 0,filter:void 0,search:void 0,sort:void 0,limit:void 0,pick:w?void 0:C.pick}),S===void 0)O=x.resultObjectType;else if(x.resultObjectType!==O)O=void 0;if(!w)break;let M=Array.isArray(x.data)?x.data:[];D+=M.length;for(let ie of M)A.push(ie);if(!r.all)break;let fe=x.pager;if(!fe)throw new c("E2008",{url:"",status:"",serverResponse:"服务端未返回分页信息,无法保证全量结果"});let G=JSON.stringify(M);if(fe.page!==Number(y(f.page.name))||S!==void 0&&G===S)throw new c("E2008",{url:"",status:"",serverResponse:"服务端分页未向前推进"});if(fe.page*fe.recPerPage>=fe.total)break;if(!M.length)throw new c("E2008",{url:"",status:"",serverResponse:"服务端返回空页但报告仍有数据"});S=G,b(f.page.name,fe.page+1)}if(w){if(A.every((M)=>M!==null&&typeof M==="object"&&!Array.isArray(M)))A=Xa(A,{...C,limit:void 0});else O=void 0;if(_=A.length,r.maxItems)A=A.slice(0,Number(r.maxItems))}}catch(S){throw N(S,p)}let W=x.pager?{pageID:x.pager.page,recPerPage:x.pager.recPerPage,recTotal:x.pager.total}:void 0;if(s.type==="list"){let S=A;if(r.sort&&S.length&&!u){let ie=(Ie,se)=>se.split(".").reduce((At,lt)=>At&&typeof At==="object"?At[lt]:void 0,Ie);for(let Ie of r.sort.split(",")){let se=tc(Ie.trim());if(!S.some((lt)=>lt&&typeof lt==="object"&&se.some((Zi)=>ie(lt,Zi)!==void 0)))throw new c("E2009",{option:"sort",reason:`排序字段 "${se[0]}" 不在返回数据中,请检查字段名(示例 id:asc)`})}}let M=W?W.pageID*W.recPerPage<W.recTotal:null,fe={returned:S.length,fetched:D,page:W?.pageID??null,pageSize:W?.recPerPage??null,total:W?.recTotal??null,hasMore:M,truncated:_>S.length,processingScope:r.all?"all":"page",totalScope:"serverBeforeLocalProcessing"},G=m==="table"&&!u&&O?fn(O).filter((ie)=>S.some((Ie)=>Ie!=null&&Object.hasOwn(Ie,ie))):u;return{action:s,data:S,rawResponse:x,resultObjectType:O,pager:W,fields:G?.length?G:void 0,isList:!0,meta:fe}}if(s.type==="get"){let S=x.data instanceof ArrayBuffer?Buffer.from(x.data).toString("base64"):x.data??{};return{action:s,data:S,rawResponse:x,resultObjectType:x.resultObjectType,fields:u,isList:!1}}return{action:s,data:x.data,rawResponse:x,resultObjectType:x.resultObjectType,fields:u,isList:!1,...x.fileWarnings?.length?{fileWarnings:x.fileWarnings}:{}}}var Qa;var Gn=E(()=>{T();Ro();xe();Te();qt();Yt();Bo();Qa=/^[A-Za-z_][\w.]*?(?::(?:asc|desc)|_(?:asc|desc))?$/i});import{defineModuleActions as Ee,extendModuleAction as Vn}from"zentao-api";function Le(e,t,n,o,r){let i={name:t,display:n,type:"action",method:"put",path:`/${r?.pathCollection??`${e}s`}/{${o}}/${t}`,resultType:"text",minVersion:Ae,pathParams:{[o]:`${e} ID`}};if(r?.query)i.params=r.query;if(r?.properties||r?.required)i.requestBody={required:!0,type:"object",schema:{type:"object",properties:r?.properties??{},required:r?.required??[]}};return i}function rc(){Ee("bug",[Le("bug","assignto","指派Bug","bugID",{properties:Jn,required:["assignedTo"]})]),Ee("task",[Le("task","pause","暂停任务","taskID",{properties:qo}),Le("task","cancel","取消任务","taskID",{properties:qo}),Le("task","restart","继续任务","taskID",{properties:{realStarted:{type:"string",description:"实际开始"},consumed:{type:"number",description:"总计消耗",format:"float"},left:{type:"number",description:"预计剩余",format:"float"},comment:{type:"string",description:"备注"}},required:["realStarted"]}),Le("task","assignto","指派任务","taskID",{query:[{name:"executionID",required:!0,type:"number",description:"执行ID"}],properties:{assignedTo:{type:"string",description:"指派给"},left:{type:"number",description:"预计剩余",format:"float"},comment:{type:"string",description:"备注"}},required:["assignedTo","left"]})]);let e=[{module:"story",idKey:"storyID",displayPrefix:"需求"},{module:"epic",idKey:"storyID",displayPrefix:"业务需求"},{module:"requirement",idKey:"storyID",displayPrefix:"用户需求"}];for(let{module:t,idKey:n,displayPrefix:o}of e){let r={properties:{assignedTo:{type:"string",description:"指派给"},result:{type:"string",description:"评审结果",options:nc},reviewedDate:{type:"string",description:"评审时间"},comment:{type:"string",description:"备注"}},required:["result","reviewedDate","comment"],...t==="story"?{pathCollection:"stories"}:{}};Ee(t,[Le(t,"review",`${o}评审`,n,r)])}Ee("feedback",[Le("feedback","assignto","指派反馈","feedbackID",{properties:Jn,required:["assignedTo"]})]),Ee("ticket",[Le("ticket","assignto","指派工单","ticketID",{properties:Jn,required:["assignedTo"]})])}function oc(){Ee("task",[{name:"recordestimate",display:"记录任务工时",type:"action",method:"put",path:"/tasks/{taskID}/recordworkhour",resultType:"text",minVersion:Ae,pathParams:{taskID:"任务 ID"},requestBody:{required:!0,type:"object",schema:{type:"object",properties:{date:{type:"array",items:{type:"string"},description:"日期,格式 YYYY-MM-DD,默认今天"},work:{type:"array",items:{type:"string"},description:"工作内容"},consumed:{type:"array",items:{type:"number"},description:"本次耗时(小时,累加到总计)"},left:{type:"array",items:{type:"number"},description:"更新后的剩余工时(小时,覆盖之前值)"}},required:["date","consumed","left"]}}},{name:"effort",display:"获取任务工时记录",type:"list",method:"get",path:"/tasks/{taskID}/recordworkhour",resultType:"list",minVersion:Ae,pathParams:{taskID:"任务 ID"},params:[{name:"taskID",required:!0,type:"number",description:"任务 ID"}],resultGetter:(e)=>{let t=e?.efforts;return t?Object.values(t):[]}},{name:"editeffort",display:"编辑工时记录",type:"action",method:"put",path:"/tasks/{effortID}/editeffort",resultType:"text",minVersion:Ae,pathParams:{effortID:"工时记录 ID"},params:[{name:"effortID",required:!0,type:"number",description:"工时记录 ID"}],requestBody:{required:!0,type:"object",schema:{type:"object",properties:{date:{type:"string",description:"日期,格式 YYYY-MM-DD"},work:{type:"string",description:"工作内容"},consumed:{type:"number",description:"本次耗时(小时,累加到总计)",format:"float"},left:{type:"number",description:"更新后的剩余工时(小时,覆盖之前值)",format:"float"}},required:["consumed","left"]}}},{name:"deleteeffort",display:"删除工时记录",type:"delete",method:"delete",path:"/tasks/{effortID}/deleteworkhour",resultType:"text",minVersion:Ae,pathParams:{effortID:"工时记录 ID"},params:[{name:"effortID",required:!0,type:"number",description:"工时记录 ID"}]}])}function ic(){let e=[{module:"build",display:"获取版本详情",idKey:"buildID",resultGetter:"build"},{module:"release",display:"获取发布详情",idKey:"releaseID",resultGetter:"release"},{module:"testtask",display:"获取测试单详情",idKey:"testtaskID",resultGetter:"testtask"}];for(let t of e)Ee(t.module,{name:"get",display:t.display,type:"get",method:"get",path:`/${t.module}s/{${t.idKey}}`,resultType:"object",resultGetter:t.resultGetter,minVersion:Ae,pathParams:{[t.idKey]:`${t.module} ID`}})}function sc(){for(let e of["create","update"])Vn("bug",e,(t)=>{let n=t.requestBody?.schema;if(!n)return t;return n.properties={...n.properties??{},deadline:{type:"string",description:"截止日期,格式 YYYY-MM-DD"},module:{type:"number",description:"所属模块 ID"}},t});Vn("project","create",(e)=>{let t=e.requestBody?.schema;if(!t)return e;if(t.properties={...t.properties??{},desc:{type:"string",description:"项目描述"}},!t.required?.includes("desc"))t.required=[...t.required??[],"desc"];return e}),Vn("story","create",(e)=>{let t=e.requestBody?.schema;if(!t)return e;return t.properties={...t.properties??{},plan:{type:"array",items:{type:"number"},description:"所属计划 ID(可多个)"}},e})}function ac(e){let{status:t,...n}=e??{};return Object.values(n).filter((o)=>o&&typeof o==="object")}function Vo(e){return Go.find((t)=>t.module===e)?.actionObjectType}function cc(){for(let e of Go){let t=e.idKey,n={[t]:`${e.display} ID`},o=e.detailPath?{name:"history",display:`获取${e.display}历史记录`,type:"list",method:"get",path:e.detailPath,resultType:"list",resultGetter:"actions",minVersion:Ae,pathParams:n}:{name:"history",display:`获取${e.display}历史记录`,type:"list",method:"get",path:`/action/ajaxGetList?objectType=${e.actionObjectType}&objectID={${t}}`,resultType:"list",resultGetter:ac,minVersion:Ae,pathParams:n};Ee(e.module,o),Ee(e.module,{name:"comment",display:`添加${e.display}备注`,type:"action",method:"post",path:`/actions/comment?objectType=${e.actionObjectType}&objectID={${t}}`,resultType:"text",minVersion:Ae,pathParams:n,requestBody:{required:!0,type:"object",schema:{type:"object",properties:{comment:{type:"string",description:"备注内容"}},required:["comment"]}}})}}function Qt(){if(Wo)return;Wo=!0,rc(),oc(),ic(),sc(),cc()}var Ae,Jn,qo,nc,Go,Wo=!1;var en=E(()=>{Ae=["22.0","biz13.0","max8.0","ipd5.0"];Jn={assignedTo:{type:"string",description:"指派给"},comment:{type:"string",description:"备注"}},qo={comment:{type:"string",description:"备注"}},nc=[{value:"pass",label:"通过"},{value:"reject",label:"拒绝"},{value:"clarify",label:"需澄清"}];Go=[{module:"bug",display:"Bug",idKey:"bugID",actionObjectType:"bug",detailPath:"/bugs/{bugID}"},{module:"task",display:"任务",idKey:"taskID",actionObjectType:"task",detailPath:"/tasks/{taskID}"},{module:"story",display:"需求",idKey:"storyID",actionObjectType:"story",detailPath:"/stories/{storyID}"},{module:"epic",display:"业务需求",idKey:"storyID",actionObjectType:"story"},{module:"requirement",display:"用户需求",idKey:"storyID",actionObjectType:"story"},{module:"testcase",display:"用例",idKey:"caseID",actionObjectType:"testcase",detailPath:"/testcases/{caseID}"},{module:"testtask",display:"测试单",idKey:"testtaskID",actionObjectType:"testtask",detailPath:"/testtasks/{testtaskID}"},{module:"feedback",display:"反馈",idKey:"feedbackID",actionObjectType:"feedback",detailPath:"/feedbacks/{feedbackID}"},{module:"ticket",display:"工单",idKey:"ticketID",actionObjectType:"ticket"},{module:"product",display:"产品",idKey:"productID",actionObjectType:"product"},{module:"project",display:"项目",idKey:"projectID",actionObjectType:"project"},{module:"execution",display:"执行",idKey:"executionID",actionObjectType:"execution"},{module:"build",display:"版本",idKey:"buildID",actionObjectType:"build",detailPath:"/builds/{buildID}"},{module:"release",display:"发布",idKey:"releaseID",actionObjectType:"release",detailPath:"/releases/{releaseID}"},{module:"productplan",display:"计划",idKey:"planID",actionObjectType:"productplan",detailPath:"/productplans/{planID}"},{module:"program",display:"项目集",idKey:"programID",actionObjectType:"program"}]});async function tn(e){let t=[],n=0,o=[];for(let r=0;r<e.ids.length;r++){let i=e.ids[r];e.throwIfAborted?.();try{t.push({id:i,ok:!0,value:await e.execute(i)})}catch(s){if(e.onError?.(i,s),e.throwIfAborted?.(),n++,t.push({id:i,ok:!1,error:s}),e.failFast){o=e.ids.slice(r+1);break}}}return{outcomes:t,failed:n,skipped:o}}import{z as R}from"zod";function pi(e,t){if(t)return e?vc:wc;return e?li:Pe}function ve(e,t){let n={data:e??null,...t},o=t?.meta||t?.fileWarnings?.length||t?.isError?n:e??null;return{...t?.isError?{isError:!0}:{},structuredContent:n,content:[{type:"text",text:JSON.stringify(o,null,2)}]}}function Ve(e,t){e=N(e);let n=e instanceof c?`E${e.code}`:"E_INTERNAL",o=e instanceof Error?e.message:String(e),r=n!=="E2009"&&e instanceof Error&&"details"in e?X(e.details):void 0;return{isError:!0,structuredContent:{data:null,error:{code:n,message:o,...t,...r&&{details:r}}},content:[{type:"text",text:`${n}: ${o}${r?`
|
|
3
|
-
`+JSON.stringify(r):""}`}]}}var ci,di,Pe,li,ui,wc,vc;var er=E(()=>{T();ci=R.array(R.object({stage:R.enum(["resolve","upload","cleanup"]),code:R.string(),message:R.string(),field:R.string().optional(),path:R.string().optional(),name:R.string().optional(),fileID:R.number().optional(),uid:R.string().optional(),objectType:R.string().optional(),objectID:R.number().optional()})),di=R.object({code:R.string(),message:R.string(),module:R.string().optional(),action:R.string().optional()}),Pe=R.object({data:R.unknown(),resultObjectType:R.string().optional(),error:di.optional()}),li=Pe.extend({pager:R.object({pageID:R.number(),recPerPage:R.number(),recTotal:R.number()}).optional(),meta:R.object({processingScope:R.literal("page"),returnedCount:R.number().int().nonnegative(),totalScope:R.literal("serverBeforeLocalProcessing").optional()}).optional()}),ui={fileWarnings:ci.optional(),error:di.extend({details:R.object({uid:R.string().optional(),fileIDs:R.array(R.number()).optional(),fileWarnings:ci.optional()}).optional()}).optional()},wc=Pe.extend(ui),vc=li.extend(ui)});import{z as j}from"zod";function Et(e){return Mt(e)}function tr(e,t){if(t.readOnly&&!Et(e))return!1;if(e.requestBody?.mediaType!=="multipart/form-data")return!0;return t.allowLocalFiles!==!1||t.localUploadRoot!==void 0}function kc(e){return l`${e.display??e.name}操作;参数、示例和最低版本见 zentao_action_help`}function xc(e){let t=e.actions.map((n)=>n.name);return[t[0],...t.slice(1)]}function zc(e){let t=xc(e),n=e.actions.flatMap((s)=>ge(e.name,s.name)),o=new Set(n.map((s)=>s.name)),r=e.actions.some((s)=>s.type==="list"),i={assistant:j.string().optional().describe("本次操作来源标记;省略继承服务设置,空字符串关闭"),action:j.enum(t).describe(e.actions.map((s)=>`${s.name}: ${s.display??s.name}`).join("; ")),params:j.record(j.string(),j.unknown()).optional().describe(l("路径、查询或请求体参数;必填项见 zentao_action_help"))};if(n.some((s)=>s.role==="path"&&s.name.endsWith("ID")&&s.name!=="scopeID"))i.id=j.number().int().nonnegative().optional().describe("首个路径 ID 简写;多 ID 用 params");if(e.actions.some((s)=>ae(e.name,s.name)))i.url=j.string().optional().describe("get 或 read 的附件 URL,可代替文件 ID");for(let s of["product","project","execution"])if(Tt(n,s))i[s]=j.number().int().nonnegative().optional().describe(`${s}ID 或 scope/scopeID 简写,冲突时报错`);if(e.actions.some((s)=>s.type==="list"||s.type==="get"))i.pick=j.string().optional().describe("返回字段,逗号分隔");if(r)i.all=j.boolean().optional().describe("显式遍历全部页面后本地处理"),i.maxItems=j.number().int().positive().optional().describe("整次调用最多返回条数"),i.filter=j.array(j.string()).optional().describe("当前页过滤,组内逗号为 AND、多组为 OR;远端筛选见 params.filters"),i.sort=j.string().optional().describe("当前页排序,如 pri:asc"),i.search=j.array(j.string()).optional().describe("当前页搜索,组内逗号为 AND、多组为 OR"),i.searchFields=j.string().optional().describe("搜索字段,逗号分隔");if(e.actions.some((s)=>Je(s)))i.ids=j.array(j.number().int().positive()).optional().describe("批量目标 ID;get/update/delete/action 类操作逐个执行并返回逐项结果"),i.batchFailFast=j.boolean().optional().describe("批量失败后跳过剩余目标");if(o.has("pageID"))i.page=j.number().int().positive().optional().describe("页码,从 1 开始");if(o.has("recPerPage"))i.recPerPage=j.number().int().min(1).max(1000).optional().describe("每页 1–1000 条");return{inputSchema:j.object(i).strict(),outputSchema:pi(r,n.some((s)=>s.role==="body"&&s.textType==="html"))}}function Tc(e,t,n){let o=t.requestBody?.schema.example,r=Object.fromEntries(ge(e.name,t.name).filter((i)=>i.required&&i.defaultValue===void 0).map((i)=>[i.name,(i.role==="body"?o?.[i.name]:void 0)??(i.type==="array"?[]:i.options?.[0]?.value??(i.type==="number"||i.role==="path"&&i.name.endsWith("ID")?1:i.type==="boolean"?!1:i.type==="object"?{}:`<${i.name}>`))]));return{name:l`zentao_${e.name}${n?Et(t)?"_read":"_write":""}`,arguments:ae(e.name,t.name)?{action:t.name,url:"/file-read-298.png"}:{action:t.name,...Object.keys(r).length?{params:r}:{}},note:"ID、文本等均为格式示例,请替换为实际值后调用。"}}async function Cc(e,t,n){if(n!==void 0)Qe(n);let{client:o,identity:r}=await e.getContext(t),i=ee(o,t),{user:s}=await vt(i,r.account,n),a=s?.account??r.account??null;return ve({account:a,server:r.server,userFound:Boolean(s),user:s?Object.fromEntries(["id","account","realname","dept","role"].filter((d)=>s[d]!==void 0).map((d)=>[d,s[d]])):null,...a===null?{note:l("当前禅道版本不支持通过 Token 查询当前用户资料。")}:{}})}async function Sc(e,t){let{identity:n}=await t.switchProfile(e.profileKey),o=`${n.account}@${n.server}`;return ve({status:"success",currentProfile:o})}async function Ec(e,t,n,o,r){let i=t.assistant??o.assistant;if(i!==void 0)Qe(i);let s=De(e,t.action);if(!s)throw new c("E2005",{module:e.name});if(!tr(s,o))throw new c("E2009",{option:`${e.name}/${s.name}`,reason:Ge});let a=e.name==="file"&&s.name==="read";for(let z of["filter","sort","search","searchFields","pick"])if(t[z]!==void 0&&s.type!=="list"&&!(z==="pick"&&s.type==="get"&&!a))throw new c("E2009",{option:z,reason:`不适用于 ${e.name}/${s.name}`});if((t.all!==void 0||t.maxItems!==void 0)&&s.type!=="list")throw new c("E2009",{option:"all/maxItems",reason:`不适用于 ${e.name}/${s.name}`});if(t.all!==void 0&&t.page!==void 0)throw new c("E2009",{option:"all/page",reason:"all 与 page 不能同时使用:all 已显式遍历全部页面"});let d=t.ids!==void 0?t.ids.length?[...new Set(t.ids)]:void 0:void 0;if(t.ids!==void 0){if(!Je(s))throw new c("E2009",{option:"ids",reason:"此操作不支持批量对象操作"});if(!d.length)throw new c("E2009",{option:"ids",reason:"至少需要一个目标 ID"})}let u,m,p=d?.length?he(s):void 0,g=Wt(e,s,p?{...t,params:{...t.params,[p]:d[0]}}:t,(z)=>{if(u=z,m=n.getSiteUrl?.(),m!==void 0)Ne(z,m)});if(p)delete g[p];if(s.requestBody?.mediaType==="multipart/form-data"&&o.allowLocalFiles===!1&&o.localUploadRoot!==void 0){let z=g.file,F=g.data?.file,C=typeof z==="string"?z:typeof F==="string"?F:void 0;if(!C)throw new c("E2009",{option:"file",reason:"需要本地文件路径"});Kt(C,o.localUploadRoot)}let{client:f,config:h}=await n.getContext(r);if(u!==void 0&&m!==f.siteUrl)Ne(u,f.siteUrl);let y={assistant:i,pick:t.pick,filter:t.filter,sort:t.sort,search:t.search,searchFields:t.searchFields,recPerPage:t.recPerPage!=null?String(t.recPerPage):void 0,all:t.all,maxItems:t.maxItems!=null?String(t.maxItems):void 0,batchFailFast:t.batchFailFast,format:"json"},b=(z)=>St(ee(f,r),e,s.name,z,y,h),k=(z)=>o.allowLocalFiles===!1?No(z,o.localUploadRoot):z();if(d?.length){let z=he(s),{outcomes:F,failed:C,skipped:x}=await tn({ids:d,failFast:t.batchFailFast??!1,throwIfAborted:()=>r?.throwIfAborted(),execute:(D)=>k(()=>b({...g,[z]:D}))}),A=[],O=[];for(let D of F)if(D.ok)A.push({objectID:D.id,ok:!0,data:D.value.data??D.value.rawResponse??null});else{let _=D.error instanceof c?D.error:Error(String(D.error));O.push({objectID:D.id,error:{..._ instanceof c?{code:`E${_.code}`}:{},message:_.message}}),A.push({objectID:D.id,ok:!1,error:{message:_.message}})}return ve({ok:C===0,data:A,meta:{success:d.length-C-x.length,failed:C,skipped:x.length,...O.length?{errors:O}:{}}},{isError:C>0})}let w=await k(()=>b(g)),v={...w.fileWarnings?.length?{fileWarnings:w.fileWarnings}:{},...w.resultObjectType?{resultObjectType:w.resultObjectType}:{}};if(w.action.type==="list")return ve(w.data,{...v,...w.pager?{pager:w.pager}:{},meta:{processingScope:"page",returnedCount:Array.isArray(w.data)?w.data.length:0,...w.pager?{totalScope:"serverBeforeLocalProcessing"}:{}}});if(w.action.type==="get")return ve(a?{encoding:"base64",content:w.data}:w.data,v);return ve(w.data??w.rawResponse,v)}function Ac(e){let t=e.every(Et),n=e.some((o)=>["update","delete","action"].includes(o.type));return{readOnlyHint:t,destructiveHint:n,openWorldHint:!0}}function fi(e,t,n={}){let o=n.modules?[...new Set(n.modules)].map((r)=>{let i=me(r);if(!i)throw new c("E2001",{module:r});return i}):vr();if(!o.length)throw new c("E2009",{option:"modules",reason:"至少指定一个模块"});if(e.registerTool(l("zentao_action_help"),{description:l("查看禅道操作的路径、参数定义和最低版本要求,无需登录;调用业务工具前可按需查询"),inputSchema:j.object({module:j.string().describe("模块名,如 doc、story"),action:j.string().describe("操作名,如 createMyDoc、getGrades")}).strict(),outputSchema:Pe,annotations:{readOnlyHint:!0,destructiveHint:!1,openWorldHint:!1}},async({module:r,action:i})=>{try{let s=me(r);if(!s)throw new c("E2001",{module:r});let a=De(s,i);if(!a)throw new c("E2005",{module:s.name});return ve({...Me(s,a),...ae(s.name,a.name)?{description:(a.name==="read"?'读取附件内容。MCP 对两种 stream 取值均返回 { encoding: "base64", content: "…" }。':"获取附件元数据,params.fileID 接受数字 ID 或 Base64 gid。")+"顶层 url 可代替文件 ID,接受当前站点的附件读取或下载链接。"}:{},available:o.some((d)=>d.name===s.name)&&tr(a,n),...n.allowLocalFiles===!1&&n.localUploadRoot===void 0&&a.requestBody?.mediaType==="multipart/form-data"?{unavailableReason:Ge}:{},example:Tc(s,a,n.splitTools)})}catch(s){return Ve(s,{module:r,action:i})}}),e.registerTool(l("zentao_profile"),{description:"查询当前 Token 对应的账号、站点和用户资料。旧版禅道按已绑定的账号查询,未绑定时返回空账号。",inputSchema:j.object({assistant:j.string().optional().describe("本次操作来源标记;省略继承服务设置,空字符串关闭")}).strict(),outputSchema:Pe,annotations:{readOnlyHint:!0,destructiveHint:!1,openWorldHint:!0}},async(r,i)=>{try{return await Cc(t,i.signal,r.assistant??n.assistant)}catch(s){return Ve(s)}}),t.switchProfile&&!n.readOnly)e.registerTool(l("zentao_switch_profile"),{description:"切换当前 MCP 实例的登录账号,不改变 CLI 或其他 MCP 实例的账号",inputSchema:j.object({profileKey:j.string().describe("目标用户配置标识,支持 account@server、account 或 account@hostname")}).strict(),outputSchema:Pe,annotations:{readOnlyHint:!1,destructiveHint:!1,openWorldHint:!0}},async(r)=>{try{return await Sc(r,t)}catch(i){return Ve(i)}});for(let r of new Set(o)){let i=r.actions.filter((a)=>tr(a,n)),s=n.splitTools?[{suffix:"_read",actions:i.filter(Et)},{suffix:"_write",actions:i.filter((a)=>!Et(a))}]:[{suffix:"",actions:i}];for(let a of s){if(!a.actions.length)continue;let d={...r,actions:a.actions},u=l`zentao_${d.name}${a.suffix}`,m=kc(d),p=zc(d),g=Ac(d.actions);e.registerTool(u,{description:m,...p,annotations:g},async(f,h)=>{let y=f;try{if(!a.actions.some((b)=>b.name===y.action))throw new c("E2006");return await Ec(r,y,t,n,h.signal)}catch(b){return Ve(b,{module:d.name,action:y.action})}})}}}var mi=E(()=>{L();xn();Te();Yt();xe();xe();Gn();T();de();be();Gt();Ye();er();Ke()});import{z as $e}from"zod";function nn(e,t){let n,o,r;return(i,s)=>{if(s?.aborted)throw new c("E5003");let a=e();return Ut(a,i,async()=>{let d=t?.insecure??a.insecure;if(!n||o!==a.server||r!==d)n=U(a.server,void 0,{insecure:d,actionAssistant:""}),o=a.server,r=d;let u=n.getZentaoConfig({timeout:t?.timeout??a.timeout});if(!s)return u;let m,p=new Promise((g,f)=>{if(m=()=>f(new c("E5003")),s.addEventListener("abort",m,{once:!0}),s.aborted)m()});try{return await Promise.race([u,p])}finally{s.removeEventListener("abort",m)}})}}function gi(e,t){e.registerTool(l("zentao_link"),{description:"使用当前绑定站点的路由配置生成或解析页面链接。",inputSchema:$e.object({action:$e.enum(["create","parse"]),module:$e.string().min(1).optional().describe("create 时必填,页面模块名"),method:$e.string().min(1).optional().describe("create 时必填,页面方法名"),vars:$e.array($e.string()).optional().describe('create 的有序参数,如 ["bugID=42"]'),relative:$e.boolean().optional().describe("create 时返回站内路径"),url:$e.string().min(1).optional().describe("parse 时必填,页面网址或站内路径")}).strict(),outputSchema:Pe,annotations:{readOnlyHint:!0,destructiveHint:!1,openWorldHint:!0}},async(n,o)=>{try{if(n.action==="parse"){if(n.url===void 0||n.module!==void 0||n.method!==void 0||n.vars!==void 0||n.relative!==void 0)throw new c("E2009",{option:"parse",reason:"解析时仅接受 url"});return ve(await t({action:"parse",url:n.url},o.signal))}if(!n.module||!n.method||n.url!==void 0)throw new c("E2009",{option:"create",reason:"生成链接需要 module 和 method,url 用于解析"});return ve(await t({action:"create",module:n.module,method:n.method,vars:n.vars,relative:n.relative},o.signal))}catch(r){return Ve(r)}})}var nr=E(()=>{de();Tn();L();T();er()});import{McpServer as Pc}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Ic}from"@modelcontextprotocol/sdk/server/stdio.js";function rn({client:e,profile:t}){return{client:e,config:K(t),identity:{server:t.server,account:t.account}}}function Oc(e){H(e?.assistant,!0,"stdio");let t={...e,assistantSource:"stdio"},n,o,r=He(),i=Boolean(!e?.profile&&r.url&&r.account&&(r.token||r.password)),s=e?.profile;return{getSiteUrl:()=>Se(s).server,pageLink:nn(()=>Ht({profile:s}),e),async getContext(a){if(a?.aborted)throw new c("E5003");if(!n){let k=new AbortController,w=le({...t,signal:k.signal}),v={promise:w,controller:k,pending:!0,waiters:0};o=v,n=w,w.finally(()=>{v.pending=!1}).catch(()=>{}),w.catch(()=>{if(n===w)n=void 0})}let d=n,u=i,m=o?.promise===d?o:void 0;if(m)m.waiters++;let p,g;try{g=await(a?Promise.race([d,new Promise((k,w)=>{p=()=>w(new c("E5003")),a.addEventListener("abort",p,{once:!0})})]):d)}finally{if(p)a?.removeEventListener("abort",p);if(m&&--m.waiters===0&&m.pending){if(m.controller.abort(),n===d)n=void 0}}if(a?.aborted)throw new c("E5003");if(u)return rn(g);let f=et(g.profile.account,g.profile.server);if(!f?.token)throw new c("E1006");if(n===d)s=Z(f.account,f.server);let h=K(f),y=K(g.profile);if(f.token===g.profile.token&&(e?.timeout??h.timeout)===(e?.timeout??y.timeout)&&(e?.insecure??h.insecure)===(e?.insecure??y.insecure)&&H(e?.assistant,h.autoAssistant,"stdio")===H(e?.assistant,y.autoAssistant,"stdio"))return rn({client:g.client,profile:f});let b=le({...t,profile:f});if(n===d)n=b;return rn(await b)},async switchProfile(a){let d=J(a);if(!d)throw new c("E1007");let u=await le({...t,profile:d});return n=Promise.resolve(u),i=!1,s=Z(d.account,d.server),rn(u)}}}function ct(e,t){Qt();let n=new Pc({name:l("zentao-cli"),version:ce()},{capabilities:{tools:{}}});if(fi(n,e,t),e.pageLink)gi(n,e.pageLink);return n}async function rr(e){let t=ct(Oc(e),e),n=new Ic;await t.connect(n)}var or=E(()=>{L();ot();Y();Cn();rt();T();mi();Fe();be();nr();en()});var Mc,Rc,dt;var ir=E(()=>{L();Mc={language:"语言",darkMode:"深色模式",switchDark:"切换至深色模式",switchLight:"切换至浅色模式",title:l("接入禅道 MCP"),site:l("禅道站点"),steps:"接入步骤",progress:"接入进度",step1:"准备 Token",step2:"配置 Agent",step3:"验证连接",method:"Token 获取方式",login:"账号登录",existing:"已有 Token",username:"用户名",password:"密码",usernamePlaceholder:l("禅道用户名"),passwordPlaceholder:"输入密码",personalToken:"个人 Token",getToken:"获取 Token 并继续",continue:"继续配置",trust:l("账号密码经此服务发送至禅道,不保存。"),retention:"Token 仅保留在当前页面,刷新或关闭后清除。",skip:"稍后填写 Token,先看配置",tokenReady:"已填写",tokenEmpty:"未填写",enterToken:"填写 Token",copyToken:"复制 Token",clearToken:"清除 Token",setupMethod:"配置方式",agentSetup:"让 Agent 配置",changeToken:"更换 Token",expand:"展开",collapse:"收起",expandInstructions:"展开接入说明",collapseInstructions:"收起接入说明",setupIntro:"建议不向 AI 提供 Token。复制说明,让 Agent 告知 MCP 配置文件位置和 Token 设置方法,再由你在本机填写。",includeToken:"复制说明或配置时附带 Token(有风险)",includeWarning:l("发送给 AI 后,Token 可能被 AI 服务商处理,并保存在对话记录或日志中;泄露后他人可能以你的权限访问禅道。预览仍隐藏 Token。"),copyInstructions:"复制接入说明",copiedInstructions:"已复制 · 让 Agent 说明配置位置和 Token 设置方法",previewPrompt:"预览说明",manual:"手动配置",chooseAgent:"选择 Agent",copyConfig:"复制配置",nextVerify:"配置好了,去验证",verifyTitle:"在 Agent 中验证",verifyIntro:"重载或重启 Agent 后,发送这条提问:",verifyPrompt:l("请通过 zentao-remote MCP 查询我有权访问的产品列表,只显示 ID 和名称。"),copyVerify:"复制验证提问",copiedVerify:"已复制 · 去 Agent 中发送",verifyResult:"检查返回的产品 ID 和名称。列表为空时,请确认账号的产品访问权限。",troubleshoot:"没有连接成功?",troubleshootText:"确认 MCP 服务已启用,且 Agent 能访问服务地址。Token 失效时,重新获取并更新 Agent 配置。",backSetup:"返回配置",details:"接入详情",mcpAddress:"MCP 地址:",localOnly:"此地址仅供同一台电脑上的 Agent 使用。",guide:"完整接入指南 ↗",copied:"已复制",showPassword:"显示密码",hidePassword:"隐藏密码",showToken:"显示 Token",hideToken:"隐藏 Token",required:l("请填写禅道用户名和密码。"),invalidToken:"请只粘贴 Token 值,不要包含引号、请求头名称或空格。",tokenRequired:"请填写个人 Token。",submitting:"正在获取…",connecting:l("正在连接禅道,请稍候。"),networkError:"连接失败,请检查网络后重试。",copyFailed:"复制失败,请允许浏览器访问剪贴板,或手动复制预览并填写 Token。",copiedSecret:"已复制,内容包含个人 Token,请妥善保管。",clearedNotice:"页面中的 Token 已清除。已复制或保存到 Agent 的 Token 不受影响。",insecure:"请通过管理员提供的 HTTPS 地址打开,再填写密码或 Token。本机可使用 http://127.0.0.1。",noScript:"请启用 JavaScript 后获取 Token 和复制配置。",readOnly:"仅开放查询",readWrite:"开放查询与操作",allModules:"全部可用模块",accountPermissions:l("实际权限以你的禅道账号为准。"),reachable:"Agent 所在环境需要能访问此地址。",officialDocs:"官方配置文档 ↗",mergeHint:"合并到已有配置,保留其他服务。",noQuery:"请使用不含查询参数的接入页面。",pageMethod:"请通过浏览器打开接入页面。",postOnly:"仅支持 POST。",invalidOrigin:"请求来源不正确,请重新打开接入页面。",expired:"请求来源不正确或服务已重启,请刷新页面后重试。",httpsRequired:"请通过管理员提供的 HTTPS 地址获取 Token。",jsonRequired:"请通过接入页面提交 JSON 登录信息。",busy:"获取 Token 的用户较多,请稍后重试。",tooLarge:"登录信息过长,请检查输入。",bodyTimeout:"接收请求超时,请重试。",invalidJson:"登录信息格式不正确。",invalidCredentialsInput:l("请填写有效的禅道用户名和密码,禅道地址由管理员设置。"),cancelled:"请求已取消。",invalidTokenResponse:l("禅道返回的 Token 格式无效,请联系管理员。"),invalidCredentials:"用户名或密码不正确,或当前账号不允许登录,请检查后重试。",timeout:l("连接禅道超时,请稍后重试。"),certificate:l("禅道的 HTTPS 证书验证失败,请联系管理员。"),loginFailed:l("无法获取 Token,请检查网络,或联系管理员确认禅道服务和 API 登录是否可用。")},Rc={language:"Language",darkMode:"Dark mode",switchDark:"Switch to dark mode",switchLight:"Switch to light mode",title:l("Connect ZenTao MCP"),site:l("ZenTao site"),steps:"Connection steps",progress:"Connection progress",step1:"Get token",step2:"Set up Agent",step3:"Verify",method:"Token source",login:"Sign in",existing:"Use a token",username:"Username",password:"Password",usernamePlaceholder:l("ZenTao username"),passwordPlaceholder:"Enter your password",personalToken:"Personal token",getToken:"Get token and continue",continue:"Continue to setup",trust:l("Credentials are sent to ZenTao through this service and are not stored."),retention:"Your token stays on this page and is cleared when you refresh or close it.",skip:"Set up first, add a token later",tokenReady:"Added",tokenEmpty:"Not added",enterToken:"Add token",copyToken:"Copy token",clearToken:"Clear token",setupMethod:"Setup method",agentSetup:"Let Agent set up",changeToken:"Change token",expand:"Expand",collapse:"Collapse",expandInstructions:"Expand setup instructions",collapseInstructions:"Collapse setup instructions",setupIntro:"Keep your token out of AI prompts. Copy the instructions so your Agent can explain which MCP config file to edit and how to set the token locally.",includeToken:"Include token in copied setup (risky)",includeWarning:l("If sent to AI, your token may be processed by the AI provider and stored in chat history or logs. If exposed, others could access ZenTao with your permissions. The preview still hides your token."),copyInstructions:"Copy setup instructions",copiedInstructions:"Copied · Ask your Agent where and how to set the token",previewPrompt:"Preview",manual:"Manual setup",chooseAgent:"Choose your Agent",copyConfig:"Copy config",nextVerify:"Setup done, verify connection",verifyTitle:"Verify in your Agent",verifyIntro:"Reload or restart your Agent, then send this prompt:",verifyPrompt:l("Use the zentao-remote MCP to query the products I can access. Show only their IDs and names."),copyVerify:"Copy verification prompt",copiedVerify:"Copied · Send it to your Agent",verifyResult:"Check the returned product IDs and names. If the list is empty, check your account’s product permissions.",troubleshoot:"Having trouble connecting?",troubleshootText:"Check that the MCP server is enabled and its address is reachable from your Agent. If your token has expired, get a new one and update the Agent config.",backSetup:"Back to setup",details:"Connection details",mcpAddress:"MCP address: ",localOnly:"This address only works for an Agent running on the same computer.",guide:"Full setup guide ↗",copied:"Copied",showPassword:"Show password",hidePassword:"Hide password",showToken:"Show token",hideToken:"Hide token",required:l("Enter your ZenTao username and password."),invalidToken:"Paste only the token value, without quotes, header names or spaces.",tokenRequired:"Enter your personal token.",submitting:"Getting token…",connecting:l("Connecting to ZenTao…"),networkError:"Connection failed. Check your network and try again.",copyFailed:"Copy failed. Allow clipboard access, or copy the preview and add your token locally.",copiedSecret:"Copied with your personal token. Keep it private.",clearedNotice:"Token cleared from this page. Copies already saved in your Agent are unchanged.",insecure:"Open the HTTPS address provided by your administrator before entering credentials. On this computer, you can use http://127.0.0.1.",noScript:"Enable JavaScript to get a token and copy the configuration.",readOnly:"Queries only",readWrite:"Queries and actions enabled",allModules:"All available modules",accountPermissions:l("Your ZenTao account permissions apply."),reachable:"This address must be reachable from your Agent.",officialDocs:"Official setup docs ↗",mergeHint:"Merge into your existing config and preserve other services.",noQuery:"Open the connection page without query parameters.",pageMethod:"Open the connection page in your browser.",postOnly:"Only POST requests are supported.",invalidOrigin:"Invalid request origin. Reopen the connection page.",expired:"The request origin is invalid or the service restarted. Refresh the page and try again.",httpsRequired:"Use the HTTPS address provided by your administrator to get a token.",jsonRequired:"Submit your sign-in details through the connection page.",busy:"Too many token requests. Wait a moment and try again.",tooLarge:"Sign-in details are too long. Check your input.",bodyTimeout:"Receiving the request timed out. Try again.",invalidJson:"The sign-in request format is invalid.",invalidCredentialsInput:l("Enter a valid ZenTao username and password. The site address is set by your administrator."),cancelled:"Request cancelled.",invalidTokenResponse:l("ZenTao returned an invalid token. Contact your administrator."),invalidCredentials:"The username or password is incorrect, or this account cannot sign in. Check your details and try again.",timeout:l("The ZenTao connection timed out. Try again later."),certificate:l("ZenTao’s HTTPS certificate could not be verified. Contact your administrator."),loginFailed:l("Could not get a token. Check your network, or ask your administrator to check ZenTao and API sign-in.")},dt={zh:Mc,en:Rc}});var hi;var yi=E(()=>{L();hi=gr`
|
|
1
|
+
var D2=Object.defineProperty;var w2=(T)=>T;function R2(T,$){this[T]=w2.bind(null,$)}var O2=(T,$)=>{for(var L in $)D2(T,L,{get:$[L],enumerable:!0,configurable:!0,set:R2.bind($,L)})};var N=(T,$)=>()=>(T&&($=T(T=0)),$);function J(T,...$){if(typeof T!=="string")return T.reduce((L,Y,W)=>L+J(Y)+(W<$.length?String($[W]):""),"");return jT(T,void 0)}function jT(T,$){if(!$)return T;let L=$;return T.replace(/https:\/\/www\.zentao\.net\//g,L.homepage).replace(/zentao-api/g,"\x00sdk\x00").replace(/ZenTao-Action-Assistant/g,"\x00assistant-header\x00").replace(/zentao-cli/g,L.packageName).replace(/禅道|禪道|ZenTao|Zentao/g,L.displayName).replace(/ZENTAO/g,L.commandName.toUpperCase()).replace(/zentao/g,L.commandName).replace(/\u0000sdk\u0000/g,"zentao-api").replace(/\u0000assistant-header\u0000/g,"ZenTao-Action-Assistant")}function M0(T,$=!1,L=void 0){if(!L||T===null||typeof T!=="object")return $&&typeof T==="string"?jT(T,L):T;let Y=Z1.get(L);if(!Y)Z1.set(L,Y=new WeakMap);if(!$&&Y.has(T))return Y.get(T);let W=Array.isArray(T)?T.map((H)=>M0(H,$,L)):Object.fromEntries(Object.entries(T).map(([H,Q])=>[H,typeof Q==="string"&&($||["display","description","label","title"].includes(H))?jT(Q,L):M0(Q,$||H==="examples"||H==="example",L)]));if(Object.freeze(W),!$)Y.set(T,W);return W}function HT(T,$){return(void 0)?.logoSvg?(void 0).logoSvg.replace("<svg ",`<svg class="${$}" aria-hidden="true" `):T}function A1(T,...$){return T.raw.reduce((L,Y,W)=>L+J(Y)+(W<$.length?String($[W]):""),"")}var w0=void 0,Z1;var b=N(()=>{Z1=new WeakMap});import{getModule as y1,getModuleAction as S2,getModuleNames as P1,getObjectProps as M2,getModuleActionParams as q2}from"zentao-api";function I0(T){if(!T)return;try{return M0(y1(T))}catch{return}}function k1(){return P1()}function b1(){return P1().map((T)=>M0(y1(T)))}function j1(T){return Object.fromEntries(Object.entries(M2(T)??{}).map(([$,L])=>[$,J(L)]))}function q0(T,$){return M0(S2(T.name,$))}var z0=(...T)=>M0(q2(...T));var J0=N(()=>{b()});import{ERRORS as z2}from"zentao-api";function Z2(T){if(!T||typeof T!=="object")return!1;let $=T.code;return typeof $==="string"&&$.startsWith("E_")}function v(T){if(T instanceof B)return T;if(!Z2(T))return T;let{code:$,message:L,details:Y}=T,W=T.params??{},H=Y&&typeof Y==="object"?Y:{};switch($){case"E_HTTP_ERROR":{let Q=Number(H.status),X=typeof H.url==="string"?H.url:"";if(Q===401)return new B("E1004",void 0,Y);if(Q===403)return new B("E2006",void 0,Y);if(Q===404)return new B("E2002",{object:X},Y);return new B("E2008",{url:X,status:String(H.status??""),serverResponse:typeof H.body==="string"?H.body:String(H.body??"")},Y)}case"E_TIMEOUT":return new B("E5001",void 0,Y);case"E_ABORTED":return new B("E5003",void 0,Y);case"E_NETWORK_ERROR":{let Q=(typeof H.message==="string"?H.message:L)??"";if(Q.includes("SSL")||Q.includes("TLS")||Q.includes("certificate"))return new B("E5002",void 0,Y);return new B("E1002",{url:""},Y)}case"E_API_FAILED":return new B("E2008",{url:"",status:"",serverResponse:String(W.message??H.message??"")},Y);case"E_LOGIN_FAILED":return new B("E1003",void 0,Y);case"E_UNSUPPORTED_ZENTAO_VERSION":return new B("E2010",{action:String(H.action??""),version:String(H.version??""),minVersion:Array.isArray(H.minVersion)?H.minVersion.join(" / "):String(H.minVersion??"")},Y);case"E_INVALID_ZENTAO_VERSION":return new B("E2011",{version:String(W.version??"")},Y);case"E_INVALID_ZENTAO_CONFIG":return new B("E2012",void 0,Y);case"E_MISSING_PARAM":return new B("E2003",{fields:String(W.param??""),module:""},Y);case"E_INVALID_PARAM":{let Q=String(W.param??""),X=String(W.value??"");return new B("E2004",{field:Q??"",value:X??""},Y)}case"E_INVALID_MODULE":return new B("E2001",{module:String(W.module??"")},Y);case"E_INVALID_ACTION":case"E_INVALID_REQUEST_NAME":return new B("E2005",{module:""},Y);case"E_NO_PROFILE":case"E_NO_GLOBAL_CLIENT":return new B("E1006",void 0,Y);case"E_PROFILE_NOT_FOUND":return new B("E1007",void 0,Y);default:return new B("E2008",{url:"",status:"",serverResponse:A2(T)},Y)}}function A2(T){let $=z2[T.code];if(!$)return T.message??String(T.code);return x1(J($),T.params)}function x1(T,$){return T.replace(/\{([^{}]+)\}/g,(L,Y)=>$&&Object.hasOwn($,Y)?String($[Y]):L)}function E1(T,$){if($==="json"||$==="raw"){let L={ok:!1,error:{code:T.code,message:T.message}};if(T.details)L.error={...L.error,details:T.details};return JSON.stringify(L,null,4)}return`Error(E${T.code}): ${T.message}`}var N2,B;var S=N(()=>{b();N2={E1001:J("必须提供有效的禅道服务地址、用户名和密码或 TOKEN"),E1002:J("所提供的禅道服务地址 {url} 无法访问"),E1003:"当前用户名和密码不正确",E1004:"所提供的 Token 已失效,请提供密码重新登录,或提供新的 TOKEN",E1005:"配置文件损坏或无法读取,请检查 {path}",E1006:J("未找到可用的用户配置,请执行 `zentao login --web` 在浏览器中登录;终端登录使用 `zentao login --no-browser`"),E1007:J("指定的用户配置不存在,请通过 `zentao profile list` 查看可用配置"),E1008:"浏览器登录已取消",E1009:J("浏览器登录等待超时,请重新执行 `zentao login --web`"),E1010:J("无法启动本地登录服务,请检查本机网络权限,或使用 `zentao login --no-browser`"),E1011:"配置文件写入失败,请检查 {path} 的目录权限和磁盘空间",E1012:J("未能确认远端会话已撤销,已保留本地登录记录,请重试或联系禅道管理员"),E2001:J("未找到指定的模块 {module},请通过 `zentao help` 查看支持的模块"),E2002:"未找到指定的对象 {object},请检查对象 ID 是否正确",E2003:J("缺少必要参数 {fields},请通过 `zentao {module} --help` 查看必要参数"),E2004:"{field} 参数值 {value} 无效,请检查参数格式是否正确",E2005:J("不支持的操作,请通过 `zentao {module} --help` 查看支持的操作"),E2006:"当前用户没有权限执行此操作",E2007:"`--data` 参数中的 JSON 数据格式无效",E2008:J("禅道服务端返回错误(Url:{url},Status:{status}),请查看详细错误信息:{serverResponse}"),E2009:"选项 {option} 的值无效,{reason}",E2010:J("操作 {action} 不支持当前禅道版本 {version},最低版本要求:{minVersion},请升级对应系列的禅道版本"),E2011:J("无法识别禅道版本 {version},仅支持点分数字的正式版本(如 22.5、biz13.5、max8.5、ipd5.5)"),E2012:J("无法识别禅道服务端配置,请检查站点根地址的 ?mode=getconfig 是否返回包含 version 的 JSON 对象"),E5001:J("请求超时,请检查网络连接或禅道服务是否正常"),E5002:J("SSL/TLS 证书验证失败,请检查禅道服务地址是否正确"),E5003:"请求已取消",E5004:"无法启动 MCP HTTP 服务:{reason}"};B=class B extends Error{code;details;constructor(T,$,L){let Y=x1(N2[T],$);super(Y);this.name=J("ZentaoError"),this.code=T.replace("E",""),this.details=L}}});function xT(T){return T.replace(/^[a-zA-Z]+_(\d+)$/,"$1")}function N0(T){return Object.keys(T.pathParams??{}).find(($)=>$.endsWith("ID")&&$!=="scopeID")}function x0(T){return["get","update","delete","action"].includes(T.type)&&Boolean(N0(T))}function QT(T,$,L){let Y=(Q)=>{throw new B("E2009",{option:"ids",reason:Q})},W=N0(T);for(let Q of["id",...Object.keys(T.pathParams??{}).filter((X)=>X.endsWith("ID"))])if($[Q]!==void 0&&(Array.isArray($[Q])||String($[Q]).includes(",")))Y("单个目标不接受多个 ID,请使用 --ids");if($.id!==void 0&&!W)Y("此操作没有对象 ID");if(L===void 0)return;if(!x0(T))Y("此操作不支持批量对象操作");if($.id!==void 0||W&&$[W]!==void 0)Y("--ids 不能与单个目标同时使用");let H=L.split(",").map((Q)=>xT(Q.trim()));if(!H.length||H.some((Q)=>!/^\d+$/.test(Q)||!Number.isSafeInteger(Number(Q))||Number(Q)<1))Y("每个 ID 必须为正安全整数");return[...new Set(H.map(Number))]}var i0=N(()=>{S()});function R0(T){return T.replace(/IDs\b/g,"Ids").replace(/([A-Z]+)([A-Z][a-z])/g,"$1-$2").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function ET(T){let $=R0(T);return`--${["deadline","timeout","profile","config","format","color","input","yes","quiet","insecure","assistant","data","ids","fields","all","max-items","filter","sort","search"].includes($)?"data-":""}${$}`}function E0(T,$){let L=$.requestBody?.schema.properties;return z0(T.name,$.name).map((Y)=>({...Y,...Y.role==="body"?L?.[Y.name]:{},type:(Y.role==="body"?L?.[Y.name]?.type:void 0)??Y.type??(Y.role==="path"&&Y.name.endsWith("ID")?"integer":"string")}))}function U0(T,$){if($.type!=="list"||!$.pagerGetter)return;let L=E0(T,$),Y=L.find((H)=>["pageID","page"].includes(H.name)),W=L.find((H)=>["recPerPage","limit"].includes(H.name));return Y&&W?{page:Y,size:W}:void 0}function B0(T,$){let L=E0(T,$),Y=U0(T,$),W=L.find((H)=>H.role==="path"&&!["scope","scopeID"].includes(H.name));return{module:T.name,action:$.name,command:`${T.name} ${R0($.name)}`,display:$.display,description:$.description,type:$.type,path:$.path,method:$.method,minVersion:$.minVersion,parameters:L.map((H)=>({...H,flag:ET(H.name)})),target:W?.name,batch:x0($),pagination:Y?{page:Y.page.name,pageSize:Y.size.name}:null,requestBody:$.requestBody,readOnly:XT($),destructive:!XT($)&&["update","delete","action"].includes($.type),autoFill:$.type==="update"&&T.actions.some((H)=>H.type==="get"&&H.path===$.path),defaultFields:["id","title","name","status",...T.name==="bug"?["severity"]:[],"assignedTo"],localFiles:$.requestBody?.mediaType==="multipart/form-data"}}function XT(T){return(T.type==="list"||T.type==="get")&&(T.method??"get").toLowerCase()==="get"||T.type==="list"&&["/ai/knowledges/search","/ai/knowledges/embeddingssearch"].includes(T.path)}var O0=N(()=>{J0();i0()});import{existsSync as x2,readFileSync as E2}from"node:fs";import{dirname as h2,join as fT}from"node:path";import{fileURLToPath as f2}from"node:url";function a(){return"0.5.1"}var Z0=()=>{};function h0(T){try{if(typeof T!=="string")throw TypeError();new Headers({"ZenTao-Action-Assistant":T})}catch{throw new B("E2009",{option:"assistant",reason:"标记必须是有效的 HTTP 请求头字符串,不能包含换行或中文等非 Latin-1 字符"})}return T}function g(T,$=!0,L="cli"){return T!==void 0?h0(T):$?v2[L]:""}var vT,v2;var Y0=N(()=>{b();S();Z0();vT=`${w0?.packageName??"zentao-cli"} ${a()}`,v2={cli:`CLI <${vT}>`,stdio:`AI <${vT}, mcp: stdio>`,http:`AI <${vT}, mcp: http>`}});function m2(T){return typeof T==="string"&&g2.test(T)&&u2.test(T)&&c2.test(T)}function JT(T){if(m2(T))throw new B("E1004",void 0,{responseType:"login-page"})}async function v1(T){let $=T.headers.get("Content-Disposition")??"";if(/\battachment\b/i.test($))return;let L=T.headers.get("Content-Type")??"";if(!/\b(?:text\/html|application\/xhtml\+xml)\b/i.test(L))return;let Y=T.clone().body?.getReader();if(!Y)return;let W=new TextDecoder,H="",Q=0;try{while(Q<gT){let X=await Y.read();if(X.done){JT(H+W.decode());return}let G=gT-Q,U=X.value.subarray(0,G);Q+=U.byteLength,H+=W.decode(U,{stream:Q<gT}),JT(H)}}catch(X){if(X instanceof DOMException&&X.name==="AbortError")throw new B("E5001",void 0,X);throw X}finally{await Y.cancel().catch(()=>{return})}}var g2,u2,c2,gT=65536;var g1=N(()=>{S();g2=/^\s*<!doctype\s+html\b|^\s*<html\b/i,u2=/(?:id|name)\s*=\s*["']loginForm["']|user-login(?:\.html)?/i,c2=/<input\b[^>]*\bname\s*=\s*["']account["'][^>]*>/i});import{ZentaoClient as u1}from"zentao-api";function c(T,$,L){return new c1({baseUrl:T,token:$,insecure:L?.insecure,timeout:L?.timeout,actionAssistant:L?.actionAssistant??g()})}function i(T,$){if(!$)return T;let L=new u1(T.siteUrl),Y=(W)=>{let H=("signal"in W?W.signal:void 0)??$;if(H.aborted)throw new B("E5003");return{...W,signal:H}};return L.request=(W,H={})=>T.request(W,Y(H)),L.fetch=(W,H,Q,X)=>T.fetch(W,Y(H),Q,X),L.getZentaoConfig=(W={})=>T.getZentaoConfig(Y(W)),L}async function uT(T){try{return await T.getZentaoConfig()}catch($){throw v($)}}var c1;var V0=N(()=>{Y0();S();g1();c1=class c1 extends u1{async request(T,$){let L=await super.request(T,$);if(L instanceof Response)await v1(L);else JT(L);return L}}});var e,m1;var BT=N(()=>{e={autoAssistant:!0,defaultOutputFormat:"table",defaultRecPerPage:20,insecure:!1,timeout:1e4,htmlToMarkdown:!0,batchFailFast:!1,pagers:{},jsonPretty:!1},m1=Object.keys(e)});import d2 from"configstore";import{chmodSync as l2,existsSync as p2,mkdirSync as d1,rmdirSync as i2}from"node:fs";import{dirname as n2,isAbsolute as l1,join as cT,resolve as s2}from"node:path";import{homedir as mT}from"node:os";import{z as j}from"zod";function r2(){let T=process.env.XDG_CONFIG_HOME;return cT(T&&l1(T)?T:cT(mT(),".config"),J("zentao"),J("zentao.json"))}function p1(){if(!GT)GT=new d2(J("zentao-cli"),void 0,{configPath:u,clearInvalidConfig:!1});return GT}function a2(){try{if(p2(u))l2(u,384)}catch{}}function e2(T){try{p1().set(T),a2()}catch($){let L=$?.code;throw new B("E1011",{path:u},{operation:"write",reason:"write_failed",path:u,...L?{systemCode:L}:{}})}}function KT(T){let $=`${u}.lock`,L=!1;try{d1(n2(u),{recursive:!0,mode:448});let Y=Date.now()+5000;while(!L)try{d1($,{mode:448}),L=!0}catch(Q){if(Q.code!=="EEXIST")throw Q;if(Date.now()>=Y)throw new B("E1011",{path:u},{reason:"lock_timeout",path:$});Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}let W=s0(),H=T(W);return e2(W),H}catch(Y){if(Y instanceof B)throw Y;throw new B("E1011",{path:u},{operation:"write",reason:"write_failed",path:u,systemCode:Y.code})}finally{if(L)i2($)}}function TL(T){if(T==="~")return mT();if(T.startsWith("~/")||T.startsWith("~\\"))return cT(mT(),T.slice(2));return T}function i1(T){if(typeof T!=="string"||T.trim()==="")throw Error("setConfigPath: path must be a non-empty string");let $=TL(T),L=l1($)?$:s2($);if(GT&&L!==u)throw Error("setConfigPath: cannot change config path after store has been initialized");u=L}function s0(){let T;try{T=p1().all}catch($){let L=$?.code;throw new B("E1005",{path:u},{operation:"read",reason:$ instanceof SyntaxError?"invalid_json":"unreadable",path:u,...L?{systemCode:L}:{}})}if(!o2.safeParse(T).success)throw new B("E1005",{path:u},{operation:"read",reason:"invalid_structure",path:u});return T}function l(T,$){return`${T}@${$}`}function n(T){return T.replace(/\/+$/,"")}function W0(){let T=s0();if(!T.currentProfile||!T.profiles?.length)return;return T.profiles.find(($)=>l($.account,$.server)===T.currentProfile)}function IT(T,$){let L=s0(),Y=n($);return L.profiles?.find((W)=>W.account===T&&n(W.server)===Y)}function s(T){let $=s0().profiles??[],L=$.find((W)=>l(W.account,W.server)===T);if(L)return L;let Y=$.filter((W)=>W.account===T||`${W.account}@${new URL(W.server).hostname}`===T);if(Y.length>1)throw new B("E2009",{option:"profile",reason:"账号简写不唯一,请指定完整 key"},{candidates:Y.map((W)=>l(W.account,W.server))});return Y[0]}function f0(T){KT(($)=>{let L=n(T.server),Y=(G)=>G.account===T.account&&n(G.server)===L,W=$.profiles?.find(Y),H={...W,...T,server:L,config:W?.config??T.config,user:W?.user||T.user?{...W?.user,...T.user}:void 0,serverConfig:T.serverConfig??W?.serverConfig},Q=$.profiles??[],X=Q.findIndex(Y);$.profiles=Q.filter((G)=>!Y(G)),$.profiles.splice(X<0?$.profiles.length:X,0,H)})}function UT(T,$){return KT((L)=>{let Y=L.profiles??[];if(L.profiles=Y.filter((W)=>l(W.account,W.server)!==T||$!==void 0&&W.token!==$),L.currentProfile===T&&!L.profiles.some((W)=>l(W.account,W.server)===T))L.currentProfile=void 0;return L.profiles.length!==Y.length})}function t0(T){return KT(($)=>{let L=s(T);if(!L)return!1;return $.currentProfile=l(L.account,L.server),!0})}function VT(){return s0().profiles??[]}function t(T){return{...e,...T.config}}function dT(T,$,L){KT((Y)=>{let W=Y.profiles?.find((H)=>H.account===T.account&&H.server===T.server);if(!W)throw new B("E1007");if(W.config??={},L===void 0)delete W.config[$];else W.config[$]=L})}function FT(){return u}function F0(T,$,L,Y,W,H){let Q=new Date().toISOString();return{...H,server:n(T),account:$,token:L,user:H?{...H.user,...W}:W,loginTime:Q,lastUsedTime:Q,serverConfig:Y??H?.serverConfig}}var t2,o2,u,GT=null;var T0=N(()=>{b();S();BT();t2=j.object({autoAssistant:j.boolean(),defaultOutputFormat:j.enum(["table","markdown","json","raw"]),defaultRecPerPage:j.number().int().positive().max(1000),insecure:j.boolean(),timeout:j.number().int().positive(),htmlToMarkdown:j.boolean(),batchFailFast:j.boolean(),pagers:j.record(j.string(),j.number().int().positive().max(1000)),jsonPretty:j.boolean()}).partial().passthrough(),o2=j.object({currentProfile:j.string().optional(),profiles:j.array(j.object({server:j.string().url(),account:j.string(),token:j.string(),loginTime:j.string().optional(),lastUsedTime:j.string().optional(),user:j.record(j.string(),j.unknown()).optional(),config:t2.optional(),serverConfig:j.object({version:j.string()}).passthrough().optional()}).passthrough()).optional()}).passthrough();u=r2()});function A(){return CT?.signal}function n1(){return _T}function s1(T){CT=new AbortController,_T=void 0;let $=()=>{_T="interrupt",CT.abort(new B("E5003"))};process.once("SIGINT",$);let L=T.deadline?setTimeout(()=>{_T="deadline",CT.abort(new B("E5001"))},T.deadline):void 0;return L?.unref(),()=>{clearTimeout(L),process.removeListener("SIGINT",$)}}var CT,_T;var $0=N(()=>{S()});import{request as $L}from"zentao-api";async function DT(T,$,L){let Y,W=!1,H;for(let Q=1;;Q++){let X=await $L("user/list",{browseType:"inside",orderBy:"id_asc",recPerPage:100,pageID:Q,filters:[{field:"account",operator:"=",value:$}]},{client:T,throwOnFail:!0,actionAssistant:L}),G=Array.isArray(X.data)?X.data:[];if(W||=G.length>0,Y=G.find((K)=>K.account===$),Y||!G.length)break;let U=JSON.stringify(G.map((K)=>[K.id,K.account]));if(U===H||X.pager&&X.pager.page!==Q)throw new B("E2008",{url:T.siteUrl,status:"",serverResponse:"用户列表分页未向前推进,无法确认当前用户详情"});if(H=U,X.pager?Q*X.pager.recPerPage>=X.pager.total:G.length<100)break}return{user:Y,hadUsers:W}}var lT=N(()=>{S()});async function A0(T,$,L,Y){let W=c(T,void 0,Y),H=W.fetch;if(Y?.signal)W.fetch=(Q,X,G,U)=>{if(Y.signal?.aborted)throw new B("E5003");return H.call(W,Q,{...X,signal:Y.signal},G,U)};try{let Q;try{Q=await W.login($,L)}catch(U){throw v(U)}let X,G=await uT(W);try{({user:X}=await pT(W,$))}catch{}if(Y?.signal?.aborted)throw new B("E5003");return{client:W,token:Q,user:X,serverConfig:G}}finally{W.fetch=H}}async function pT(T,$){try{let L=await uT(T),{user:Y,hadUsers:W}=await DT(T,$);if(!W)throw new B("E1004");return{serverConfig:L,user:Y}}catch(L){throw v(L)}}function y0(){return{url:process.env[J("ZENTAO_URL")],account:process.env[J("ZENTAO_ACCOUNT")],password:process.env[J("ZENTAO_PASSWORD")],token:process.env[J("ZENTAO_TOKEN")]}}var o0=N(()=>{b();lT();V0();S()});function r0(T){if(typeof T==="string"){let Y=s(T);if(!Y)throw new B("E1007");T=Y}let $=y0();if(!T&&Object.values($).some(Boolean)&&!($.url&&$.account&&($.token||$.password)))throw new B("E1001",{},{reason:"incomplete_environment"});if(!T&&$.url&&$.account&&($.token||$.password))return{source:"environment",server:n($.url),account:$.account,token:$.token,password:$.password};let L=T??W0();if(L?.token)return{source:"profile",server:L.server,account:L.account,token:L.token,profile:L};throw new B("E1006")}async function H0(T){let $=T?.signal??A();if($?.aborted)throw new B("E5003");let L=r0(T?.profile),Y=L.source==="profile"?t(L.profile):void 0,W={insecure:T?.insecure??Y?.insecure,timeout:T?.timeout??Y?.timeout,actionAssistant:g(T?.assistant,Y?.autoAssistant,T?.assistantSource)};if(L.source==="environment"){let{server:H,account:Q,token:X,password:G}=L;if(X)return{client:i(c(H,X,W),$),profile:F0(H,Q,X)};let U=await A0(H,Q,G,{...W,signal:$});return{client:i(U.client,$),profile:F0(H,Q,U.token,U.serverConfig,U.user)}}return{client:i(c(L.server,L.token,W),$),profile:L.profile}}async function iT(T,$){let L=y0();if(!L.url||!L.account||!L.password)return;let Y;try{Y=n(L.url)}catch{return}if(Y!==n(T.server)||L.account!==T.account)return;let W=$?.signal??A(),H=await A0(T.server,T.account,L.password,{insecure:$?.insecure,timeout:$?.timeout,signal:W}),Q=F0(T.server,T.account,H.token,H.serverConfig,H.user);return f0(Q),{client:i(H.client,W),profile:Q}}var v0=N(()=>{V0();S();T0();$0();o0();Y0()});async function RT(T,$,L,Y){try{let H=await c(T,void 0,Y).post("/users/login",{account:$,password:L},{signal:Y?.signal});if(H?.status!=="success"||typeof H.token!=="string"||!H.token.trim())throw new B("E1003");return H.token}catch(W){throw v(W)}}var sT=N(()=>{V0();S()});function ST(T,$,L){let Y={...T};delete Y.assistant;let W=L?[...L]:[];if(W.length>0&&W[0]===$)W.shift();let H;if(W.length>0&&!W[0].startsWith("-")){let Q=W[0].trim(),X=Q.split(",").map((U)=>U.trim()).filter(Boolean);if(X.length>0&&X.every((U)=>/^\d+$/.test(U)))H=Q,W.shift();else if(Y.data===void 0&&Q.startsWith("{")&&Q.endsWith("}"))Y.data=Q,W.shift()}if(T.params)try{Object.assign(Y,JSON.parse(T.params))}catch{throw new B("E2009",{option:"params",reason:"不是有效的 JSON 对象"})}for(let Q of W){let X=Q.indexOf("="),G=Q.slice(2,X);if(!Q.startsWith("--")||X<3||!/^\w/.test(G)||/[^\w.-]/.test(G))throw new B("E2009",{option:X<0?Q:Q.slice(0,X),reason:"请使用 --字段名=值 传参"});let U=Q.slice(X+1);if(U==="true")U=!0;else if(U==="false")U=!1;else if(U!==""&&!/\D/.test(U))U=Number(U);Y[G]=U}if(H!==void 0)Y.id=H;return Y}var MT=N(()=>{S()});import nL from"turndown";function sL(){if(!W1)W1=new nL({headingStyle:"atx",codeBlockStyle:"fenced"});return W1}function q$(T){return tL.test(T)}function oL(T){if(!T||!q$(T))return T;return sL().turndown(T).trim()}function H1(T){let $={...T};for(let L of["desc","description","content","steps","spec","verify","comment","bio"]){let Y=$[L];if(typeof Y==="string"&&q$(Y))$[L]=oL(Y)}return $}function z$(T){return T.map(H1)}var W1=null,tL;var N$=N(()=>{tL=/<[a-z][\s\S]*>/i});import{readFile as rL}from"node:fs/promises";async function aL(){if(qT)return qT;if(process.stdin.isTTY||process.stdin.listenerCount("data")>0)return;return qT=(async()=>{let T=A();T?.throwIfAborted();let $=()=>process.stdin.destroy(new B("E5003"));T?.addEventListener("abort",$,{once:!0});try{let L=[];for await(let W of process.stdin)L.push(Buffer.from(W));return Buffer.concat(L).toString("utf-8").trim()||void 0}finally{T?.removeEventListener("abort",$)}})(),qT}function Q1(T){try{let $=JSON.parse(T);if(!$||typeof $!=="object"||Array.isArray($))throw new B("E2007");return $}catch{throw new B("E2007")}}async function zT(T){if(T===void 0)return;if(T==="@-"){let $=await aL();if($)return Q1($);if(T==="@-")throw new B("E2007");return}if(T.startsWith("@"))try{return Q1(await rL(T.slice(1),{encoding:"utf8",signal:A()}))}catch($){if($ instanceof B)throw $;throw new B("E2009",{option:"data",reason:"无法读取 JSON 文件"})}return Q1(T)}var qT;var X1=N(()=>{$0();S()});import{isDeepStrictEqual as eL}from"node:util";import{getModuleActionParams as T9}from"zentao-api";function u0(T,$,L){let Y=(H)=>{throw new B("E2009",{option:T,reason:H})},{type:W}=L;if(W==="number"||W==="integer"){if(typeof $!=="number"||!Number.isFinite($))Y("必须为有限数字");if(W==="integer"&&!Number.isSafeInteger($))Y("必须为安全整数")}else if(W==="array"?!Array.isArray($):W==="object"?!$||typeof $!=="object"||Array.isArray($):W&&typeof $!==W)Y(`必须为 ${W} 类型`);if(typeof $==="number"){if(L.minimum!==void 0&&$<L.minimum)Y(`不能小于 ${L.minimum}`);if(L.maximum!==void 0&&$>L.maximum)Y(`不能大于 ${L.maximum}`)}if(typeof $==="string"){let H=[...$].length;if(L.minLength!==void 0&&H<L.minLength)Y(`长度不能少于 ${L.minLength}`);if(L.maxLength!==void 0&&H>L.maxLength)Y(`长度不能超过 ${L.maxLength}`);if(L.pattern&&!new RegExp(L.pattern).test($))Y(`格式必须符合 ${L.pattern}`)}if(Array.isArray($)){if(L.minItems!==void 0&&$.length<L.minItems)Y(`至少需要 ${L.minItems} 个元素`);if(L.maxItems!==void 0&&$.length>L.maxItems)Y(`最多允许 ${L.maxItems} 个元素`);if(L.items)$.forEach((H,Q)=>u0(`${T}[${Q}]`,H,L.items))}if(L.options?.length){if((Array.isArray($)?$:[$]).some((Q)=>!L.options.some((X)=>X.value===Q)))Y(`可选值:${L.options.map((Q)=>Q.value).join(", ")}`)}}function Z$(T,$,L){let Y=T9(T.name,$.name);if(L.data!==void 0&&(!L.data||typeof L.data!=="object"||Array.isArray(L.data)))throw new B("E2009",{option:"data",reason:"请求体必须为 JSON 对象"});let W=L.data??{},H=Boolean($.requestBody),Q=(K,F)=>{throw new B("E2009",{option:K,reason:F})};for(let K of Object.keys(L)){if(K==="data"&&H)continue;if(!Y.some((F)=>F.name===K))Q(K,`操作 ${T.name}/${$.name} 不支持此参数`)}for(let K of Object.keys(W)){if(!Y.some((F)=>F.name===K&&F.role==="body"))Q(`data.${K}`,"不是此操作的请求体字段");if(L[K]!==void 0&&!eL(L[K],W[K]))Q(K,"params 与 params.data 中的参数值冲突")}let X=U0(T,$);if(X)for(let[K,F]of[[X.page,void 0],[X.size,X.size.maximum??1000]]){let I=W[K.name]??L[K.name];if(I!==void 0)u0(K.name,I,{...K,type:"integer",minimum:1,maximum:F})}let G=$.type==="update"&&T.actions.some((K)=>K.type==="get"&&K.path===$.path),U=$.requestBody?.schema.properties;for(let K of Y){let I=K.role==="body"&&Object.hasOwn(W,K.name)?W[K.name]:L[K.name];if(I===void 0){if(K.required&&K.defaultValue===void 0&&!(K.role==="body"&&G))throw new B("E2003",{fields:K.name,module:T.name});continue}let V=K.role==="path"&&K.name.endsWith("ID");if(u0(K.name,I,{...K,type:K.type??(V?"number":void 0),...K.role==="body"?U?.[K.name]:{}}),typeof I==="number"){if((V||K.name.endsWith("ID")||["pageID","recPerPage"].includes(K.name))&&(!Number.isSafeInteger(I)||I<0))Q(K.name,"必须为非负安全整数");if((K.name==="pageID"||K.name==="recPerPage")&&I<1)Q(K.name,"必须为大于 0 的整数");if(K.name==="recPerPage"&&I>1000)Q(K.name,"不能超过 1000")}}}var J1=N(()=>{O0();S()});import{request as A$,processData as $9}from"zentao-api";function y$(T){let $=T?.split(",").map((L)=>L.trim()).filter(Boolean);return $&&$.length>0?$:void 0}async function c0(T,$,L,Y,W,H,Q){let X=q0($,L);if(!X)throw new B("E2005",{module:$.name});let G=Q?{...Q}:ST(W,L,Y);if($.name==="relation"&&X.name==="unlink"){let M=["objectType","objectID","relatedObjectType","relatedObjectID","relationName"].filter((O)=>Object.hasOwn(G,O));if(M.length)throw new B("E2009",{option:M.join(", "),reason:"解除关联已改用关系记录 relationID,请从 relation list 的返回结果获取,不能用对象 ID 或 relationKey 代替"})}if($.name==="bug"&&X.name==="create"&&G.product!==void 0){if(G.productID!==void 0&&Number(G.product)!==Number(G.productID))throw new B("E2009",{option:"product/productID",reason:"--product 与 --productID 必须指定同一个产品"});if(G.productID===void 0)G.productID=G.product}if(X.requestBody){let M=G.data;if(M===void 0||typeof M==="string"){let O=await zT(M);if(O!==void 0)G.data=O}}let U=`${$.name}/${X.name}`,K=y$(W.pick),F=W.format??H.defaultOutputFormat??"table",I=F==="raw",V=W.htmlToMarkdown??(F!=="json"&&H.htmlToMarkdown!==!1);if(I&&(W.all||W.maxItems||W.pick||W.filter?.length||W.search?.length||W.sort||W.searchFields))throw new B("E2009",{option:"raw",reason:"原始响应不能与本地处理或自动翻页组合"});let C=U0($,X);if(W.all&&!C)throw new B("E2009",{option:"all",reason:"此操作不支持分页"});let _=G.data??{},q=(M)=>_[M]??G[M],z=(M,O)=>{if(G[M]=O,Object.hasOwn(_,M))_[M]=O};if(C){let M=Number(q(C.page.name)??W.page??1),O=Number(q(C.size.name)??W.recPerPage??H.pagers?.[$.name]??H.defaultRecPerPage??20);u0("page",M,{...C.page,type:"integer",minimum:1}),u0("page-size",O,{...C.size,type:"integer",minimum:1,maximum:C.size.maximum??1000}),z(C.page.name,M),z(C.size.name,O)}let w=!I,D=w&&X.type==="list",k=w&&X.type==="get",y={client:T,actionAssistant:W.assistant,autoFill:X.type==="update",throwOnFail:!0,recPerPage:C?String(q(C.size.name)):void 0,timeout:W.timeout,insecure:W.insecure,convert:D&&V?z$:void 0,convertSingle:k&&V?H1:void 0,filter:D?W.filter:void 0,search:D?W.search:void 0,searchFields:D?y$(W.searchFields):void 0,sort:D?W.sort:void 0,limit:D?W.maxItems:void 0,pick:D||k?K:void 0},R,x=[],m=0,r=0;try{if(I){let O=await A$(U,G,{...y,raw:!0});if(O&&typeof O==="object"&&"status"in O&&O.status==="fail"){let f="message"in O?O.message:void 0;throw new B("E2008",{url:"",status:"",serverResponse:typeof f==="string"?f:JSON.stringify(f??O)},O)}return{action:X,data:O,rawResponse:O,fields:K,isList:X.type==="list"}}let M;for(;;){if(R=await A$(U,G,{...y,raw:!1,convert:void 0,filter:void 0,search:void 0,sort:void 0,limit:void 0,pick:D?void 0:y.pick}),!D)break;let O=Array.isArray(R.data)?R.data:[];if(m+=O.length,x.push(...O),!W.all)break;let f=R.pager;if(!f)throw new B("E2008",{url:"",status:"",serverResponse:"服务端未返回分页信息,无法保证全量结果"});let E=JSON.stringify(O);if(f.page!==Number(q(C.page.name))||M!==void 0&&E===M)throw new B("E2008",{url:"",status:"",serverResponse:"服务端分页未向前推进"});if(f.page*f.recPerPage>=f.total)break;if(!O.length)throw new B("E2008",{url:"",status:"",serverResponse:"服务端返回空页但报告仍有数据"});M=E,z(C.page.name,f.page+1)}if(D){if(x=$9(x,{...y,limit:void 0}),r=x.length,W.maxItems)x=x.slice(0,Number(W.maxItems))}}catch(M){throw v(M)}let h=R.pager?{pageID:R.pager.page,recPerPage:R.pager.recPerPage,recTotal:R.pager.total}:void 0;if(X.type==="list"){let M=x,O=h?h.pageID*h.recPerPage<h.recTotal:null,f={returned:M.length,fetched:m,page:h?.pageID??null,pageSize:h?.recPerPage??null,total:h?.recTotal??null,hasMore:O,truncated:r>M.length,processingScope:W.all?"all":"page",totalScope:"serverBeforeLocalProcessing"},E=F==="table"&&!K&&M.some((X0)=>X0&&typeof X0==="object")?B0($,X).defaultFields.filter((X0)=>M.some((p0)=>p0&&Object.hasOwn(p0,X0))):K;return{action:X,data:M,rawResponse:R,pager:h,fields:E?.length?E:void 0,isList:!0,meta:f}}if(X.type==="get"){let M=R.data??{};return{action:X,data:M,rawResponse:R,fields:K,isList:!1}}return{action:X,data:R.data,rawResponse:R,fields:K,isList:!1}}var NT=N(()=>{S();N$();X1();MT();J0();S();O0();J1()});function TT(T,$,L){let Y=z0(T.name,$.name);if(Y.some((W)=>W.role==="path"&&W.name==="scope"&&W.options?.some((H)=>H.value===`${L}s`)))return"scopeID";return[`${L}ID`,L].find((W)=>Y.some((H)=>H.name===W&&(H.type==="number"||H.role==="path"&&!H.type&&W.endsWith("ID"))))}function ZT(T,$,L){let Y={...L.params},W=Object.keys($.pathParams??{}),H=W.includes("scope"),Q=(U,K)=>{throw new B("E2009",{option:U,reason:K})},X=(U,K)=>{if(K===void 0)return;if(Y[U]!==void 0&&String(Y[U])!==String(K))Q(U,"简写与 params 中的参数值冲突");Y[U]=K};for(let U of["product","project","execution"]){let K=L[U],F=`${U}ID`;if(H){let I=[K,Y[U],Y[F]].filter((V)=>V!==void 0);if(I.length){X("scope",`${U}s`);for(let V of I)X("scopeID",V);delete Y[U],delete Y[F]}}else if(K!==void 0){let I=TT(T,$,U);if(!I)Q(U,`操作 ${T.name}/${$.name} 不支持此数字简写,请按字段类型使用 params`);X(I,K)}}let G=W.find((U)=>U.endsWith("ID")&&U!=="scopeID");if(L.id!==void 0||Y.id!==void 0){if(!G)Q("id",`操作 ${T.name}/${$.name} 没有可简写的路径 ID`);X(G,L.id),X(G,Y.id),delete Y.id}if(X("pageID",L.page),X("recPerPage",L.recPerPage),$.requestBody){if(Y.data!==void 0&&(!Y.data||typeof Y.data!=="object"||Array.isArray(Y.data)))Q("params.data","MCP 请求体必须是 JSON 对象,请勿使用 CLI 字符串或管道语法");Y.data??={}}return Z$(T,$,Y),Y}var AT=N(()=>{J0();S();J1()});import{z as d}from"zod";function C0(T,$){let L={data:T??null,...$};return{structuredContent:L,content:[{type:"text",text:JSON.stringify($?L:T??null,null,2)}]}}function $T(T,$){T=v(T);let L=T instanceof B?`E${T.code}`:"E_INTERNAL",Y=T instanceof Error?T.message:String(T);return{isError:!0,structuredContent:{data:null,error:{code:L,message:Y,...$}},content:[{type:"text",text:`${L}: ${Y}`}]}}var m0,h$;var f$=N(()=>{S();m0=d.object({data:d.unknown(),error:d.object({code:d.string(),message:d.string(),module:d.string().optional(),action:d.string().optional()}).optional()}),h$=m0.extend({pager:d.object({pageID:d.number(),recPerPage:d.number(),recTotal:d.number()}).optional(),meta:d.object({processingScope:d.literal("page"),returnedCount:d.number().int().nonnegative(),totalScope:d.literal("serverBeforeLocalProcessing").optional()}).optional()})});import{z as P}from"zod";import{realpathSync as v$}from"node:fs";import{sep as g$}from"node:path";function LT(T){return XT(T)}function I1(T,$){if($.readOnly&&!LT(T))return!1;if(T.requestBody?.mediaType!=="multipart/form-data")return!0;return $.allowLocalFiles!==!1||$.localUploadRoot!==void 0}function U9(T,$){let L,Y;try{L=v$(T),Y=v$($)}catch{throw new B("E2009",{option:"file",reason:"文件或根目录不存在"})}if(L!==Y&&!L.startsWith(Y.endsWith(g$)?Y:Y+g$))throw new B("E2009",{option:"file",reason:"上传路径超出允许的根目录 ZENTAO_MCP_UPLOAD_ROOT"})}function V9(T){return J`${T.display??T.name}操作;参数、示例和最低版本见 zentao_action_help`}function F9(T){let $=T.actions.map((L)=>L.name);return[$[0],...$.slice(1)]}function C9(T){let $=F9(T),L=T.actions.flatMap((H)=>z0(T.name,H.name)),Y=new Set(L.map((H)=>H.name)),W={assistant:P.string().optional().describe("本次操作来源标记;省略继承服务设置,空字符串关闭"),action:P.enum($).describe(T.actions.map((H)=>`${H.name}: ${H.display??H.name}`).join("; ")),params:P.record(P.string(),P.unknown()).optional().describe(J("路径、查询或请求体参数;必填项见 zentao_action_help"))};if(L.some((H)=>H.role==="path"&&H.name.endsWith("ID")&&H.name!=="scopeID"))W.id=P.number().int().nonnegative().optional().describe("首个路径 ID 简写;多 ID 用 params");for(let H of["product","project","execution"])if(T.actions.some((Q)=>TT(T,Q,H)))W[H]=P.number().int().nonnegative().optional().describe(`${H}ID 或 scope/scopeID 简写,冲突时报错`);if(T.actions.some((H)=>H.type==="list"||H.type==="get"))W.pick=P.string().optional().describe("返回字段,逗号分隔");if(T.actions.some((H)=>H.type==="list"))W.all=P.boolean().optional().describe("显式遍历全部页面后本地处理"),W.maxItems=P.number().int().positive().optional().describe("整次调用最多返回条数"),W.filter=P.array(P.string()).optional().describe("当前页过滤,组内逗号为 AND、多组为 OR;远端筛选见 params.filters"),W.sort=P.string().optional().describe("当前页排序,如 pri:asc"),W.search=P.array(P.string()).optional().describe("当前页搜索,组内逗号为 AND、多组为 OR"),W.searchFields=P.string().optional().describe("搜索字段,逗号分隔");if(T.actions.some((H)=>x0(H)))W.ids=P.array(P.number().int().positive()).optional().describe("批量目标 ID;get/update/delete/action 类操作逐个执行并返回逐项结果"),W.batchFailFast=P.boolean().optional().describe("批量失败后跳过剩余目标");if(Y.has("pageID"))W.page=P.number().int().positive().optional().describe("页码,从 1 开始");if(Y.has("recPerPage"))W.recPerPage=P.number().int().min(1).max(1000).optional().describe("每页 1–1000 条");return P.object(W).strict()}function _9(T,$,L){let Y=$.requestBody?.schema.example,W=Object.fromEntries(z0(T.name,$.name).filter((H)=>H.required&&H.defaultValue===void 0).map((H)=>[H.name,(H.role==="body"?Y?.[H.name]:void 0)??(H.type==="array"?[]:H.options?.[0]?.value??(H.type==="number"||H.role==="path"&&H.name.endsWith("ID")?1:H.type==="boolean"?!1:H.type==="object"?{}:`<${H.name}>`))]));return{name:J`zentao_${T.name}${L?LT($)?"_read":"_write":""}`,arguments:{action:$.name,...Object.keys(W).length?{params:W}:{}},note:"ID、文本等均为格式示例,请替换为实际值后调用。"}}async function D9(T,$,L){if(L!==void 0)h0(L);let{client:Y,identity:W}=await T.getContext($);if(W.account===void 0)return C0({server:W.server,account:null,user:null,userFound:!1,note:J("无法仅凭禅道 Token 确定账号,未查询用户详情。")});let H=i(Y,$),{user:Q}=await DT(H,W.account,L),X={account:W.account,server:W.server,userFound:Boolean(Q),user:Q?Object.fromEntries(["id","account","realname","dept","role"].filter((G)=>Q[G]!==void 0).map((G)=>[G,Q[G]])):null};return C0(X)}async function w9(T,$){let{identity:L}=await $.switchProfile(T.profileKey),Y=`${L.account}@${L.server}`;return C0({status:"success",currentProfile:Y})}async function R9(T,$,L,Y,W){let H=$.assistant??Y.assistant;if(H!==void 0)h0(H);let Q=q0(T,$.action);if(!Q)throw new B("E2005",{module:T.name});if(!I1(Q,Y))throw new B("E2009",{option:`${T.name}/${Q.name}`,reason:u$});for(let V of["filter","sort","search","searchFields","pick"])if($[V]!==void 0&&Q.type!=="list"&&!(V==="pick"&&Q.type==="get"))throw new B("E2009",{option:V,reason:`不适用于 ${T.name}/${Q.name}`});if(($.all!==void 0||$.maxItems!==void 0)&&Q.type!=="list")throw new B("E2009",{option:"all/maxItems",reason:`不适用于 ${T.name}/${Q.name}`});if($.ids!==void 0){if(!x0(Q))throw new B("E2009",{option:"ids",reason:"此操作不支持批量对象操作"});if(!$.ids.length)throw new B("E2009",{option:"ids",reason:"至少需要一个目标 ID"})}let X=ZT(T,Q,$);if(Q.requestBody?.mediaType==="multipart/form-data"&&Y.allowLocalFiles===!1&&Y.localUploadRoot!==void 0){let V=X.file,C=X.data?.file,_=typeof V==="string"?V:typeof C==="string"?C:void 0;if(!_)throw new B("E2009",{option:"file",reason:"需要本地文件路径"});U9(_,Y.localUploadRoot)}let{client:G,config:U}=await L.getContext(W),K=$.action,F={assistant:H,pick:$.pick,filter:$.filter,sort:$.sort,search:$.search,searchFields:$.searchFields,recPerPage:$.recPerPage!=null?String($.recPerPage):void 0,all:$.all,maxItems:$.maxItems!=null?String($.maxItems):void 0,batchFailFast:$.batchFailFast,format:"json"};if($.ids?.length){let V=N0(Q),C=i(G,W),_=[],q=0,z=0,w=[];for(let D=0;D<$.ids.length;D++){let k=$.ids[D];W?.throwIfAborted();try{let y=await c0(C,T,K,[],F,U,{...X,[V]:k});_.push({objectID:k,ok:!0,data:y.data??y.rawResponse??null})}catch(y){W?.throwIfAborted(),q++;let R=y instanceof B?y:Error(String(y));if(w.push({objectID:k,error:{...R instanceof B?{code:`E${R.code}`}:{},message:R.message}}),_.push({objectID:k,ok:!1,error:{message:R.message}}),$.batchFailFast){z=$.ids.length-D-1;break}}}return C0({ok:q===0,data:_,meta:{success:$.ids.length-q-z,failed:q,skipped:z,...w.length?{errors:w}:{}}})}let I=await c0(i(G,W),T,K,[],F,U,X);if(I.action.type==="list")return C0(I.data,{...I.pager?{pager:I.pager}:{},meta:{processingScope:"page",returnedCount:Array.isArray(I.data)?I.data.length:0,...I.pager?{totalScope:"serverBeforeLocalProcessing"}:{}}});if(I.action.type==="get")return C0(I.data);return C0(I.data??I.rawResponse)}function O9(T){let $=T.every(LT),L=T.some((Y)=>["update","delete","action"].includes(Y.type));return{readOnlyHint:$,destructiveHint:L,openWorldHint:!0}}function c$(T,$,L={}){let Y=L.modules?[...new Set(L.modules)].map((W)=>{let H=I0(W);if(!H)throw new B("E2001",{module:W});return H}):b1();if(!Y.length)throw new B("E2009",{option:"modules",reason:"至少指定一个模块"});if(T.registerTool(J("zentao_action_help"),{description:J("查看禅道操作的路径、参数定义和最低版本要求,无需登录;调用业务工具前可按需查询"),inputSchema:P.object({module:P.string().describe("模块名,如 doc、story"),action:P.string().describe("操作名,如 createMyDoc、getGrades")}).strict(),outputSchema:m0,annotations:{readOnlyHint:!0,destructiveHint:!1,openWorldHint:!1}},async({module:W,action:H})=>{try{let Q=I0(W);if(!Q)throw new B("E2001",{module:W});let X=q0(Q,H);if(!X)throw new B("E2005",{module:Q.name});return C0({...B0(Q,X),available:Y.some((G)=>G.name===Q.name)&&I1(X,L),...L.allowLocalFiles===!1&&L.localUploadRoot===void 0&&X.requestBody?.mediaType==="multipart/form-data"?{unavailableReason:u$}:{},example:_9(Q,X,L.splitTools)})}catch(Q){return $T(Q,{module:W,action:H})}}),T.registerTool(J("zentao_profile"),{description:"获取当前 MCP 绑定的账号和站点;已知账号时查询远端用户详情,仅 Token 认证时账号未知。userFound=false 表示无用户详情,服务端失败会报错",inputSchema:P.object({assistant:P.string().optional().describe("本次操作来源标记;省略继承服务设置,空字符串关闭")}).strict(),outputSchema:m0,annotations:{readOnlyHint:!0,destructiveHint:!1,openWorldHint:!0}},async(W,H)=>{try{return await D9($,H.signal,W.assistant??L.assistant)}catch(Q){return $T(Q,{module:"user",action:"list"})}}),$.switchProfile&&!L.readOnly)T.registerTool(J("zentao_switch_profile"),{description:"切换当前 MCP 实例的登录账号,不改变 CLI 或其他 MCP 实例的账号",inputSchema:P.object({profileKey:P.string().describe("目标用户配置标识,支持 account@server、account 或 account@hostname")}).strict(),outputSchema:m0,annotations:{readOnlyHint:!1,destructiveHint:!1,openWorldHint:!0}},async(W)=>{try{return await w9(W,$)}catch(H){return $T(H)}});for(let W of new Set(Y)){let H=W.actions.filter((X)=>I1(X,L)),Q=L.splitTools?[{suffix:"_read",actions:H.filter(LT)},{suffix:"_write",actions:H.filter((X)=>!LT(X))}]:[{suffix:"",actions:H}];for(let X of Q){if(!X.actions.length)continue;let G={...W,actions:X.actions},U=J`zentao_${G.name}${X.suffix}`,K=V9(G),F=C9(G),I=O9(G.actions);T.registerTool(U,{description:K,inputSchema:F,outputSchema:G.actions.some((V)=>V.type==="list")?h$:m0,annotations:I},async(V,C)=>{let _=V;try{if(!X.actions.some((q)=>q.name===_.action))throw new B("E2006");return await R9(W,_,$,L,C.signal)}catch(q){return $T(q,{module:G.name,action:_.action})}})}}}var u$="HTTP MCP 不支持通过本地路径上传服务端文件,请使用本地 CLI 或 stdio MCP";var m$=N(()=>{b();lT();O0();J0();J0();NT();S();V0();Y0();AT();f$();i0()});import{defineModuleActions as _0,extendModuleAction as d$}from"zentao-api";function S0(T,$,L,Y,W){let H={name:$,display:L,type:"action",method:"put",path:`/${T}s/{${Y}}/${$}`,resultType:"text",minVersion:D0,pathParams:{[Y]:`${T} ID`}};if(W?.query)H.params=W.query;if(W?.properties||W?.required)H.requestBody={required:!0,type:"object",schema:{type:"object",properties:W?.properties??{},required:W?.required??[]}};return H}function M9(){_0("bug",[S0("bug","assignto","指派Bug","bugID",{properties:U1,required:["assignedTo"]})]),_0("task",[S0("task","pause","暂停任务","taskID",{properties:l$}),S0("task","cancel","取消任务","taskID",{properties:l$}),S0("task","restart","继续任务","taskID",{properties:{realStarted:{type:"string",description:"实际开始"},consumed:{type:"number",description:"总计消耗",format:"float"},left:{type:"number",description:"预计剩余",format:"float"},comment:{type:"string",description:"备注"}},required:["realStarted"]}),S0("task","assignto","指派任务","taskID",{query:[{name:"executionID",required:!0,type:"number",description:"执行ID"}],properties:{assignedTo:{type:"string",description:"指派给"},left:{type:"number",description:"预计剩余",format:"float"},comment:{type:"string",description:"备注"}},required:["assignedTo","left"]})]);let T=[{module:"story",idKey:"storyID",displayPrefix:"需求"},{module:"epic",idKey:"storyID",displayPrefix:"业务需求"},{module:"requirement",idKey:"storyID",displayPrefix:"用户需求"}];for(let{module:$,idKey:L,displayPrefix:Y}of T)_0($==="story"?"story":$,[S0($,"review",`${Y}评审`,L,{properties:{assignedTo:{type:"string",description:"指派给"},result:{type:"string",description:"评审结果",options:S9},reviewedDate:{type:"string",description:"评审时间"},comment:{type:"string",description:"备注"}},required:["result","reviewedDate","comment"]})]);_0("feedback",[S0("feedback","assignto","指派反馈","feedbackID",{properties:U1,required:["assignedTo"]})]),_0("ticket",[S0("ticket","assignto","指派工单","ticketID",{properties:U1,required:["assignedTo"]})])}function q9(){_0("task",[{name:"recordestimate",display:"记录任务工时",type:"action",method:"put",path:"/tasks/{taskID}/recordworkhour",resultType:"text",minVersion:D0,pathParams:{taskID:"任务 ID"},requestBody:{required:!0,type:"object",schema:{type:"object",properties:{date:{type:"array",items:{type:"string"},description:"日期,格式 YYYY-MM-DD,默认今天"},work:{type:"array",items:{type:"string"},description:"工作内容"},consumed:{type:"array",items:{type:"number"},description:"本次耗时(小时,累加到总计)"},left:{type:"array",items:{type:"number"},description:"更新后的剩余工时(小时,覆盖之前值)"}},required:["date","consumed","left"]}}},{name:"effort",display:"获取任务工时记录",type:"list",method:"get",path:"/tasks/{taskID}/recordworkhour",resultType:"list",minVersion:D0,pathParams:{taskID:"任务 ID"},params:[{name:"taskID",required:!0,type:"number",description:"任务 ID"}],resultGetter:(T)=>{let $=T?.efforts;return $?Object.values($):[]}},{name:"editeffort",display:"编辑工时记录",type:"action",method:"put",path:"/tasks/{effortID}/editeffort",resultType:"text",minVersion:D0,pathParams:{effortID:"工时记录 ID"},params:[{name:"effortID",required:!0,type:"number",description:"工时记录 ID"}],requestBody:{required:!0,type:"object",schema:{type:"object",properties:{date:{type:"string",description:"日期,格式 YYYY-MM-DD"},work:{type:"string",description:"工作内容"},consumed:{type:"number",description:"本次耗时(小时,累加到总计)",format:"float"},left:{type:"number",description:"更新后的剩余工时(小时,覆盖之前值)",format:"float"}},required:["consumed","left"]}}},{name:"deleteeffort",display:"删除工时记录",type:"delete",method:"delete",path:"/tasks/{effortID}/deleteworkhour",resultType:"text",minVersion:D0,pathParams:{effortID:"工时记录 ID"},params:[{name:"effortID",required:!0,type:"number",description:"工时记录 ID"}]}])}function z9(){let T=[{module:"build",display:"获取版本详情",idKey:"buildID",resultGetter:"build"},{module:"release",display:"获取发布详情",idKey:"releaseID",resultGetter:"release"},{module:"testtask",display:"获取测试单详情",idKey:"testtaskID",resultGetter:"testtask"}];for(let $ of T)_0($.module,{name:"get",display:$.display,type:"get",method:"get",path:`/${$.module}s/{${$.idKey}}`,resultType:"object",resultGetter:$.resultGetter,minVersion:D0,pathParams:{[$.idKey]:`${$.module} ID`}})}function N9(){for(let T of["create","update"])d$("bug",T,($)=>{let L=$.requestBody?.schema;if(!L)return $;return L.properties={...L.properties??{},deadline:{type:"string",description:"截止日期,格式 YYYY-MM-DD"},module:{type:"number",description:"所属模块 ID"}},$});d$("project","create",(T)=>{let $=T.requestBody?.schema;if(!$)return T;if($.properties={...$.properties??{},desc:{type:"string",description:"项目描述"}},!$.required?.includes("desc"))$.required=[...$.required??[],"desc"];return T})}function A9(T){let{status:$,...L}=T??{};return Object.values(L).filter((Y)=>Y&&typeof Y==="object")}function y9(){for(let T of Z9){let $=T.idKey,L={[$]:`${T.display} ID`},Y=T.detailPath?{name:"history",display:`获取${T.display}历史记录`,type:"list",method:"get",path:T.detailPath,resultType:"list",resultGetter:"actions",minVersion:D0,pathParams:L}:{name:"history",display:`获取${T.display}历史记录`,type:"list",method:"get",path:`/action/ajaxGetList?objectType=${T.actionObjectType}&objectID={${$}}`,resultType:"list",resultGetter:A9,minVersion:D0,pathParams:L};_0(T.module,Y),_0(T.module,{name:"comment",display:`添加${T.display}备注`,type:"action",method:"post",path:`/actions/comment?objectType=${T.actionObjectType}&objectID={${$}}`,resultType:"text",minVersion:D0,pathParams:L,requestBody:{required:!0,type:"object",schema:{type:"object",properties:{comment:{type:"string",description:"备注内容"}},required:["comment"]}}})}}function yT(){if(p$)return;p$=!0,M9(),q9(),z9(),N9(),y9()}var D0,U1,l$,S9,Z9,p$=!1;var V1=N(()=>{D0=["22.0","biz13.0","max8.0","ipd5.0"];U1={assignedTo:{type:"string",description:"指派给"},comment:{type:"string",description:"备注"}},l$={comment:{type:"string",description:"备注"}},S9=[{value:"pass",label:"通过"},{value:"reject",label:"拒绝"},{value:"clarify",label:"需澄清"}];Z9=[{module:"bug",display:"Bug",idKey:"bugID",actionObjectType:"bug",detailPath:"/bugs/{bugID}"},{module:"task",display:"任务",idKey:"taskID",actionObjectType:"task",detailPath:"/tasks/{taskID}"},{module:"story",display:"需求",idKey:"storyID",actionObjectType:"story",detailPath:"/stories/{storyID}"},{module:"epic",display:"业务需求",idKey:"storyID",actionObjectType:"story"},{module:"requirement",display:"用户需求",idKey:"storyID",actionObjectType:"story"},{module:"testcase",display:"用例",idKey:"caseID",actionObjectType:"testcase",detailPath:"/testcases/{caseID}"},{module:"testtask",display:"测试单",idKey:"testtaskID",actionObjectType:"testtask",detailPath:"/testtasks/{testtaskID}"},{module:"feedback",display:"反馈",idKey:"feedbackID",actionObjectType:"feedback",detailPath:"/feedbacks/{feedbackID}"},{module:"ticket",display:"工单",idKey:"ticketID",actionObjectType:"ticket"},{module:"product",display:"产品",idKey:"productID",actionObjectType:"product"},{module:"project",display:"项目",idKey:"projectID",actionObjectType:"project"},{module:"execution",display:"执行",idKey:"executionID",actionObjectType:"execution"},{module:"build",display:"版本",idKey:"buildID",actionObjectType:"build",detailPath:"/builds/{buildID}"},{module:"release",display:"发布",idKey:"releaseID",actionObjectType:"release",detailPath:"/releases/{releaseID}"},{module:"productplan",display:"计划",idKey:"planID",actionObjectType:"productplan",detailPath:"/productplans/{planID}"},{module:"program",display:"项目集",idKey:"programID",actionObjectType:"program"}]});import{McpServer as P9}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as k9}from"@modelcontextprotocol/sdk/server/stdio.js";function PT({client:T,profile:$}){return{client:T,config:t($),identity:{server:$.server,account:$.account}}}function b9(T){g(T?.assistant,!0,"stdio");let $={...T,assistantSource:"stdio"},L,Y,W=y0(),H=Boolean(!T?.profile&&W.url&&W.account&&(W.token||W.password));return{async getContext(Q){if(Q?.aborted)throw new B("E5003");if(!L){let q=new AbortController,z=H0({...$,signal:q.signal}),w={promise:z,controller:q,pending:!0,waiters:0};Y=w,L=z,z.finally(()=>{w.pending=!1}).catch(()=>{}),z.catch(()=>{if(L===z)L=void 0})}let X=L,G=H,U=Y?.promise===X?Y:void 0;if(U)U.waiters++;let K,F;try{F=await(Q?Promise.race([X,new Promise((q,z)=>{K=()=>z(new B("E5003")),Q.addEventListener("abort",K,{once:!0})})]):X)}finally{if(K)Q?.removeEventListener("abort",K);if(U&&--U.waiters===0&&U.pending){if(U.controller.abort(),L===X)L=void 0}}if(Q?.aborted)throw new B("E5003");if(G)return PT(F);let I=IT(F.profile.account,F.profile.server);if(!I?.token)throw new B("E1006");let V=t(I),C=t(F.profile);if(I.token===F.profile.token&&(T?.timeout??V.timeout)===(T?.timeout??C.timeout)&&(T?.insecure??V.insecure)===(T?.insecure??C.insecure)&&g(T?.assistant,V.autoAssistant,"stdio")===g(T?.assistant,C.autoAssistant,"stdio"))return PT({client:F.client,profile:I});let _=H0({...$,profile:I});if(L===X)L=_;return PT(await _)},async switchProfile(Q){let X=s(Q);if(!X)throw new B("E1007");let G=await H0({...$,profile:X});return L=Promise.resolve(G),H=!1,PT(G)}}}function d0(T,$){yT();let L=new P9({name:J("zentao-cli"),version:a()},{capabilities:{tools:{}}});return c$(L,T,$),L}async function F1(T){let $=d0(b9(T),T),L=new k9;await $.connect(L)}var C1=N(()=>{b();v0();T0();o0();S();m$();Z0();Y0();V1()});var j9,x9,l0;var _1=N(()=>{b();j9={language:"语言",darkMode:"深色模式",switchDark:"切换至深色模式",switchLight:"切换至浅色模式",title:J("接入禅道 MCP"),site:J("禅道站点"),steps:"接入步骤",progress:"接入进度",step1:"准备 Token",step2:"配置 Agent",step3:"验证连接",method:"Token 获取方式",login:"账号登录",existing:"已有 Token",username:"用户名",password:"密码",usernamePlaceholder:J("禅道用户名"),passwordPlaceholder:"输入密码",personalToken:"个人 Token",getToken:"获取 Token 并继续",continue:"继续配置",trust:J("账号密码经此服务发送至禅道,不保存。"),retention:"Token 仅保留在当前页面,刷新或关闭后清除。",skip:"稍后填写 Token,先看配置",tokenReady:"已填写",tokenEmpty:"未填写",enterToken:"填写 Token",copyToken:"复制 Token",clearToken:"清除 Token",setupMethod:"配置方式",agentSetup:"让 Agent 配置",changeToken:"更换 Token",expand:"展开",collapse:"收起",expandInstructions:"展开接入说明",collapseInstructions:"收起接入说明",setupIntro:"建议不向 AI 提供 Token。复制说明,让 Agent 告知 MCP 配置文件位置和 Token 设置方法,再由你在本机填写。",includeToken:"复制说明或配置时附带 Token(有风险)",includeWarning:J("发送给 AI 后,Token 可能被 AI 服务商处理,并保存在对话记录或日志中;泄露后他人可能以你的权限访问禅道。预览仍隐藏 Token。"),copyInstructions:"复制接入说明",copiedInstructions:"已复制 · 让 Agent 说明配置位置和 Token 设置方法",previewPrompt:"预览说明",manual:"手动配置",chooseAgent:"选择 Agent",copyConfig:"复制配置",nextVerify:"配置好了,去验证",verifyTitle:"在 Agent 中验证",verifyIntro:"重载或重启 Agent 后,发送这条提问:",verifyPrompt:J("请通过 zentao-remote MCP 查询我有权访问的产品列表,只显示 ID 和名称。"),copyVerify:"复制验证提问",copiedVerify:"已复制 · 去 Agent 中发送",verifyResult:"检查返回的产品 ID 和名称。列表为空时,请确认账号的产品访问权限。",troubleshoot:"没有连接成功?",troubleshootText:"确认 MCP 服务已启用,且 Agent 能访问服务地址。Token 失效时,重新获取并更新 Agent 配置。",backSetup:"返回配置",details:"接入详情",mcpAddress:"MCP 地址:",localOnly:"此地址仅供同一台电脑上的 Agent 使用。",guide:"完整接入指南 ↗",copied:"已复制",showPassword:"显示密码",hidePassword:"隐藏密码",showToken:"显示 Token",hideToken:"隐藏 Token",required:J("请填写禅道用户名和密码。"),invalidToken:"请只粘贴 Token 值,不要包含引号、请求头名称或空格。",tokenRequired:"请填写个人 Token。",submitting:"正在获取…",connecting:J("正在连接禅道,请稍候。"),networkError:"连接失败,请检查网络后重试。",copyFailed:"复制失败,请允许浏览器访问剪贴板,或手动复制预览并填写 Token。",copiedSecret:"已复制,内容包含个人 Token,请妥善保管。",clearedNotice:"页面中的 Token 已清除。已复制或保存到 Agent 的 Token 不受影响。",insecure:"请通过管理员提供的 HTTPS 地址打开,再填写密码或 Token。本机可使用 http://127.0.0.1。",noScript:"请启用 JavaScript 后获取 Token 和复制配置。",readOnly:"仅开放查询",readWrite:"开放查询与操作",allModules:"全部可用模块",accountPermissions:J("实际权限以你的禅道账号为准。"),reachable:"Agent 所在环境需要能访问此地址。",officialDocs:"官方配置文档 ↗",mergeHint:"合并到已有配置,保留其他服务。",noQuery:"请使用不含查询参数的接入页面。",pageMethod:"请通过浏览器打开接入页面。",postOnly:"仅支持 POST。",invalidOrigin:"请求来源不正确,请重新打开接入页面。",expired:"请求来源不正确或服务已重启,请刷新页面后重试。",httpsRequired:"请通过管理员提供的 HTTPS 地址获取 Token。",jsonRequired:"请通过接入页面提交 JSON 登录信息。",busy:"获取 Token 的用户较多,请稍后重试。",tooLarge:"登录信息过长,请检查输入。",bodyTimeout:"接收请求超时,请重试。",invalidJson:"登录信息格式不正确。",invalidCredentialsInput:J("请填写有效的禅道用户名和密码,禅道地址由管理员设置。"),cancelled:"请求已取消。",invalidTokenResponse:J("禅道返回的 Token 格式无效,请联系管理员。"),invalidCredentials:"用户名或密码不正确,或当前账号不允许登录,请检查后重试。",timeout:J("连接禅道超时,请稍后重试。"),certificate:J("禅道的 HTTPS 证书验证失败,请联系管理员。"),loginFailed:J("无法获取 Token,请检查网络,或联系管理员确认禅道服务和 API 登录是否可用。")},x9={language:"Language",darkMode:"Dark mode",switchDark:"Switch to dark mode",switchLight:"Switch to light mode",title:J("Connect ZenTao MCP"),site:J("ZenTao site"),steps:"Connection steps",progress:"Connection progress",step1:"Get token",step2:"Set up Agent",step3:"Verify",method:"Token source",login:"Sign in",existing:"Use a token",username:"Username",password:"Password",usernamePlaceholder:J("ZenTao username"),passwordPlaceholder:"Enter your password",personalToken:"Personal token",getToken:"Get token and continue",continue:"Continue to setup",trust:J("Credentials are sent to ZenTao through this service and are not stored."),retention:"Your token stays on this page and is cleared when you refresh or close it.",skip:"Set up first, add a token later",tokenReady:"Added",tokenEmpty:"Not added",enterToken:"Add token",copyToken:"Copy token",clearToken:"Clear token",setupMethod:"Setup method",agentSetup:"Let Agent set up",changeToken:"Change token",expand:"Expand",collapse:"Collapse",expandInstructions:"Expand setup instructions",collapseInstructions:"Collapse setup instructions",setupIntro:"Keep your token out of AI prompts. Copy the instructions so your Agent can explain which MCP config file to edit and how to set the token locally.",includeToken:"Include token in copied setup (risky)",includeWarning:J("If sent to AI, your token may be processed by the AI provider and stored in chat history or logs. If exposed, others could access ZenTao with your permissions. The preview still hides your token."),copyInstructions:"Copy setup instructions",copiedInstructions:"Copied · Ask your Agent where and how to set the token",previewPrompt:"Preview",manual:"Manual setup",chooseAgent:"Choose your Agent",copyConfig:"Copy config",nextVerify:"Setup done, verify connection",verifyTitle:"Verify in your Agent",verifyIntro:"Reload or restart your Agent, then send this prompt:",verifyPrompt:J("Use the zentao-remote MCP to query the products I can access. Show only their IDs and names."),copyVerify:"Copy verification prompt",copiedVerify:"Copied · Send it to your Agent",verifyResult:"Check the returned product IDs and names. If the list is empty, check your account’s product permissions.",troubleshoot:"Having trouble connecting?",troubleshootText:"Check that the MCP server is enabled and its address is reachable from your Agent. If your token has expired, get a new one and update the Agent config.",backSetup:"Back to setup",details:"Connection details",mcpAddress:"MCP address: ",localOnly:"This address only works for an Agent running on the same computer.",guide:"Full setup guide ↗",copied:"Copied",showPassword:"Show password",hidePassword:"Hide password",showToken:"Show token",hideToken:"Hide token",required:J("Enter your ZenTao username and password."),invalidToken:"Paste only the token value, without quotes, header names or spaces.",tokenRequired:"Enter your personal token.",submitting:"Getting token…",connecting:J("Connecting to ZenTao…"),networkError:"Connection failed. Check your network and try again.",copyFailed:"Copy failed. Allow clipboard access, or copy the preview and add your token locally.",copiedSecret:"Copied with your personal token. Keep it private.",clearedNotice:"Token cleared from this page. Copies already saved in your Agent are unchanged.",insecure:"Open the HTTPS address provided by your administrator before entering credentials. On this computer, you can use http://127.0.0.1.",noScript:"Enable JavaScript to get a token and copy the configuration.",readOnly:"Queries only",readWrite:"Queries and actions enabled",allModules:"All available modules",accountPermissions:J("Your ZenTao account permissions apply."),reachable:"This address must be reachable from your Agent.",officialDocs:"Official setup docs ↗",mergeHint:"Merge into your existing config and preserve other services.",noQuery:"Open the connection page without query parameters.",pageMethod:"Open the connection page in your browser.",postOnly:"Only POST requests are supported.",invalidOrigin:"Invalid request origin. Reopen the connection page.",expired:"The request origin is invalid or the service restarted. Refresh the page and try again.",httpsRequired:"Use the HTTPS address provided by your administrator to get a token.",jsonRequired:"Submit your sign-in details through the connection page.",busy:"Too many token requests. Wait a moment and try again.",tooLarge:"Sign-in details are too long. Check your input.",bodyTimeout:"Receiving the request timed out. Try again.",invalidJson:"The sign-in request format is invalid.",invalidCredentialsInput:J("Enter a valid ZenTao username and password. The site address is set by your administrator."),cancelled:"Request cancelled.",invalidTokenResponse:J("ZenTao returned an invalid token. Contact your administrator."),invalidCredentials:"The username or password is incorrect, or this account cannot sign in. Check your details and try again.",timeout:J("The ZenTao connection timed out. Try again later."),certificate:J("ZenTao’s HTTPS certificate could not be verified. Contact your administrator."),loginFailed:J("Could not get a token. Check your network, or ask your administrator to check ZenTao and API sign-in.")},l0={zh:j9,en:x9}});var i$;var n$=N(()=>{b();i$=A1`
|
|
4
2
|
(() => {
|
|
5
3
|
const $ = id => document.getElementById(id);
|
|
6
4
|
const root = document.documentElement;
|
|
@@ -241,31 +239,31 @@ var E=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(o){n=[o]}if(n)throw n[0];return t};f
|
|
|
241
239
|
feedback('zt-login-feedback', 'trust');
|
|
242
240
|
render();
|
|
243
241
|
})();
|
|
244
|
-
`});function
|
|
245
|
-
url = ${JSON.stringify(
|
|
246
|
-
http_headers = { token = ${JSON.stringify(
|
|
242
|
+
`});function E9(T,$,L,Y="zh"){if(T==="codex")return`[mcp_servers.zentao-remote]
|
|
243
|
+
url = ${JSON.stringify($)}
|
|
244
|
+
http_headers = { token = ${JSON.stringify(L)} }`;if(T==="cherry"&&Y==="en")return`Name: zentao-remote
|
|
247
245
|
Type: Streamable HTTP
|
|
248
|
-
URL: ${
|
|
249
|
-
Header: token: ${
|
|
250
|
-
Authentication: Personal token (no OAuth)`;if(
|
|
246
|
+
URL: ${$}
|
|
247
|
+
Header: token: ${L}
|
|
248
|
+
Authentication: Personal token (no OAuth)`;if(T==="cherry")return`名称:zentao-remote
|
|
251
249
|
类型:Streamable HTTP
|
|
252
|
-
URL:${
|
|
253
|
-
请求头:token: ${
|
|
254
|
-
认证:个人 Token(无需 OAuth)`;let
|
|
255
|
-
`);return["请帮我在当前使用的 Agent 中配置公司的禅道 MCP 服务。","","服务名称:zentao-remote",`禅道地址:${
|
|
256
|
-
`)}function
|
|
250
|
+
URL:${$}
|
|
251
|
+
请求头:token: ${L}
|
|
252
|
+
认证:个人 Token(无需 OAuth)`;let W={token:L};if(T==="opencode")return JSON.stringify({mcp:{"zentao-remote":{type:"remote",url:$,headers:W,oauth:!1,enabled:!0}}},null,2);let H=T==="gemini"?{httpUrl:$,headers:W}:{type:T==="cline"?"streamableHttp":"http",url:$,headers:W};return JSON.stringify({[T==="vscode"?"servers":"mcpServers"]:{"zentao-remote":H}},null,2)}function h9(T,$,L,Y="zh"){if(Y==="en")return["Help me configure our ZenTao MCP service in the Agent I am currently using.","","Server name: zentao-remote",`ZenTao site: ${T}`,`MCP server URL: ${$}`,"Transport: Streamable HTTP",`Authentication header: token: ${L}`,"","Follow the official documentation for this Agent to prepare the user-level MCP configuration, preserving existing services.","Tell me the full path of the MCP configuration file to edit, the field for the token request header, and how to set it. For settings managed through a UI, give me the entry point and field.","If the token is a placeholder, I will fill in the real value locally. Do not ask me to send my ZenTao password or token in this conversation.","There is no need to install zentao-cli or start an MCP process locally.","Use the token only in request headers. Do not display the real token in replies or commit it to a repository.","Wait until I have set the token locally, then explain how to reload or restart the Agent.","Finally, verify the connection: Use the zentao-remote MCP to query the products I can access. Show only their IDs and names."].join(`
|
|
253
|
+
`);return["请帮我在当前使用的 Agent 中配置公司的禅道 MCP 服务。","","服务名称:zentao-remote",`禅道地址:${T}`,`MCP 服务地址:${$}`,"传输方式:Streamable HTTP",`认证请求头:token: ${L}`,"","请按当前 Agent 的官方文档准备用户级 MCP 配置,保留已有服务。","请告知需要修改的 MCP 配置文件完整路径,以及设置 token 请求头的具体字段和方法;若通过界面配置,请给出入口和字段。","Token 为占位符时,由我在本机填写真实值。不要要求我在对话中提供禅道密码或 Token。","本机无需安装 zentao-cli 或启动 MCP 进程。","Token 只用于请求头。不要在回复中显示真实 Token,也不要提交到项目仓库。","等我在本机设置好 Token 后,再指导我重载或重启 Agent。","最后验证连接:请通过 zentao-remote MCP 查询我有权访问的产品列表,只显示 ID 和名称。"].join(`
|
|
254
|
+
`)}function t$(T){let $=(W)=>W.replace(/[&<>"']/g,(H)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[H]),L=(W)=>$(l0.zh[W]),Y=JSON.stringify({site:T.url,key:T.key,readOnly:!!T.readOnly,modules:T.modules,guides:s$,messages:l0}).replace(/</g,"\\u003c");return J`<!doctype html>
|
|
257
255
|
<html lang="zh-CN">
|
|
258
256
|
<head>
|
|
259
257
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
260
258
|
<meta name="color-scheme" content="light dark"><meta name="referrer" content="no-referrer">
|
|
261
|
-
<title>${
|
|
262
|
-
<script nonce="${
|
|
259
|
+
<title>${L("title")} · ZenTao</title>
|
|
260
|
+
<script nonce="${$(T.nonce)}">
|
|
263
261
|
try {
|
|
264
262
|
const theme = localStorage.getItem('zentao-mcp-theme');
|
|
265
263
|
if (theme === 'dark' || theme === 'light') document.documentElement.dataset.theme = theme;
|
|
266
264
|
} catch {}
|
|
267
265
|
</script>
|
|
268
|
-
<style nonce="${
|
|
266
|
+
<style nonce="${$(T.nonce)}">
|
|
269
267
|
|
|
270
268
|
:root {
|
|
271
269
|
--zt-page: light-dark(#f3f6f7, #06111e);
|
|
@@ -442,7 +440,7 @@ button:active:not(:disabled) { opacity: .85; }
|
|
|
442
440
|
<body>
|
|
443
441
|
|
|
444
442
|
<header class="zt-topbar">
|
|
445
|
-
<div class="zt-brand">${
|
|
443
|
+
<div class="zt-brand">${HT('<svg class="zt-logo" viewBox="0 0 100 100" aria-hidden="true" shape-rendering="crispEdges"><path fill="currentColor" transform="scale(6.25)" d="M6 1h4v1H6z M4 2h8v1H4z M3 3h10v1H3z M2 4h2v1H2z M9 4h5v1H9z M2 5h1v1H2z M4 5h2v1H4z M10 5h4v1h-4z M1 6h5v1H1z M11 6h4v1h-4z M1 7h4v1H1z M6 7h4v1H6z M13 7h2v1h-2z M1 8h3v1H1z M5 8h3v1H5z M10 8h5v1h-5z M1 9h3v1H1z M5 9h2v1H5z M8 9h1v1H8z M11 9h4v1h-4z M2 10h2v1H2z M5 10h5v1H5z M11 10h3v1h-3z M2 11h2v1H2z M6 11h3v1H6z M11 11h3v1h-3z M3 12h2v1H3z M10 12h3v1h-3z M4 13h8v1H4z M6 14h4v1H6z"/></svg>',"zt-logo")}<span>ZenTao <span class="zt-brand-separator">/ MCP</span></span></div>
|
|
446
444
|
<div class="zt-preferences">
|
|
447
445
|
<label class="zt-language"><svg class="zt-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 8 6 6m-7 0 6-6 2-4H2m5-2h1m6 20 5-11 5 11m-8-4h6"/></svg><select id="zt-language" data-i18n-aria="language" aria-label="语言"><option value="zh">中文</option><option value="en">English</option></select></label>
|
|
448
446
|
<button type="button" id="zt-theme-switch" class="zt-theme-switch" role="switch" aria-checked="false" aria-label="深色模式"><svg class="zt-icon zt-sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2m0 16v2M2 12h2m16 0h2M5 5l1.5 1.5m11 11L19 19M5 19l1.5-1.5m11-11L19 5"/></svg><svg class="zt-icon zt-moon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20.9 13A9 9 0 0 1 11 3.1 9 9 0 1 0 20.9 13Z"/></svg></button>
|
|
@@ -451,9 +449,9 @@ button:active:not(:disabled) { opacity: .85; }
|
|
|
451
449
|
<main class="zt-main">
|
|
452
450
|
<div class="zt-heading">
|
|
453
451
|
<h1 data-i18n="title">接入禅道 MCP</h1>
|
|
454
|
-
<div class="zt-site"><span data-i18n="site">禅道站点</span><a href="${
|
|
452
|
+
<div class="zt-site"><span data-i18n="site">禅道站点</span><a href="${$(T.url)}" target="_blank" rel="noreferrer">${$(T.url.replace(/^https?:\/\//,""))} ↗</a></div>
|
|
455
453
|
</div>
|
|
456
|
-
<noscript><p class="zt-notice">${
|
|
454
|
+
<noscript><p class="zt-notice">${L("noScript")}</p></noscript>
|
|
457
455
|
<p id="zt-insecure" class="zt-notice" data-i18n="insecure" hidden></p>
|
|
458
456
|
<section class="zt-panel" data-i18n-aria="steps" aria-label="接入步骤">
|
|
459
457
|
<nav class="zt-steps" data-i18n-aria="progress" aria-label="接入进度">
|
|
@@ -500,13 +498,13 @@ button:active:not(:disabled) { opacity: .85; }
|
|
|
500
498
|
<button type="button" id="zt-change-token" class="zt-link" data-i18n="changeToken">更换 Token</button>
|
|
501
499
|
<button type="button" id="zt-clear-token" class="zt-link zt-clear" data-i18n="clearToken">清除 Token</button>
|
|
502
500
|
</div>
|
|
503
|
-
<label class="zt-checkbox"><input id="zt-include" type="checkbox" aria-describedby="zt-include-warning" disabled><span data-i18n="includeToken">${
|
|
504
|
-
<p id="zt-include-warning" class="zt-caption" data-i18n="includeWarning" role="status" hidden>${
|
|
501
|
+
<label class="zt-checkbox"><input id="zt-include" type="checkbox" aria-describedby="zt-include-warning" disabled><span data-i18n="includeToken">${L("includeToken")}</span></label>
|
|
502
|
+
<p id="zt-include-warning" class="zt-caption" data-i18n="includeWarning" role="status" hidden>${L("includeWarning")}</p>
|
|
505
503
|
</div>
|
|
506
504
|
<p id="zt-token-feedback" class="zt-feedback zt-token-feedback" role="status" aria-live="polite"></p>
|
|
507
505
|
</section>
|
|
508
506
|
<div id="zt-assisted-setup">
|
|
509
|
-
<p class="zt-setup-text" data-i18n="setupIntro">${
|
|
507
|
+
<p class="zt-setup-text" data-i18n="setupIntro">${L("setupIntro")}</p>
|
|
510
508
|
<div class="zt-prompt-card">
|
|
511
509
|
<button type="button" id="zt-preview-toggle" class="zt-preview-trigger" aria-expanded="false" aria-controls="zt-prompt-preview" aria-label="展开接入说明">
|
|
512
510
|
<span class="zt-preview-heading"><span data-i18n="previewPrompt">预览说明</span><span id="zt-preview-action">展开</span></span>
|
|
@@ -518,7 +516,7 @@ button:active:not(:disabled) { opacity: .85; }
|
|
|
518
516
|
<p id="zt-copy-feedback" class="zt-feedback zt-action-feedback" role="status" aria-live="polite"></p>
|
|
519
517
|
</div>
|
|
520
518
|
<div id="zt-manual" hidden>
|
|
521
|
-
<label class="zt-label" for="zt-client" data-i18n="chooseAgent">选择 Agent</label><select id="zt-client" class="zt-input">${
|
|
519
|
+
<label class="zt-label" for="zt-client" data-i18n="chooseAgent">选择 Agent</label><select id="zt-client" class="zt-input">${s$.map((W)=>`<option value="${W.id}">${W.name}</option>`).join("")}</select>
|
|
522
520
|
<p id="zt-agent-steps" class="zt-caption zt-guide-text"></p>
|
|
523
521
|
<a id="zt-agent-docs" class="zt-caption" target="_blank" rel="noreferrer" data-i18n="officialDocs"></a>
|
|
524
522
|
<pre id="zt-config" class="zt-code" tabindex="0"></pre>
|
|
@@ -542,48 +540,49 @@ button:active:not(:disabled) { opacity: .85; }
|
|
|
542
540
|
<div class="zt-panel-footer"><button type="button" id="zt-back-setup" class="zt-link"><svg class="zt-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 12H5m6 6-6-6 6-6"/></svg><span data-i18n="backSetup">返回配置</span></button></div>
|
|
543
541
|
</section>
|
|
544
542
|
</section>
|
|
545
|
-
<footer class="zt-page-footer"><details class="zt-details"><summary ><span data-i18n="details">接入详情</span><svg class="zt-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 6 6 6-6 6"/></svg></summary><div class="zt-details-body"><p><span data-i18n="mcpAddress">MCP 地址:</span><code id="zt-mcp-url"></code></p><p id="zt-address-hint"></p><p id="zt-permissions">${
|
|
543
|
+
<footer class="zt-page-footer"><details class="zt-details"><summary ><span data-i18n="details">接入详情</span><svg class="zt-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 6 6 6-6 6"/></svg></summary><div class="zt-details-body"><p><span data-i18n="mcpAddress">MCP 地址:</span><code id="zt-mcp-url"></code></p><p id="zt-address-hint"></p><p id="zt-permissions">${L(T.readOnly?"readOnly":"readWrite")} · ${$(T.modules?.join("、")||l0.zh.allModules)} · ${L("accountPermissions")}</p>${!w0?'<p><a href="https://github.com/easysoft/zentao-cli/blob/main/docs/mcp-user-guide.md" target="_blank" rel="noreferrer" data-i18n="guide">完整接入指南 ↗</a></p>':""}</div></details></footer>
|
|
546
544
|
</main>
|
|
547
545
|
|
|
548
|
-
<script nonce="${
|
|
549
|
-
const data = ${
|
|
550
|
-
const makeConfig = ${
|
|
551
|
-
const makePrompt = ${
|
|
552
|
-
${
|
|
546
|
+
<script nonce="${$(T.nonce)}">
|
|
547
|
+
const data = ${Y};
|
|
548
|
+
const makeConfig = ${J(E9.toString())};
|
|
549
|
+
const makePrompt = ${J(h9.toString())};
|
|
550
|
+
${i$}
|
|
553
551
|
</script>
|
|
554
|
-
</body></html>`}var
|
|
555
|
-
`)}
|
|
556
|
-
`);return
|
|
557
|
-
|
|
558
|
-
${
|
|
559
|
-
`
|
|
552
|
+
</body></html>`}var s$;var o$=N(()=>{b();_1();n$();s$=[{id:"claude",name:"Claude Code",docs:"https://code.claude.com/docs/en/mcp",steps:"将配置合并到 ~/.claude.json 的 mcpServers 中。重新打开会话,在 /mcp 中检查连接。",stepsEn:"Merge into mcpServers in ~/.claude.json. Reopen the session and check the connection with /mcp."},{id:"cursor",name:"Cursor",docs:"https://cursor.com/docs/mcp",steps:"将配置合并到用户级 ~/.cursor/mcp.json。在设置的 MCP 页面启用服务,再打开 Agent 会话。",stepsEn:"Merge into ~/.cursor/mcp.json. Enable the server in MCP settings, then open an Agent session."},{id:"codex",name:"Codex",docs:"https://developers.openai.com/codex/mcp/",steps:J("将配置合并到 ~/.codex/config.toml。重新加载 MCP 或重启应用 / CLI,再确认 zentao-remote 已启用。"),stepsEn:J("Merge into ~/.codex/config.toml. Reload MCP or restart the app / CLI, then check that zentao-remote is enabled.")},{id:"vscode",name:"VS Code Copilot",docs:"https://code.visualstudio.com/docs/agent-customization/mcp-servers",steps:"从命令面板运行 MCP: Open User Configuration,将配置合并到用户配置。在 Agent 模式中启用该服务的工具。",stepsEn:"Run MCP: Open User Configuration from the command palette and merge into that config. Enable the server’s tools in Agent mode."},{id:"cherry",name:"Cherry Studio",docs:"https://docs.cherryai.com.cn/advanced-basic/extensions/mcp",steps:"在「设置 → MCP → MCP 服务器 → 添加」填写下列信息。启用服务后,在「工作 → Agent 菜单 → 编辑 → MCP」绑定给当前 Agent。",stepsEn:"Open Settings → MCP → MCP Servers → Add and enter these values. Enable the server, then bind it to your Agent in Work → Agent menu → Edit → MCP."},{id:"opencode",name:"OpenCode",docs:"https://opencode.ai/docs/mcp-servers/",steps:"将配置合并到用户级 ~/.config/opencode/opencode.json。重新打开 OpenCode,检查 MCP 服务状态。",stepsEn:"Merge into ~/.config/opencode/opencode.json. Reopen OpenCode and check the MCP server status."},{id:"gemini",name:"Gemini CLI",docs:"https://geminicli.com/docs/tools/mcp-server/",steps:"将配置合并到 ~/.gemini/settings.json。重新打开 Gemini CLI,通过 /mcp 查看状态。httpUrl 用于 Streamable HTTP。",stepsEn:"Merge into ~/.gemini/settings.json. Reopen Gemini CLI and check the status with /mcp. httpUrl uses Streamable HTTP."},{id:"cline",name:"Cline",docs:"https://docs.cline.bot/mcp/mcp-overview",steps:"打开 MCP Servers → Configure → Configure MCP Servers,将配置合并到打开的 JSON 文件,启用服务并检查工具列表。",stepsEn:"Open MCP Servers → Configure → Configure MCP Servers. Merge into the JSON file, enable the server and check its tools."}]});import{randomBytes as r$}from"node:crypto";function a$(T){let $=g(T.assistant,!0,"http"),L=r$(32).toString("hex"),Y=0;return async({path:W,method:H,headers:Q,signal:X,readBody:G})=>{let U=r$(18).toString("base64"),K={...H==="POST"?{Connection:"close"}:{},"Cache-Control":"no-store","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":`default-src 'none'; script-src 'nonce-${U}'; style-src 'nonce-${U}'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`},F=(V,C,_)=>Response.json({error:l0.zh[C],errorCode:C},{status:V,headers:{...K,..._}});if(W.includes("?"))return F(400,"noQuery");if(W==="/start"||W==="/start/"){if(H!=="GET")return F(405,"pageMethod",{Allow:"GET"});return new Response(t$({...T,nonce:U,key:L}),{headers:{...K,"Content-Type":"text/html; charset=utf-8"}})}if(H!=="POST")return F(405,"postOnly",{Allow:"POST"});let I;try{I=new URL(Q.get("origin")??"")}catch{return F(403,"invalidOrigin")}if(!["http:","https:"].includes(I.protocol)||I.origin!==Q.get("origin")||I.host!==Q.get("host")?.toLowerCase()||Q.get(J("x-zentao-start"))!==L||![null,"same-origin","none"].includes(Q.get("sec-fetch-site")))return F(403,"expired");if(I.protocol!=="https:"&&!["localhost","127.0.0.1","[::1]"].includes(I.hostname))return F(403,"httpsRequired");if(Q.get("content-type")?.split(";")[0].trim().toLowerCase()!=="application/json")return F(415,"jsonRequired");if(Y>=8)return F(429,"busy",{"Retry-After":"5"});Y++;try{let{body:V,status:C}=await G();if(C)return F(C,C===413?"tooLarge":C===408?"bodyTimeout":"invalidJson");if(!V||typeof V!=="object"||Array.isArray(V))return F(400,"required");let _=V;if(Object.keys(_).some((z)=>!["account","password"].includes(z))||typeof _.account!=="string"||!_.account.trim()||_.account.length>256||typeof _.password!=="string"||!_.password||_.password.length>4096)return F(400,"invalidCredentialsInput");if(X.aborted)return F(400,"cancelled");let q=await RT(T.url,_.account.trim(),_.password,{...T,actionAssistant:$,signal:X});if(!/^[A-Za-z0-9\-._~+/]+=*$/.test(q))return F(502,"invalidTokenResponse");return Response.json({token:q},{headers:K})}catch(V){let C=V instanceof B?V.code:"";if(["1003","1004","2006"].includes(C))return F(401,"invalidCredentials");if(C==="5001")return F(504,"timeout");if(C==="5002")return F(502,"certificate");return F(502,"loginFailed")}finally{Y--}}}var D1=16384,YT=(T)=>["/start","/start/","/start/token"].includes(T);var e$=N(()=>{b();sT();S();o$();_1();Y0()});var Y2={};O2(Y2,{startMcpHttpServer:()=>u9});import{createServer as f9}from"node:http";import{StreamableHTTPServerTransport as v9}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{WebStandardStreamableHTTPServerTransport as g9}from"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";function L2(T){let $=[];for(let H=0;H<T.length;H+=2){let Q=T[H].toLowerCase();if(Q==="token"||Q==="authorization")$.push([Q,T[H+1]])}if($.length!==1)return;let[L,Y]=$[0];return(L==="token"?/^([A-Za-z0-9\-._~+/]+=*)$/:/^Bearer ([A-Za-z0-9\-._~+/]+=*)$/i).exec(Y)?.[1]}function j0(T,$,L){if(T.destroyed||T.writableEnded)return;if(T.headersSent){T.destroy();return}T.writeHead($,{"Content-Type":"application/json; charset=utf-8",...T.req.method==="POST"?{Connection:"close"}:{}}),T.end(JSON.stringify({error:L}))}function T2(T,$=w1){return new Promise((L)=>{let Y=[],W=0,H=!1,Q=(F)=>{if(H)return;H=!0,clearTimeout(K),T.off("data",X),T.off("end",G),T.off("error",U),T.off("aborted",U),L(F)},X=(F)=>{if(W+=F.length,W>$)Q({status:413}),T.resume();else Y.push(F)},G=()=>{try{Q({body:JSON.parse(Buffer.concat(Y).toString("utf8"))})}catch{Q({status:400})}},U=()=>Q({status:400}),K=setTimeout(()=>{Q({status:408}),T.resume()},WT);K.unref(),T.on("data",X),T.once("end",G),T.once("error",U),T.once("aborted",U)})}async function u9(T){let $=g(T.assistant,!0,"http");if(T={...T,allowLocalFiles:!1},T.localUploadRoot===void 0){let I=process.env[J("ZENTAO_MCP_UPLOAD_ROOT")];if(I?.trim())T={...T,localUploadRoot:I.trim()}}if(!process.versions.bun){let[I,V,C]=process.versions.node.split(".").map(Number);if(I<18||I===18&&(V<14||V===14&&C<1))throw new B("E5004",{reason:"HTTP 模式需要 Node.js 18.14.1 或更新版本"})}for(let[I,V]of[["timeout",T.timeout],["port",T.port]])if(V!==void 0&&(!Number.isInteger(V)||V<(I==="port"?0:1)||V>(I==="port"?65535:2147483647)))throw new B("E2009",{option:I,reason:I==="port"?"必须为 0–65535 的整数":"必须为 1–2147483647 的整数毫秒数"});if(T.host!==void 0&&!T.host.trim())throw new B("E2009",{option:"host",reason:"监听地址不能为空"});let L;try{if(L=new URL(T.url),!["http:","https:"].includes(L.protocol)||L.username||L.password||L.search||L.hash)throw Error()}catch{throw new B("E2009",{option:"url",reason:J("请提供不含凭证、查询参数或片段的 HTTP(S) 禅道站点地址")})}let Y=c(L.toString()).siteUrl,W={...e,pagers:{},timeout:T.timeout??e.timeout,insecure:T.insecure??e.insecure},H=a$({...T,url:Y,timeout:W.timeout}),Q=(I)=>({async getContext(){return{client:c(Y,I,{...W,actionAssistant:$}),config:W,identity:{server:Y}}}});if(await d0(Q(),T).close(),process.versions.bun)return c9(T,W.timeout,Q,H);let X=new Set,G=new Set,U=f9({requestTimeout:WT},(I,V)=>{let C=Date.now(),_=I.url?.split("?")[0],q=_==="/mcp"||_==="/healthz"||YT(_??"")?_:"/unknown",z=["POST","GET","DELETE","PUT","PATCH","HEAD","OPTIONS"].includes(I.method??"")?I.method:"OTHER",w,D,k=!1,y=new AbortController,R=()=>{if(k)return;k=!0,y.abort(),clearTimeout(D),X.delete(x),I.socket.off("close",R),w?.close().catch(()=>{}),process.stderr.write(`[mcp-http] ${z} ${q} ${V.writableFinished?V.statusCode:499} ${Date.now()-C}ms
|
|
553
|
+
`)},x=()=>{R(),I.destroy(),V.destroy()};X.add(x),V.once("finish",R),V.once("close",R),V.once("error",R),I.once("aborted",R),I.once("error",R),I.socket.once("close",R),(async()=>{if(YT(_??"")){let O=new Headers;for(let E=0;E<I.rawHeaders.length;E+=2)O.append(I.rawHeaders[E],I.rawHeaders[E+1]);let f=await H({path:I.url,method:I.method,headers:O,signal:y.signal,readBody:()=>T2(I,D1)});if(k)return;V.writeHead(f.status,Object.fromEntries(f.headers)),V.end(await f.text());return}if(I.rawHeaders.some((O,f)=>f%2===0&&O.toLowerCase()==="origin")){j0(V,403,"不支持浏览器 Origin 请求");return}if(_==="/healthz"&&I.method==="GET"){V.writeHead(200,{"Content-Type":"application/json"}),V.end('{"status":"ok"}');return}if(_!=="/mcp"){j0(V,404,"未找到接口");return}if(I.method!=="POST"){V.setHeader("Allow","POST"),j0(V,405,"仅支持 POST");return}let m=L2(I.rawHeaders);if(!m||I.url?.includes("?")){j0(V,401,J("请通过单个 token 或 Authorization: Bearer 请求头提供禅道 Token"));return}let{body:r,status:h}=await T2(I);if(k)return;if(h){j0(V,h,h===413?"请求体超过 1 MiB":h===408?"接收请求超时":"JSON 请求体无效");return}D=setTimeout(()=>{j0(V,504,"工具调用超时"),R()},Math.max(60000,W.timeout)),D.unref(),w=d0(Q(m),T);let M=new v9({sessionIdGenerator:void 0});if(await w.connect(M),k){await w.close();return}await M.handleRequest(I,V,r)})().catch(()=>{j0(V,500,"MCP 请求处理失败"),R()})});U.on("connection",(I)=>{G.add(I),I.once("close",()=>G.delete(I))}),U.on("clientError",(I,V)=>V.destroy()),await new Promise((I,V)=>{U.once("error",V),U.listen(T.port??9090,T.host??"127.0.0.1",()=>{U.off("error",V),I()})}).catch((I)=>{throw new B("E5004",{reason:typeof I?.code==="string"?I.code:"监听失败"})});let K,F=U.address();return{url:new URL(`http://${F.family==="IPv6"?`[${F.address}]`:F.address}:${F.port}/mcp`),close(){return K??=new Promise((I)=>{let V=setTimeout(()=>{for(let C of X)C();for(let C of G)C.destroy()},$2);V.unref(),U.close(()=>{clearTimeout(V),I()}),U.closeIdleConnections?.()})}}}async function c9(T,$,L,Y){let W=new Set,H,Q=!1;try{H=Bun.serve({hostname:T.host??"127.0.0.1",port:T.port??9090,idleTimeout:WT/1000,maxRequestBodySize:w1,async fetch(G){if(Q)return Response.json({error:"MCP 服务正在关闭"},{status:503,headers:{Connection:"close"}});let U=Date.now(),K=new URL(G.url),F=["/mcp","/healthz"].includes(K.pathname)||YT(K.pathname)?K.pathname:"/unknown",I=["POST","GET","DELETE","PUT","PATCH","HEAD","OPTIONS"].includes(G.method)?G.method:"OTHER",V,C,_,q=!1,z=499,w=new AbortController,D=()=>{if(q)return;q=!0,w.abort(),clearTimeout(C),W.delete(k),G.signal.removeEventListener("abort",k),V?.close().catch(()=>{}),_?.cancel().catch(()=>{}),process.stderr.write(`[mcp-http] ${I} ${F} ${z} ${Date.now()-U}ms
|
|
554
|
+
`)},k=()=>{z=499,D()};W.add(k),G.signal.addEventListener("abort",k,{once:!0});let y=(R,x,m)=>{return z=R,D(),Response.json({error:x},{status:R,headers:{...G.method==="POST"?{Connection:"close"}:{},...m}})};try{if(YT(F)){let E=await Y({path:K.pathname+K.search,method:I,headers:G.headers,signal:w.signal,async readBody(){_=G.body?.getReader();let X0=[],p0=0,N1=!1;C=setTimeout(()=>{N1=!0,_?.cancel().catch(()=>{})},WT),C.unref();try{if(_)while(!0){let bT=await _.read();if(bT.done)break;if(p0+=bT.value.byteLength,p0>D1)return{status:413};X0.push(bT.value)}if(N1)return{status:408};if(q)return{status:400};return H.timeout(G,0),{body:JSON.parse(Buffer.concat(X0).toString("utf8"))}}catch{return{status:400}}finally{clearTimeout(C)}}});return z=E.status,D(),E}if(G.headers.has("origin"))return y(403,"不支持浏览器 Origin 请求");if(F==="/healthz"&&I==="GET")return z=200,D(),Response.json({status:"ok"});if(F!=="/mcp")return y(404,"未找到接口");if(I!=="POST")return y(405,"仅支持 POST",{Allow:"POST"});let R=L2(Array.from(G.headers).flat());if(!R||G.url.includes("?"))return y(401,J("请通过单个 token 或 Authorization: Bearer 请求头提供禅道 Token"));_=G.body?.getReader();let x=[],m=0,r=!1;if(C=setTimeout(()=>{r=!0,_?.cancel().catch(()=>{})},WT),C.unref(),_)while(!0){let E=await _.read();if(E.done)break;if(m+=E.value.byteLength,m>w1)return y(413,"请求体超过 1 MiB");x.push(E.value)}if(clearTimeout(C),r)return y(408,"接收请求超时");if(q||G.signal.aborted)return y(400,"请求已取消");let h;try{h=JSON.parse(Buffer.concat(x).toString("utf8"))}catch{return y(400,"JSON 请求体无效")}_=void 0,H.timeout(G,0),V=d0(L(R),T);let M=new g9({sessionIdGenerator:void 0});if(await V.connect(M),q)return await V.close(),y(400,"请求已取消");C=setTimeout(()=>{z=504,D()},Math.max(60000,$)),C.unref();let O=await M.handleRequest(G,{parsedBody:h});if(z=O.status,!O.body)return D(),O;_=O.body.getReader();let f=new ReadableStream({async pull(E){try{let X0=await _.read();if(X0.done)E.close(),D();else E.enqueue(X0.value)}catch{E.error(Error("MCP response closed")),D()}},cancel(){z=499,D()}});return new Response(f,{status:O.status,headers:O.headers})}catch{return y(500,"MCP 请求处理失败")}},error(){return Response.json({error:"MCP 请求处理失败"},{status:500})}})}catch(G){let U=G?.code;throw new B("E5004",{reason:U??"监听失败"})}let X;return{url:new URL("/mcp",H.url),close(){return X??=(async()=>{Q=!0;let G=setTimeout(()=>{for(let U of W)U();H.stop(!0)},$2);G.unref();try{await H.stop(!1),await H.stop(!0)}finally{clearTimeout(G)}})()}}}var w1=1048576,WT=30000,$2=5000;var W2=N(()=>{b();V0();Y0();BT();S();C1();e$()});J0();b();O0();import{CommanderError as M1}from"commander";import{Command as t9,Option as U2}from"commander";J0();O0();function y2(T,$){if(T.length===0)return"0 条";let L=T.map((G)=>G&&typeof G==="object"&&!Array.isArray(G)?G:{value:G}),Y=$??[...new Set(L.flatMap(Object.keys))];if(Y.length===0)return"";let W=L.map((G)=>Y.map((U)=>{let K=$?hT(G,U):G[U];return h1(K)})),H=`| ${Y.join(" | ")} |`,Q=`| ${Y.map(()=>"---").join(" | ")} |`,X=W.map((G)=>`| ${G.join(" | ")} |`).join(`
|
|
555
|
+
`);return`${H}
|
|
556
|
+
${Q}
|
|
557
|
+
${X}`}function P2(T,$){return($??Object.keys(T)).map((Y)=>{let W=$?hT(T,Y):T[Y];return`* ${Y}: ${h1(W)}`}).join(`
|
|
558
|
+
`)}function n0(T,$=!0){return JSON.stringify(T,null,$?4:0)}function k2(T,$){if(!T)return"";if(!$&&!T.recTotal)return"没有数据";return`
|
|
560
559
|
|
|
561
|
-
已显示 ${
|
|
562
|
-
结果已由 --max-items 截断`:"")}if(
|
|
563
|
-
`)+(
|
|
564
|
-
… 表示终端省略内容;使用 --format=json 查看完整值`:"")}
|
|
565
|
-
`)}if(!
|
|
560
|
+
已显示 ${$} 项,共 ${T.recTotal} 项,当前第 ${T.pageID} 页,每页 ${T.recPerPage} 条`}function G0(T,$){if($.format==="raw")return n0($.rawResponse??T);if($.format==="json"){let L=$.meta??($.isList?{returned:Array.isArray(T)?T.length:0,total:$.pager?.recTotal??null,page:$.pager?.pageID??null,pageSize:$.pager?.recPerPage??null,hasMore:$.pager?$.pager.pageID*$.pager.recPerPage<$.pager.recTotal:null}:{});return n0({ok:!0,data:T??null,meta:L},$.jsonPretty??!1)}if($.isList&&Array.isArray(T)){let L=$.format==="table"?b2(T,$.fields):y2(T,$.fields),Y=k2($.pager,T.length);return L+Y+($.meta?.truncated?`
|
|
561
|
+
结果已由 --max-items 截断`:"")}if(!$.isList&&T&&typeof T==="object"&&!Array.isArray(T))return P2(T,$.fields);return n0(T)}function h1(T){if(T===null||T===void 0)return"";return(typeof T==="object"?JSON.stringify(T):String(T)).replace(/\r?\n/g,"<br>").replace(/\|/g,"\\|")}function hT(T,$){let L=$.split("."),Y=T;for(let W of L){if(Y===null||Y===void 0||typeof Y!=="object")return;Y=Y[W]}return Y}function b2(T,$){if(!T.length)return"0 条";let L=T.map((U)=>U&&typeof U==="object"&&!Array.isArray(U)?U:{value:U}),Y=$??[...new Set(L.flatMap(Object.keys))],W=(U)=>[...U].reduce((K,F)=>K+(F.charCodeAt(0)>255?2:1),0),H=!1,Q=(U)=>{let K=(typeof U==="object"&&U!==null?JSON.stringify(U):String(U??"")).replace(/\s+/g," "),F="";for(let I of K){if(W(F+I)>36)return H=!0,F+"…";F+=I}return F},X=[Y,...L.map((U)=>Y.map((K)=>Q($?hT(U,K):U[K])))],G=Y.map((U,K)=>Math.max(...X.map((F)=>W(F[K]))));return X.map((U)=>U.map((K,F)=>K+" ".repeat(G[F]-W(K))).join(" ").trimEnd()).join(`
|
|
562
|
+
`)+(H?`
|
|
563
|
+
… 表示终端省略内容;使用 --format=json 查看完整值`:"")}S();function Z(T,$={},L={}){if($.format==="raw")throw new B("E2009",{option:"raw",reason:"raw 仅适用于具有原始服务端响应的业务命令"});console.log(G0(T,{format:$.format??"table",isList:Array.isArray(T),meta:L}))}S();function j2(T){return{name:T.name(),description:T.description(),arguments:T.registeredArguments.map(($)=>({name:$.name(),required:$.required,variadic:$.variadic,description:$.description})),options:T.options.map(($)=>({flags:$.flags,description:$.description,default:$.defaultValue,choices:$.argChoices})),commands:T.commands.map(($)=>({name:$.name(),description:$.description()}))}}function f1(T){T.command("help").description("离线文本或 JSON 命令定义").argument("[command]").argument("[action]").action(($,L,Y,W)=>{let H=W.optsWithGlobals(),Q=$?T.commands.find((K)=>K.name()===$):T,X=L?Q?.commands.find((K)=>K.name()===L):Q;if(!X)throw new B("E2009",{option:"help",reason:"未找到指定命令或操作"});if(H.format!=="json"){X.outputHelp();return}let G=$?I0($):void 0,U=G?.actions.find((K)=>R0(K.name)===L);Z(U?B0(G,U):j2(X),H)})}v0();V0();S();async function t1(T,$){let L=new URL("api.php/v1/user",`${T.siteUrl.replace(/\/+$/,"")}/`).href;try{let Y=await T.fetch(L,{},$);return typeof Y?.profile?.account==="string"?Y.profile.account:void 0}catch(Y){throw v(Y)}}async function o1(T,$){if(await t1(T,$.token)!==$.account)throw new B("E1004")}async function r1(T,$){let L=i(c(T.server,T.token,$),$.signal),Y;try{if((await L.post("/users/logout",{}))?.status!=="success")throw new B("E1012")}catch(W){Y=v(W)}try{await t1(L,T.token)}catch(W){if(W instanceof B&&W.code==="1004")return;throw Y??W}throw Y??new B("E1012")}T0();function a1(T){T.command("status").description("显示认证来源;默认离线").option("--verify","连接服务器验证凭据").action(async($,L)=>{let Y=L.optsWithGlobals(),W=r0(Y.profile);if(Y.verify){let H=await H0(Y);await o1(H.client,H.profile)}Z({source:W.source,server:W.server,account:W.account,credentialType:W.token?"token":"password",configFile:W.source==="profile"?FT():null,verified:Boolean(Y.verify)},Y)})}b();o0();b();$0();import{createInterface as LL}from"node:readline/promises";import{Writable as YL}from"node:stream";async function e1(){let T=!1,$=new YL({write(Y,W,H){if(!T)process.stderr.write(Y);H()}}),L=LL({input:process.stdin,output:$,terminal:process.stdin.isTTY});try{let Y=await L.question(J("禅道服务地址 (URL): "),{signal:A()});if(!Y)throw Error("URL is required");let W=await L.question("用户名 (Account): ",{signal:A()});if(!W)throw Error("Account is required");let H=(await L.question("认证方式 (password/token) [password]: ",{signal:A()})).trim().toLowerCase()||"password";if(H!=="password"&&H!=="token")throw Error("Auth method must be password or token");process.stderr.write(H==="token"?"Token: ":"密码 (Password): "),T=!0;let Q;try{Q=await L.question("",{signal:A()})}finally{T=!1,process.stderr.write(`
|
|
564
|
+
`)}if(!Q)throw Error("Password or Token is required");let X=Y.replace(/\/+$/,"");try{new URL(X)}catch{throw Error(`Invalid URL: ${X}`)}return{url:X,account:W,password:H==="password"?Q:"",token:H==="token"?Q:""}}finally{L.close()}}T0();S();V0();b();o0();import{randomBytes as Y$}from"node:crypto";import{createServer as JL}from"node:http";import{spawn as WL}from"node:child_process";function T$(T=process.platform,$=process.env){if($.SSH_CONNECTION||$.SSH_CLIENT||$.SSH_TTY||$.container||$.CI&&!/^(false|0)$/i.test($.CI))return!1;if(T==="darwin")return!0;if(T==="win32")return $.SESSIONNAME?.toLowerCase()!=="services";return T==="linux"&&Boolean($.DISPLAY||$.WAYLAND_DISPLAY)}async function $$(T){let $=process.platform==="darwin"?["open",T]:process.platform==="win32"?["rundll32.exe","url.dll,FileProtocolHandler",T]:process.platform==="linux"?["xdg-open",T]:void 0;if(!$)return!1;return new Promise((L)=>{let Y,W=setTimeout(()=>L(!0),5000),H=(Q)=>{clearTimeout(W),L(Q)};try{Y=WL($[0],$.slice(1),{stdio:"ignore",windowsHide:!0}),Y.once("error",()=>H(!1)),Y.once("exit",(Q)=>H(Q===0)),Y.unref()}catch{H(!1)}})}b();Z0();b();var HL={title:J("登录禅道"),intro:J("完成登录后,回到 ZenTao CLI 即可继续使用禅道。"),language:"语言",theme:"外观",system:"跟随系统",light:"浅色",dark:"深色",server:J("禅道地址"),serverHint:J("填写平时访问禅道的完整地址,保留 /zentao 等子目录。"),httpNotice:"此地址使用 HTTP,账号和密码将通过未加密的连接发送。请确认网络环境可信。",insecureNotice:J("当前已关闭 HTTPS 证书验证。请确认禅道地址属于你信任的服务器。"),account:"用户名",password:"密码",submit:"登录并保存",cancel:"取消",submitting:"正在登录…",cancelling:"正在取消…",privacy:"登录状态保存在本机。密码仅用于本次登录,不会保存到 CLI 配置。",noScript:J("请启用浏览器的 JavaScript,然后从 ZenTao CLI 重新发起登录。"),website:J("禅道官网"),websiteLabel:J("禅道官网(在新标签页打开)"),githubLabel:"GitHub 项目(在新标签页打开)",successTitle:"登录成功",successMessage:J("已登录账号 {account}({server})。登录状态已保存,可以返回 ZenTao CLI 继续操作。"),cancelTitle:"已取消登录",cancelMessage:J("本次登录已取消。需要使用禅道时,可从 ZenTao CLI 重新发起登录。"),finishedIntro:J("你可以关闭此页面,回到 ZenTao CLI 继续操作。"),connectionFailed:J("无法连接登录服务,页面可能已过期。请回到 ZenTao CLI 重新发起登录。"),cancelFailed:J("无法连接登录服务,页面可能已过期。请关闭此页面,回到 ZenTao CLI 查看登录状态。"),requestFailed:"请求处理失败,请重试。",localOnly:"仅允许本机登录请求。",expired:J("此登录页面已失效,请回到 ZenTao CLI 重新发起登录。"),notFound:"页面不存在。",invalidSession:J("登录页面已失效或请求来源不正确,请回到 ZenTao CLI 重新发起登录。"),invalidRequest:"请通过登录页面提交信息。",busy:"正在登录,请稍候。",tooLarge:"登录信息过长,请检查输入。",invalidJson:"登录信息格式不正确。",required:J("请填写禅道地址、用户名和密码。"),invalidUrl:J("请填写完整的禅道地址,例如 https://zentao.example.com。"),unsafeUrl:"请填写 HTTP 或 HTTPS 站点根地址,不要包含账号、密码、查询参数或锚点。",invalidCredentials:"用户名或密码不正确,请检查后重试。",unreachable:J("无法连接禅道,请检查地址和网络连接。"),timeout:J("连接禅道超时,请检查网络后重试。"),certificate:J("禅道的 HTTPS 证书验证失败,请联系管理员检查证书。"),invalidService:J("无法识别禅道服务,请填写禅道站点根地址。"),loginFailed:J("登录或保存失败,请检查禅道地址、账号及本地配置文件权限后重试。")},QL={title:J("登入禪道"),intro:J("完成登入後,回到 ZenTao CLI 即可繼續使用禪道。"),language:"語言",theme:"外觀",system:"跟隨系統",light:"淺色",dark:"深色",server:J("禪道網址"),serverHint:J("填寫平時存取禪道的完整網址,保留 /zentao 等子目錄。"),httpNotice:"此網址使用 HTTP,帳號和密碼將透過未加密的連線傳送。請確認網路環境可信。",insecureNotice:J("目前已關閉 HTTPS 憑證驗證。請確認禪道網址屬於你信任的伺服器。"),account:"使用者名稱",password:"密碼",submit:"登入並儲存",cancel:"取消",submitting:"正在登入…",cancelling:"正在取消…",privacy:"登入狀態儲存在本機。密碼僅用於本次登入,不會儲存到 CLI 設定。",noScript:J("請啟用瀏覽器的 JavaScript,然後從 ZenTao CLI 重新發起登入。"),website:J("禪道官網"),websiteLabel:J("禪道官網(在新分頁開啟)"),githubLabel:"GitHub 專案(在新分頁開啟)",successTitle:"登入成功",successMessage:J("已登入帳號 {account}({server})。登入狀態已儲存,可以返回 ZenTao CLI 繼續操作。"),cancelTitle:"已取消登入",cancelMessage:J("本次登入已取消。需要使用禪道時,可從 ZenTao CLI 重新發起登入。"),finishedIntro:J("你可以關閉此頁面,回到 ZenTao CLI 繼續操作。"),connectionFailed:J("無法連線至登入服務,頁面可能已過期。請回到 ZenTao CLI 重新發起登入。"),cancelFailed:J("無法連線至登入服務,頁面可能已過期。請關閉此頁面,回到 ZenTao CLI 查看登入狀態。"),requestFailed:"請求處理失敗,請重試。",localOnly:"僅允許本機登入請求。",expired:J("此登入頁面已失效,請回到 ZenTao CLI 重新發起登入。"),notFound:"頁面不存在。",invalidSession:J("登入頁面已失效或請求來源不正確,請回到 ZenTao CLI 重新發起登入。"),invalidRequest:"請透過登入頁面提交資訊。",busy:"正在登入,請稍候。",tooLarge:"登入資訊過長,請檢查輸入內容。",invalidJson:"登入資訊格式不正確。",required:J("請填寫禪道網址、使用者名稱和密碼。"),invalidUrl:J("請填寫完整的禪道網址,例如 https://zentao.example.com。"),unsafeUrl:"請填寫 HTTP 或 HTTPS 網站根網址,不要包含帳號、密碼、查詢參數或錨點。",invalidCredentials:"使用者名稱或密碼不正確,請檢查後重試。",unreachable:J("無法連線至禪道,請檢查網址和網路連線。"),timeout:J("連線至禪道逾時,請檢查網路後重試。"),certificate:J("禪道的 HTTPS 憑證驗證失敗,請聯絡管理員檢查憑證。"),invalidService:J("無法識別禪道服務,請填寫禪道網站根網址。"),loginFailed:J("登入或儲存失敗,請檢查禪道網址、帳號及本機設定檔權限後重試。")},XL={title:J("Log in to ZenTao"),intro:J("After logging in, return to ZenTao CLI to continue using ZenTao."),language:"Language",theme:"Appearance",system:"System",light:"Light",dark:"Dark",server:J("ZenTao URL"),serverHint:J("Enter the full address you normally use for ZenTao, including any subdirectory such as /zentao."),httpNotice:"This address uses HTTP. Your username and password will be sent over an unencrypted connection. Make sure you trust the network.",insecureNotice:J("HTTPS certificate verification is disabled. Make sure this ZenTao address belongs to a server you trust."),account:"Username",password:"Password",submit:"Log in and save",cancel:"Cancel",submitting:"Logging in…",cancelling:"Cancelling…",privacy:"Your login is saved on this computer. Your password is used only for this login and is not saved in the CLI configuration.",noScript:J("Enable JavaScript in your browser, then start login again from ZenTao CLI."),website:J("ZenTao website"),websiteLabel:J("ZenTao website (opens in a new tab)"),githubLabel:"GitHub project (opens in a new tab)",successTitle:"Login successful",successMessage:J("Logged in as {account} ({server}). Your login has been saved. Return to ZenTao CLI to continue."),cancelTitle:"Login cancelled",cancelMessage:J("This login was cancelled. You can start login again from ZenTao CLI when you need to use ZenTao."),finishedIntro:J("You can close this page and return to ZenTao CLI to continue."),connectionFailed:J("Could not connect to the login service. This page may have expired. Return to ZenTao CLI and start login again."),cancelFailed:J("Could not connect to the login service. This page may have expired. Close this page and check your login status in ZenTao CLI."),requestFailed:"Could not process the request. Please try again.",localOnly:"Login requests are only allowed from this computer.",expired:J("This login page has expired. Return to ZenTao CLI and start login again."),notFound:"Page not found.",invalidSession:J("This login page has expired or the request came from an unexpected source. Return to ZenTao CLI and start login again."),invalidRequest:"Submit your details using the login page.",busy:"Logging in. Please wait.",tooLarge:"The login details are too long. Check your input.",invalidJson:"The login details are not in the correct format.",required:J("Enter the ZenTao URL, username, and password."),invalidUrl:J("Enter the full ZenTao URL, such as https://zentao.example.com."),unsafeUrl:"Enter an HTTP or HTTPS site root URL without a username, password, query string, or fragment.",invalidCredentials:"The username or password is incorrect. Check your details and try again.",unreachable:J("Could not connect to ZenTao. Check the URL and your network connection."),timeout:J("The connection to ZenTao timed out. Check your network and try again."),certificate:J("ZenTao HTTPS certificate verification failed. Ask your administrator to check the certificate."),invalidService:J("Could not recognize the ZenTao service. Enter the ZenTao site root URL."),loginFailed:J("Could not log in or save your login. Check the ZenTao URL, your account, and write access to the local configuration file, then try again.")},wT={"zh-CN":HL,"zh-TW":QL,en:XL};function L$(T){let $=(W)=>W.replace(/[&<>"']/g,(H)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[H]),L=(W)=>$(wT["zh-CN"][W]),Y=`
|
|
566
565
|
color-scheme: dark;
|
|
567
566
|
--page-start: #142746; --page-end: #0c1629; --surface: #1a2639;
|
|
568
567
|
--ink: #eef3fc; --muted: #acb9cf; --accent: #80afff; --button: #2f6dd4; --button-hover: #245fc5;
|
|
569
568
|
--border: #52617a; --input: #152135; --footer: #162133; --brand: #a6c8ff;
|
|
570
569
|
--error: #ffb4b4; --error-bg: #432931; --notice: #f3d392; --notice-bg: #3a3223;
|
|
571
570
|
--success: #9ddbbb; --success-bg: #193c32;
|
|
572
|
-
`;return
|
|
571
|
+
`;return J`<!doctype html>
|
|
573
572
|
<html lang="zh-CN">
|
|
574
573
|
<head>
|
|
575
574
|
<meta charset="utf-8">
|
|
576
575
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
577
576
|
<meta name="color-scheme" content="light dark">
|
|
578
577
|
<meta name="referrer" content="no-referrer">
|
|
579
|
-
<title>${
|
|
580
|
-
<script nonce="${
|
|
578
|
+
<title>${L("title")} · ZenTao CLI</title>
|
|
579
|
+
<script nonce="${$(T.nonce)}">
|
|
581
580
|
try {
|
|
582
581
|
const theme = localStorage.getItem('zentao-login-theme');
|
|
583
582
|
if (theme === 'light' || theme === 'dark') document.documentElement.dataset.theme = theme;
|
|
584
583
|
} catch {}
|
|
585
584
|
</script>
|
|
586
|
-
<style nonce="${
|
|
585
|
+
<style nonce="${$(T.nonce)}">
|
|
587
586
|
:root {
|
|
588
587
|
color-scheme: light;
|
|
589
588
|
--page-start: #3273dc; --page-end: #2b67e5; --surface: #fff;
|
|
@@ -689,62 +688,62 @@ ${a}`}function es(e,t){return(t??Object.keys(e)).map((o)=>{let r=t?Ir(e,o):e[o];
|
|
|
689
688
|
<header class="page-header">
|
|
690
689
|
<div class="brand">
|
|
691
690
|
<!-- Original Pixel Tao geometry from site/public/brand/pixel-tao-terminal-blue-flat.svg. -->
|
|
692
|
-
${
|
|
691
|
+
${HT('<svg viewBox="0 0 16 16" aria-hidden="true" fill="currentColor" shape-rendering="crispEdges"><path d="M6 1h4v1H6z M4 2h8v1H4z M3 3h10v1H3z M2 4h2v1H2z M9 4h5v1H9z M2 5h1v1H2z M4 5h2v1H4z M10 5h4v1h-4z M1 6h5v1H1z M11 6h4v1h-4z M1 7h4v1H1z M6 7h4v1H6z M13 7h2v1h-2z M1 8h3v1H1z M5 8h3v1H5z M10 8h5v1h-5z M1 9h3v1H1z M5 9h2v1H5z M8 9h1v1H8z M11 9h4v1h-4z M2 10h2v1H2z M5 10h5v1H5z M11 10h3v1h-3z M2 11h2v1H2z M6 11h3v1H6z M11 11h3v1h-3z M3 12h2v1H3z M10 12h3v1h-3z M4 13h8v1H4z M6 14h4v1H6z"/></svg>',"brand-logo")}
|
|
693
692
|
<span class="brand-name">ZenTao CLI</span>
|
|
694
693
|
</div>
|
|
695
694
|
<div class="preferences">
|
|
696
695
|
<div class="preference">
|
|
697
696
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><ellipse cx="12" cy="12" rx="4" ry="9"/><path d="M3 12h18"/></svg>
|
|
698
|
-
<select id="language" data-i18n-label="language" aria-label="${
|
|
697
|
+
<select id="language" data-i18n-label="language" aria-label="${L("language")}" title="${L("language")}"><option value="zh-CN" lang="zh-CN">简体中文</option><option value="zh-TW" lang="zh-TW">繁體中文</option><option value="en" lang="en">English</option></select>
|
|
699
698
|
</div>
|
|
700
699
|
<div class="preference">
|
|
701
700
|
<svg class="theme-system" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="13" rx="2"/><path d="M12 17v4m-4 0h8"/></svg>
|
|
702
701
|
<svg class="theme-light" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2m0 16v2M2 12h2m16 0h2M5 5l1.5 1.5m11 11L19 19M5 19l1.5-1.5m11-11L19 5"/></svg>
|
|
703
702
|
<svg class="theme-dark" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20.5 13A9 9 0 0 1 11 3.5 9 9 0 1 0 20.5 13Z"/></svg>
|
|
704
|
-
<select id="theme" data-i18n-label="theme" aria-label="${
|
|
703
|
+
<select id="theme" data-i18n-label="theme" aria-label="${L("theme")}" title="${L("theme")}"><option value="system" data-i18n="system">${L("system")}</option><option value="light" data-i18n="light">${L("light")}</option><option value="dark" data-i18n="dark">${L("dark")}</option></select>
|
|
705
704
|
</div>
|
|
706
705
|
</div>
|
|
707
706
|
</header>
|
|
708
707
|
<section class="content" aria-labelledby="title">
|
|
709
|
-
<h1 id="title">${
|
|
710
|
-
<p class="intro" id="intro">${
|
|
711
|
-
${
|
|
708
|
+
<h1 id="title">${L("title")}</h1>
|
|
709
|
+
<p class="intro" id="intro">${$(T.message??wT["zh-CN"].intro)}</p>
|
|
710
|
+
${T.insecure?`<p class="notice insecure" data-i18n="insecureNotice">${L("insecureNotice")}</p>`:""}
|
|
712
711
|
<form id="login-form" method="post" action="/login">
|
|
713
712
|
<fieldset id="fields" disabled>
|
|
714
713
|
<div class="field">
|
|
715
|
-
<label for="server" data-i18n="server">${
|
|
716
|
-
<input id="server" name="server" type="url" autocomplete="url" inputmode="url" spellcheck="false" required placeholder="https://zentao.example.com" value="${
|
|
717
|
-
<p class="hint" id="server-hint" data-i18n="serverHint">${
|
|
718
|
-
<p class="notice" id="http-notice" data-i18n="httpNotice" hidden>${
|
|
714
|
+
<label for="server" data-i18n="server">${L("server")}</label>
|
|
715
|
+
<input id="server" name="server" type="url" autocomplete="url" inputmode="url" spellcheck="false" required placeholder="https://zentao.example.com" value="${$(T.server??"")}" aria-describedby="server-hint http-notice">
|
|
716
|
+
<p class="hint" id="server-hint" data-i18n="serverHint">${L("serverHint")}</p>
|
|
717
|
+
<p class="notice" id="http-notice" data-i18n="httpNotice" hidden>${L("httpNotice")}</p>
|
|
719
718
|
</div>
|
|
720
719
|
<div class="field">
|
|
721
|
-
<label for="account" data-i18n="account">${
|
|
722
|
-
<input id="account" name="username" type="text" autocomplete="username" autocapitalize="none" spellcheck="false" required value="${
|
|
720
|
+
<label for="account" data-i18n="account">${L("account")}</label>
|
|
721
|
+
<input id="account" name="username" type="text" autocomplete="username" autocapitalize="none" spellcheck="false" required value="${$(T.account??"")}">
|
|
723
722
|
</div>
|
|
724
723
|
<div class="field">
|
|
725
|
-
<label for="password" data-i18n="password">${
|
|
724
|
+
<label for="password" data-i18n="password">${L("password")}</label>
|
|
726
725
|
<input id="password" name="password" type="password" autocomplete="current-password" required>
|
|
727
726
|
</div>
|
|
728
727
|
<div class="actions">
|
|
729
|
-
<button class="primary" id="submit" type="submit">${
|
|
730
|
-
<button class="secondary" id="cancel" type="button">${
|
|
728
|
+
<button class="primary" id="submit" type="submit">${L("submit")}</button>
|
|
729
|
+
<button class="secondary" id="cancel" type="button">${L("cancel")}</button>
|
|
731
730
|
</div>
|
|
732
731
|
</fieldset>
|
|
733
732
|
</form>
|
|
734
|
-
<noscript><p class="notice">${
|
|
733
|
+
<noscript><p class="notice">${L("noScript")} / Please enable JavaScript and restart login from ZenTao CLI.</p></noscript>
|
|
735
734
|
<p class="feedback" id="feedback" role="status" aria-live="polite" tabindex="-1" hidden></p>
|
|
736
|
-
<p class="privacy" id="privacy" data-i18n="privacy">${
|
|
735
|
+
<p class="privacy" id="privacy" data-i18n="privacy">${L("privacy")}</p>
|
|
737
736
|
</section>
|
|
738
737
|
</main>
|
|
739
738
|
<footer>
|
|
740
|
-
<span>ZenTao CLI v${
|
|
741
|
-
<a href="https://www.zentao.net/" target="_blank" rel="noopener noreferrer" data-i18n="website" data-i18n-label="websiteLabel" aria-label="${
|
|
742
|
-
${!
|
|
739
|
+
<span>ZenTao CLI v${$(a())}</span>
|
|
740
|
+
<a href="https://www.zentao.net/" target="_blank" rel="noopener noreferrer" data-i18n="website" data-i18n-label="websiteLabel" aria-label="${L("websiteLabel")}">${L("website")}</a>
|
|
741
|
+
${!w0||w0.repository?` <a href="${w0?.repository??"https://github.com/easysoft/zentao-cli"}" target="_blank" rel="noopener noreferrer" data-i18n-label="githubLabel" aria-label="${L("githubLabel")}">GitHub</a>`:""}
|
|
743
742
|
</footer>
|
|
744
743
|
</div>
|
|
745
|
-
<script nonce="${
|
|
744
|
+
<script nonce="${$(T.nonce)}">
|
|
746
745
|
(() => {
|
|
747
|
-
const messages = ${JSON.stringify(
|
|
746
|
+
const messages = ${JSON.stringify(wT).replace(/</g,"\\u003c")};
|
|
748
747
|
let sessionKey = location.hash.slice(1);
|
|
749
748
|
history.replaceState(null, '', location.pathname);
|
|
750
749
|
const form = document.getElementById('login-form');
|
|
@@ -758,7 +757,7 @@ ${!ke||ke.repository?` <a href="${ke?.repository??"https://github.com/easys
|
|
|
758
757
|
const language = document.getElementById('language');
|
|
759
758
|
const theme = document.getElementById('theme');
|
|
760
759
|
const intro = document.getElementById('intro');
|
|
761
|
-
const customMessage = ${
|
|
760
|
+
const customMessage = ${T.message!==void 0} ? intro.textContent : null;
|
|
762
761
|
let locale;
|
|
763
762
|
try { locale = localStorage.getItem('zentao-login-language'); } catch {}
|
|
764
763
|
if (!Object.hasOwn(messages, locale)) {
|
|
@@ -884,69 +883,66 @@ ${!ke||ke.repository?` <a href="${ke?.repository??"https://github.com/easys
|
|
|
884
883
|
})();
|
|
885
884
|
</script>
|
|
886
885
|
</body>
|
|
887
|
-
</html>`}
|
|
888
|
-
${
|
|
889
|
-
`),
|
|
886
|
+
</html>`}T0();S();function BL(T){switch(T instanceof B?T.code:""){case"1003":case"1004":return{errorCode:"invalidCredentials",error:"用户名或密码不正确,请检查后重试。"};case"1002":return{errorCode:"unreachable",error:J("无法连接禅道,请检查地址和网络连接。")};case"5001":return{errorCode:"timeout",error:J("连接禅道超时,请检查网络后重试。")};case"5002":return{errorCode:"certificate",error:J("禅道的 HTTPS 证书验证失败,请联系管理员检查证书。")};case"2011":case"2012":return{errorCode:"invalidService",error:J("无法识别禅道服务,请填写禅道站点根地址。")};default:return{errorCode:"loginFailed",error:J("登录或保存失败,请检查禅道地址、账号及本地配置文件权限后重试。")}}}async function GL(T={}){let $=Y$(32).toString("hex"),L=Y$(18).toString("base64"),Y=new AbortController,W=new Set,H="",Q=!1,X=!1,G,U,K,F=new Promise((w,D)=>{U=w,K=D});F.catch(()=>{});let I=JL({requestTimeout:30000,headersTimeout:1e4},(w,D)=>{D.setHeader("Cache-Control","no-store"),D.setHeader("Referrer-Policy","no-referrer"),D.setHeader("X-Content-Type-Options","nosniff"),D.setHeader("Connection","close"),D.setHeader("Content-Security-Policy",`default-src 'none'; script-src 'nonce-${L}'; style-src 'nonce-${L}'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`),q(w,D).catch(()=>{if(!D.headersSent)_(D,500,{errorCode:"requestFailed",error:"请求处理失败,请重试。"});else D.destroy()})});I.on("connection",(w)=>{W.add(w),w.once("close",()=>W.delete(w))});function V(w,D){if(Q)return;if(Q=!0,clearTimeout(G),T.signal?.removeEventListener("abort",C),Y.abort(),process.removeListener("SIGINT",C),process.removeListener("SIGTERM",C),I.close(),setTimeout(()=>{for(let y of W)y.destroy()},250).unref(),w)K(w);else U(D)}function C(){V(new B("E1008"))}function _(w,D,k){w.writeHead(D,{"Content-Type":"application/json; charset=utf-8"}),w.end(JSON.stringify(k))}async function q(w,D){if(w.headers.host!==new URL(H).host){_(D,403,{errorCode:"localOnly",error:"仅允许本机登录请求。"});return}if(Q){_(D,410,{errorCode:"expired",error:"登录页面已失效,请重新发起登录。"});return}if(w.method==="GET"&&w.url==="/"){D.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),D.end(L$({nonce:L,server:T.server,account:T.account,message:T.message,insecure:T.insecure}));return}if(w.method!=="POST"||!["/login","/cancel"].includes(w.url??"")){_(D,404,{errorCode:"notFound",error:"页面不存在。"});return}if(w.headers.origin!==H||w.headers[J("x-zentao-login")]!==$){_(D,403,{errorCode:"invalidSession",error:"登录页面已失效或请求来源不正确,请重新发起登录。"});return}if(w.url==="/cancel"){D.once("finish",C),D.once("close",C),_(D,200,{ok:!0});return}if(w.headers["content-type"]?.split(";")[0].trim().toLowerCase()!=="application/json"){_(D,415,{errorCode:"invalidRequest",error:"请通过登录页面提交信息。"});return}if(X){_(D,409,{errorCode:"busy",error:"正在登录,请稍候。"});return}X=!0;try{let k=[],y=0;for await(let O of w){if(y+=O.length,y>16384){_(D,413,{errorCode:"tooLarge",error:"登录信息过长,请检查输入。"});return}k.push(Buffer.from(O))}let R;try{R=JSON.parse(Buffer.concat(k).toString("utf8"))}catch{_(D,400,{errorCode:"invalidJson",error:"登录信息格式不正确。"});return}if(!R||typeof R.server!=="string"||typeof R.account!=="string"||typeof R.password!=="string"||!R.server.trim()||!R.account.trim()||!R.password){_(D,400,{errorCode:"required",error:J("请填写禅道地址、用户名和密码。")});return}let x;try{x=new URL(R.server.trim())}catch{_(D,400,{errorCode:"invalidUrl",error:J("请填写完整的禅道地址,例如 https://zentao.example.com。")});return}if(!["http:","https:"].includes(x.protocol)||x.username||x.password||x.search||x.hash){_(D,400,{errorCode:"unsafeUrl",error:"请填写 HTTP 或 HTTPS 站点根地址,不要包含账号、密码、查询参数或锚点。"});return}let m=n(x.toString()),r=R.account.trim(),h=await A0(m,r,R.password,{...T,signal:Y.signal});if(Q)return;let M=F0(m,r,h.token,h.serverConfig,h.user);f0(M),_(D,200,{ok:!0,account:r,server:m}),V(void 0,IT(r,m))}catch(k){if(!Q)_(D,400,BL(k))}finally{X=!1}}try{await new Promise((w,D)=>{I.once("error",D),I.listen(0,"127.0.0.1",()=>{I.removeListener("error",D),w()})})}catch{throw I.close(),new B("E1010")}if(H=`http://127.0.0.1:${I.address().port}`,I.on("error",()=>V(new B("E1010"))),process.once("SIGINT",C),process.once("SIGTERM",C),T.signal?.addEventListener("abort",C,{once:!0}),G=setTimeout(()=>V(new B("E1009")),T.waitTimeoutMs??300000),T.signal?.aborted)C();return{url:`${H}/#${$}`,result:F,cancel:C}}async function W$(T={}){let $=await GL(T);if(process.stderr.write(`请在运行 CLI 的本机浏览器中完成登录(5 分钟内有效):
|
|
887
|
+
${$.url}
|
|
888
|
+
`),T.open!==!1&&!await $$($.url)){if(T.fallbackToTerminal){$.cancel();try{return await $.result}catch(L){if(!(L instanceof B)||L.code!=="1008")throw L}process.stderr.write(`未能自动打开浏览器,已关闭临时页面,改用终端登录。
|
|
890
889
|
`);return}process.stderr.write(`未能自动打开浏览器,请手动打开上面的链接。
|
|
891
|
-
`)}return
|
|
890
|
+
`)}return $.result}$0();Y0();function nT(T){T.command("login").description(J("登录禅道服务")).option("-s, --server <url>",J("禅道服务地址")).option("-u, --user <account>","用户名").option("-p, --password <password>","密码").option("-t, --token <token>","Token").option("--use-env","强制使用环境变量登录").option("--web","通过本机浏览器页面登录").option("--no-open","仅输出浏览器登录链接,由调用方打开(需 --web)").option("--select","登录成功后将该账号设为当前配置",T.parent?void 0:!0).option("--message <text>","自定义浏览器登录页面的副标题提示语").option("--no-browser","使用终端交互登录,不打开浏览器").action(async($)=>{let L=T.optsWithGlobals(),Y=g(L.assistant);if($.open===!1&&!$.web)throw new B("E2009",{option:"--no-open",reason:"必须与 --web 一起使用"});if($.web&&($.browser===!1||$.useEnv||$.password!==void 0||$.token!==void 0))throw new B("E2009",{option:"--web",reason:"不能与 --no-browser、--useEnv、--password 或 --token 同时使用"});if(L.input===!1&&($.web||!$.useEnv&&!($.server&&$.user&&($.password||$.token))))throw new B("E2009",{option:"no-input",reason:"禁止交互时必须提供完整凭据或 --use-env"});let W=$.server&&$.user&&($.password||$.token);if(!$.useEnv&&!W&&($.password!==void 0||$.token!==void 0))throw new B("E1001");let H=T$();if($.web||!$.useEnv&&!W&&$.browser!==!1&&H){let I=await W$({actionAssistant:Y,server:$.server,account:$.user,message:$.message,insecure:L.insecure,timeout:L.timeout,signal:A(),open:$.open!==!1&&H,fallbackToTerminal:!$.web&&Boolean(process.stdin.isTTY)});if(I){let V=l(I.account,I.server);if($.select)t0(V);Z({saved:V,selected:Boolean($.select)},L);return}}let Q,X,G,U;if($.useEnv){let I=y0();if(!I.url||!I.account||!I.password&&!I.token)throw new B("E1001");Q=I.url,X=I.account,G=I.password??"",U=I.token??""}else if(W)Q=$.server,X=$.user,G=$.password??"",U=$.token??"";else{if(!process.stdin.isTTY)throw new B("E1006");let I=await e1();Q=I.url,X=I.account,G=I.password,U=I.token}if(!Q||!X||!G&&!U)throw new B("E1001");Q=n(Q);let K;if(U){let I=c(Q,U,{actionAssistant:Y,insecure:L.insecure,timeout:L.timeout}),{serverConfig:V,user:C}=await pT(i(I,A()),X);K=F0(Q,X,U,V,C)}else{let I=await A0(Q,X,G,{actionAssistant:Y,insecure:L.insecure,timeout:L.timeout,signal:A()});K=F0(Q,X,I.token,I.serverConfig,I.user)}f0(K);let F=l(X,Q);if($.select)t0(F);Z({saved:F,selected:Boolean($.select)},L)})}b();V0();sT();T0();S();$0();Y0();function H$(T){T.command("token").description("获取 Token(默认输出纯文本,不保存配置)").argument("[profileKey]","已登录的用户配置(account@server,省略时使用当前账号)").option("-s, --server <url>",J("临时获取 Token 的禅道服务地址")).option("-u, --user <account>","临时获取 Token 的用户名").option("-p, --password <password>","临时获取 Token 的密码").option("--silent","不输出 Token,错误仍写入 stderr").addHelpText("after",`
|
|
892
891
|
省略凭证时只读取本地 Token,不联网验证。
|
|
893
892
|
临时获取必须同时提供 --server、--user、--password,不能与 profileKey 混用。
|
|
894
|
-
使用 --format json 或 --format raw 可同时输出账号、地址和 Token。`).action(async(
|
|
893
|
+
使用 --format json 或 --format raw 可同时输出账号、地址和 Token。`).action(async($,L)=>{let Y=T.opts(),W=L.server!==void 0||L.user!==void 0||L.password!==void 0;if(W&&$!==void 0)throw new B("E2009",{option:"profileKey",reason:"不能与 --server、--user 或 --password 同时使用"});let H,Q,X;if(W){if(!L.server||!L.user||!L.password)throw new B("E1001");try{X=await RT(L.server,L.user,L.password,{actionAssistant:g(Y.assistant),insecure:Y.insecure,timeout:Y.timeout,signal:A()}),H=c(L.server).siteUrl,Q=L.user}catch(G){throw v(G)}}else{let G=$===void 0?W0():s($);if(!G)throw new B($===void 0?"E1006":"E1007");if(!G.token.trim())throw new B("E1006");({server:H,account:Q,token:X}=G)}if(L.silent)return;if(Y.format==="json"||Y.format==="raw")console.log(JSON.stringify({status:"success",server:H,account:Q,token:X},null,4));else console.log(X)})}T0();S();$0();Y0();function tT(T){T.command("logout").description("删除本地登录记录").argument("[key]").option("--all","清理选定配置文件中的全部账号;空配置也成功").option("--revoke","先撤销并验证远端会话;失败时保留该账号以便重试").action(async($,L,Y)=>{let W=Y.optsWithGlobals();if(W.all&&($||W.profile))throw new B("E2009",{option:"--all",reason:"不能同时指定账号或 --profile"});let H=$??W.profile,Q=H?s(H):W0();if(!W.all&&!Q)throw new B("E1007");let X=W.all?VT():[Q],G=[];for(let U of X){if(W.revoke){let F=t(U);await r1(U,{timeout:W.timeout??F.timeout,insecure:W.insecure??F.insecure,actionAssistant:g(W.assistant,F.autoAssistant),signal:A()})}let K=l(U.account,U.server);if(UT(K,U.token))G.push(K);else if(W.revoke&&s(K))throw new B("E1012")}Z({removed:W.all?G:G[0]??null},W)})}T0();S();function oT(T){return{key:l(T.account,T.server),server:T.server,account:T.account,current:W0()?.server===T.server&&W0()?.account===T.account}}function Q$(T){let $=T.command("profile").description("管理已保存账号;use 才改变默认身份");$.action(()=>$.outputHelp()),$.command("list").description("列出已保存账号").action((L,Y)=>Z(VT().map(oT),Y.optsWithGlobals())),$.command("show").argument("[key]","完整 key 或唯一简写").description("查看账号,不验证凭据").action((L,Y,W)=>{let H=W.optsWithGlobals(),Q=L??H.profile,X=Q?s(Q):W0();if(!X)throw new B("E1007");Z({...oT(X),verified:!1},H)}),$.command("use").argument("<key>").description("设置默认身份").action((L,Y,W)=>{if(!t0(L))throw new B("E1007");Z(oT(W0()),W.optsWithGlobals())}),$.command("remove").argument("<key>").description("删除本地账号记录").action((L,Y,W)=>{let H=s(L);if(!H)throw new B("E1007");let Q=l(H.account,H.server);UT(Q),Z({removed:Q},W.optsWithGlobals())})}v0();T0();BT();S();var KL=new Set(["insecure","htmlToMarkdown","batchFailFast","jsonPretty","autoAssistant"]);function a0(T,$){throw new B("E2004",{field:T,value:$})}function IL(T,$){if(T==="defaultOutputFormat")return["table","markdown","json","raw"].includes($)?$:a0(T,$);if(KL.has(T)){if($==="true")return!0;if($==="false")return!1;return a0(T,$)}if(T==="timeout"||T==="defaultRecPerPage"){let L=Number($);return Number.isInteger(L)&&L>0&&(T!=="defaultRecPerPage"||L<=1000)?L:a0(T,$)}if(T==="pagers"){try{let L=JSON.parse($);if(L&&typeof L==="object"&&!Array.isArray(L)&&Object.values(L).every((Y)=>typeof Y==="number"&&Number.isInteger(Y)&&Y>0&&Y<=1000))return L}catch{}return a0(T,$)}return a0(T,$)}function X$(T){let $=T.command("config").description("查询配置来源并修改已保存账号的偏好");$.action(()=>$.outputHelp());let L=(W)=>{try{return r0(W.optsWithGlobals().profile).profile}catch(H){if(H instanceof B&&H.code==="1006")return;throw H}},Y=(W)=>{if(!m1.includes(W))throw new B("E2004",{field:W,value:""})};$.command("path").description("显示配置文件路径").action((W,H)=>Z({path:FT()},H.optsWithGlobals())),$.command("list").description("列出有效配置及来源").action((W,H)=>{let Q=L(H),X=Q?t(Q):e;Z(Object.entries(e).map(([G])=>({key:G,value:X[G],source:Q?.config&&Object.hasOwn(Q.config,G)?"profile":"default"})),H.optsWithGlobals())}),$.command("get").argument("<key>").description("查看一个配置项").action((W,H,Q)=>{Y(W);let X=L(Q),G=X?t(X):e;Z({key:W,value:G[W],source:X?.config&&Object.hasOwn(X.config,W)?"profile":"default"},Q.optsWithGlobals())}),$.command("set").argument("<key>").argument("<value>").description("修改一个配置项").action((W,H,Q,X)=>{Y(W);let G=IL(W,H),U=L(X);if(!U)throw new B("E1006");dT(U,W,G),Z({key:W,value:G,source:"profile"},X.optsWithGlobals())}),$.command("unset").argument("<key>").description("恢复默认值").action((W,H,Q)=>{Y(W);let X=L(Q);if(!X)throw new B("E1006");dT(X,W,void 0),Z({key:W,value:e[W],source:"default"},Q.optsWithGlobals())})}Z0();var J$={name:"@baocang/zentao-cli",version:"0.5.1",type:"module",description:"禅道命令行工具,支持在你喜爱的终端里访问和操作禅道数据,对 AI Agents 友好。",author:"Sun Hao <sunhao@chandao.com>",license:"MIT",repository:{type:"git",url:"https://github.com/baocang/zentao-cli.git"},keywords:["zentao","禅道","cli","project-management"],bin:{zentao:"./bin/zentao.js"},files:["bin","dist","skills"],scripts:{dev:"bun run src/index.ts",build:"bun run scripts/build.ts --minify","build:workbuddy":"bun run scripts/build-workbuddy.ts","build:sf":"bun run scripts/build.ts --compile --minify","build:sf:all":"bun run scripts/build.ts --compile --minify --targets=all",typecheck:"tsc --noEmit",test:"bun test",coverage:"bun test --coverage",prepublishOnly:"bun run typecheck && bun test && bun run scripts/generate-command-reference.ts --check && bun run build && node bin/zentao.js -V","build:site":"bun run scripts/build-site.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.29.0",commander:"^13.0.0",configstore:"^7.0.0","toml-eslint-parser":"^0.10.0",turndown:"^7.2.0","zentao-api":"0.8.5",zod:"^4.3.6"},devDependencies:{"@resvg/resvg-js":"2.6.2","@types/bun":"^1.3.13","@types/turndown":"^5.0.5",typescript:"^5.7.0"},engines:{node:">=18"},publishConfig:{access:"public"}};function B$(T){T.command("version").description("离线显示 CLI、SDK 和运行时版本").action(($,L)=>{Z({cli:a(),sdk:J$.dependencies["zentao-api"],runtime:typeof Bun>"u"?`Node ${process.versions.node}`:`Bun ${Bun.version}`,platform:process.platform,arch:process.arch},L.optsWithGlobals())})}b();S();function VL(T,$){let L=T,Y=$.at(-1)??"",W,H=()=>{let Q=[...L.options];for(let X=L.parent;X;X=X.parent)Q.push(...X.options);return Q};for(let Q of $.slice(0,-1)){if(W){W=void 0;continue}if(Q.startsWith("-")){let X=H().find((G)=>G.long===Q.split("=")[0]||G.short===Q);if(X?.required&&!Q.includes("="))W=X;continue}L=L.commands.find((X)=>X.name()===Q)??L}if(W)return(W.argChoices??[]).filter((Q)=>Q.startsWith(Y));return[...new Set([...L.commands.filter((Q)=>Q.name()!=="candidates").map((Q)=>Q.name()),...H().flatMap((Q)=>[Q.long,Q.short].filter(Boolean))])].filter((Q)=>Q.startsWith(Y))}function FL(T,$){if(T==="bash")return J`# bash completion for zentao (no bash-completion dependency)
|
|
895
894
|
_zentao_completion() {
|
|
896
895
|
COMPREPLY=()
|
|
897
896
|
local candidate
|
|
898
897
|
while IFS= read -r candidate; do COMPREPLY+=("$candidate"); done < <(zentao completion candidates -- "\${COMP_WORDS[@]:1:COMP_CWORD}")
|
|
899
898
|
}
|
|
900
899
|
complete -F _zentao_completion zentao
|
|
901
|
-
`;if(
|
|
900
|
+
`;if(T==="zsh")return J`#compdef zentao
|
|
902
901
|
_zentao() {
|
|
903
902
|
local -a candidates
|
|
904
903
|
candidates=("\${(@f)$(zentao completion candidates -- "\${words[@]:1:$((CURRENT-1))}")}")
|
|
905
904
|
compadd -- "\${candidates[@]}"
|
|
906
905
|
}
|
|
907
906
|
compdef _zentao zentao
|
|
908
|
-
`;if(
|
|
907
|
+
`;if(T==="fish")return J`# fish completion for zentao
|
|
909
908
|
function __zentao_candidates
|
|
910
909
|
set -l words (commandline -opc)
|
|
911
910
|
zentao completion candidates -- $words[2..-1] (commandline -ct)
|
|
912
911
|
end
|
|
913
912
|
complete -c zentao -f -a '(__zentao_candidates)'
|
|
914
|
-
`;throw new
|
|
913
|
+
`;throw new B("E2009",{option:"shell",reason:"支持 bash、zsh、fish"})}function G$(T){let $=T.command("completion").description("将补全脚本写入 stdout");$.action(()=>$.outputHelp());for(let L of["bash","zsh","fish"])$.command(L).action(()=>{process.stdout.write(FL(L))});$.command("candidates",{hidden:!0}).argument("[words...]").allowUnknownOption(!0).action((L)=>{let Y=VL(T,L);if(Y.length)process.stdout.write(Y.join(`
|
|
915
914
|
`)+`
|
|
916
|
-
`)})}
|
|
917
|
-
${
|
|
915
|
+
`)})}b();$0();S();import{cpSync as CL,existsSync as aT,mkdirSync as _L,statSync as K$,writeFileSync as DL}from"node:fs";import{homedir as K0}from"node:os";import{dirname as I$,isAbsolute as wL,join as p,relative as RL,resolve as rT,sep as OL}from"node:path";import{fileURLToPath as SL}from"node:url";import{createInterface as ML}from"node:readline/promises";var U$=[J("zentao-cli"),J("zentao-tour")],OT={"claude-code":{label:"Claude Code",dir:p(K0(),".claude","skills")},cursor:{label:"Cursor",dir:p(K0(),".cursor","skills")},"cherry-studio":{label:"Cherry Studio",dir:p(K0(),".cherrystudio","skills")},codex:{label:"Codex",dir:p(K0(),".agents","skills")},opencode:{label:"OpenCode",dir:p(K0(),".config","opencode","skills")},vscode:{label:"VS Code",dir:p(K0(),".copilot","skills")},antigravity:{label:"Antigravity",dir:p(K0(),".gemini","antigravity","skills")},gemini:{label:"Gemini",dir:p(K0(),".gemini","skills")}},P0=Object.keys(OT);function V$(T){let $=SL(import.meta.url),L=I$($),Y=[p(L,"..","..","skills",T),p(L,"..","skills",T),p(L,"..","..","..","skills",T)];for(let W of Y)if(aT(W))return{type:"directory",path:W};throw Error(`找不到技能源目录,已尝试路径:
|
|
916
|
+
${Y.map((W)=>` - ${W}`).join(`
|
|
918
917
|
`)}
|
|
919
|
-
`+
|
|
920
|
-
`)
|
|
921
|
-
`)});try{let
|
|
922
|
-
可用选项: ${
|
|
923
|
-
`)}function
|
|
924
|
-
`)
|
|
925
|
-
`)});try{let
|
|
926
|
-
可用选项: ${
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
`)?
|
|
930
|
-
`,r=[`[mcp_servers.${it}]`,l('command = "zentao"'),'args = ["mcp", "serve"]',l`env = { ZENTAO_URL = ${JSON.stringify(t.url)}, ZENTAO_ACCOUNT = ${JSON.stringify(t.account)}, ZENTAO_TOKEN = ${JSON.stringify(t.token)} }`].join(o)+o;zo(e,wa(n,r,o))}catch{throw new c("E1005",{path:e})}}function ka(e,t){let n=zt[e];switch(n.format){case"mcpServers":ga(n.configPath,t);break;case"vscode":ha(n.configPath,t);break;case"opencode":ya(n.configPath,t);break;case"codex":va(n.configPath,t);break;case"cherry-studio":return}}function jn(e,t="install"){e.command(t).description(l("配置禅道 MCP 服务到 AI Agent")).argument("[agent]",`目标 Agent (${Ze.join("|")}|all)`).action(async(n)=>{let o=e.optsWithGlobals();if(!n&&o.input===!1)throw new c("E2009",{option:"agent",reason:"--no-input 时必须指定安装目标"});let r=n?ma(n):await fa(),i=await pa(o);for(let s of r)ka(s,i);P(r.map((s)=>({agent:s,path:zt[s].configPath,...s==="cherry-studio"?{manual:{name:it,type:"stdio",command:l("zentao"),args:["mcp","serve"]}}:{}})),o)})}T();L();xe();Gt();Te();import{isDeepStrictEqual as bc}from"node:util";import{Option as Xn}from"commander";T();import{isDeepStrictEqual as Ma}from"node:util";ne();T();import{readFile as za}from"node:fs/promises";var Vt;async function Ta(){if(Vt)return Vt;if(process.stdin.isTTY||process.stdin.listenerCount("data")>0)return;return Vt=(async()=>{let e=I();e?.throwIfAborted();let t=()=>process.stdin.destroy(new c("E5003"));e?.addEventListener("abort",t,{once:!0});try{let n=[];for await(let r of process.stdin)n.push(Buffer.from(r));return Buffer.concat(n).toString("utf-8").trim()||void 0}finally{e?.removeEventListener("abort",t)}})(),Vt}function Nn(e){try{let t=JSON.parse(e);if(!t||typeof t!=="object"||Array.isArray(t))throw new c("E2007");return t}catch{throw new c("E2007")}}async function So(e){if(e==="@-"){let t=await Ta();if(t)return Nn(t);throw new c("E2007")}if(e.startsWith("@"))try{return Nn(await za(e.slice(1),{encoding:"utf8",signal:I()}))}catch(t){if(t instanceof c)throw t;throw new c("E2009",{option:"data",reason:"无法读取 JSON 文件"})}return Nn(e)}Fn();var Pa=(e,t)=>{let{src:n,pos:o,posMax:r,md:i}=e;if(!n.startsWith("![",o))return!1;let s=i.helpers.parseLinkLabel(e,o+1,!1);if(s<0||n[s+1]!=="(")return!1;let a=(p)=>{while(p<r&&/[ \t\n]/.test(n[p]))p++;return p},d=i.helpers.parseLinkDestination(n,a(s+2),r);if(!d.ok||!(Ct(d.str)||/^file:\d+$/i.test(d.str)))return!1;let u=a(d.pos),m="";if(u>d.pos&&n[u]!==")"){let p=i.helpers.parseLinkTitle(n,u,r);if(!p.ok)return!1;m=p.str,u=a(p.pos)}if(u>=r||n[u]!==")")return!1;if(!t){let p=e.push("image","img",0);if(p.attrs=[["src",d.str],["alt",""]],m)p.attrSet("title",m);p.content=n.slice(o+2,s),p.children=[],i.inline.parse(p.content,i,e.env,p.children)}return e.pos=u+1,!0};async function Ia(){let{default:e}=await import("markdown-it"),t=new e({html:!1});return t.inline.ruler.before("image","zentao_file_image",Pa),(n)=>{let o={},r=t.parse(n,o);if(r.length===3&&r[0].type==="paragraph_open"&&r[1].type==="inline"&&r[2].type==="paragraph_close")return t.renderer.renderInline(r[1].children,t.options,o);return t.renderer.render(r,t.options,o)}}var Oa;function Po(){return Oa??=Ia()}Gt();Te();Ke();qt();Ye();function q(e,t){throw new c("E2009",{option:e,reason:t})}function We(e,t,n=!1){if(t.type==="array"){if(typeof e==="string"&&e.startsWith("["))try{return JSON.parse(e)}catch{q("data","数组不是有效 JSON")}return(Array.isArray(e)?e:[String(e)]).flatMap((o)=>{if(o.startsWith("[")){try{let r=JSON.parse(o);if(Array.isArray(r))return r}catch{}q("data","数组不是有效 JSON")}return[We(o,t.items??{type:"string"})]})}if(typeof e==="boolean")return e;if(Array.isArray(e))q("data","此字段不能重复");if(Array.isArray(t.type))return/^\d+$/.test(e)?Number(e):e;if(t.type==="number"||t.type==="integer"){let o=n&&typeof e==="string"?ut(e):e;if(!String(o).trim()||!/^[+-]?(?:\d+\.?\d*|\.\d+)$/.test(String(o)))q("data","需要有效数字");return Number(o)}if(t.type==="boolean"){if(e==="true")return!0;if(e==="false")return!1;q("data","布尔值只接受 true 或 false")}if(t.type==="object")try{return JSON.parse(e)}catch{q("data","需要 JSON 对象")}return e}async function Ra(e,t,n,o){let r=o.data??{},i=e==="doc"&&(r.contentType??o.contentType)!=="html",s=n===!0?t:n.split(",").map((u)=>u.trim()),a=new Map;for(let u of s){if(!t.includes(u))q("markdown",`无效的字段名「${u}」,可选 HTML 字段为 ${t.join(", ")}`);if(i&&u==="content"){if(n===!0)continue;q("markdown","文档正文可直接传入 Markdown,转换为 HTML 需显式指定 --content-type html")}let m=r[u]??o[u];if(typeof m==="string")a.set(u,m);else if(n!==!0)q("markdown",`本次请求未提供字段 ${u}`)}if(!a.size)return;let d=await Po();for(let[u,m]of a){let p=d(m);if(Object.hasOwn(o,u))o[u]=p;if(Object.hasOwn(r,u))r[u]=p}}async function Un(e,t,n,o,r,i){if(o.format==="raw"&&(o.ids||o.all||o.maxItems||o.pick||o.filter?.length||o.search?.length||o.sort||o.searchFields||o.htmlToMarkdown))q("raw","原始响应不能与本地处理或自动翻页组合");let s={},a=Me(e,t),d=a.parameters,u=(b,k)=>{if(k===void 0)return;if(Object.hasOwn(s,b)&&!Ma(s[b],k))q(b,"同一字段的输入值冲突");s[b]=k};for(let[b,k]of Object.entries(r)){if(k===void 0)continue;let w=d.find((z)=>z.name===b),v=b==="id"||b.endsWith("ID");u(b,w?We(k,w,v):Number(k))}if(e.name==="file"&&t.name==="read"&&o.output!==void 0){if(!o.output.trim())q("output","请输入目标文件路径");if(o.ids!==void 0||o.batchFailFast||o.format==="raw"||s.stream===1)q("output","写入单个附件的原始字节时不能同时指定 --ids、--batch-fail-fast、--format=raw 或 --stream=1")}let m=a.target,p;if(n!==void 0){if(!m)q("target","此操作没有位置参数");if(ae(e.name,t.name)&&!Number.isFinite(Number(n))&&!(t.name==="get"&&Dn(n))){if(o.ids!==void 0)q("ids","--ids 与单个附件链接只能指定一个");p=n}else u(m,We(n,d.find((b)=>b.name===m),!0))}if(o.data!==void 0)s.data=await So(o.data);let g=_e(e,t,d);if(g){if(o.page!==void 0)u(g.page.name,We(o.page,g.page));if(o.recPerPage!==void 0)u(g.size.name,We(o.recPerPage,g.size))}if(o.all&&g&&(s[g.page.name]!==void 0||s.data?.[g.page.name]!==void 0))q("all/page","--all 与 --page 不能同时使用");if(o.maxItems!==void 0&&(!/^\d+$/.test(o.maxItems)||!Number.isSafeInteger(Number(o.maxItems))||Number(o.maxItems)<1))q("max-items","必须为正安全整数");let f=Ot(t,s,o.ids),h={};for(let b of["product","project","execution"])if(s[b]!==void 0&&!d.some((k)=>k.name===b))h[b]=s[b],delete s[b];let y=Wt(e,t,{...h,url:p,params:f?{...s,[he(t)]:f[0]}:s},i);if(o.markdown!==void 0)await Ra(e.name,a.markdownFields,o.markdown,y);if(f)delete y[he(t)];return y}ot();Ye();Y();T();ne();import{randomUUID as La}from"node:crypto";import{open as $a,link as ja,rename as Da,rm as Io}from"node:fs/promises";import{dirname as Na,join as _a}from"node:path";import{getModuleAction as Fa}from"zentao-api";async function Jt(e,t,n,o,r){let i=r.signal??I(),{version:s}=await e.getZentaoConfig({timeout:r.timeout,insecure:r.insecure,signal:i});if(!Fa("file","read",{version:s}))throw new c("E2010",{action:"file/read",version:s,minVersion:t.minVersion.join(" / ")});let a=(p)=>{throw new c("E5005",{path:o,reason:p instanceof Error?p.message:String(p)})},d=_a(Na(o),`.zentao-download-${La()}`),u=await $a(d,"wx",384).catch(a),m=!1;try{let p=await e.request(t.path.replace("{fileID}",n),{method:"GET",query:{stream:0},responseType:"response",actionAssistant:r.assistant,timeout:r.timeout,insecure:r.insecure,signal:i}),g=r.resolvePath?r.resolvePath(p.headers):o,f=0;if(p.body)for await(let h of p.body)await u.writeFile(h).catch(a),f+=h.byteLength;if(await u.close().catch(a),i?.aborted)throw new c("E5003");if(r.noClobber)await ja(d,g).catch(a),m=!0,await Io(d,{force:!0});else await Da(d,g).catch(a),m=!0;return{path:g,bytes:f}}catch(p){if(i?.aborted)throw new c("E5003");if(p instanceof Error&&p.name==="AbortError")throw new c("E5001");let g=N(p);if(g instanceof c)throw g;throw new c("E1002",{url:e.siteUrl},{reason:p instanceof Error?p.message:String(p)})}finally{if(!m)try{await u.close()}finally{await Io(d,{force:!0})}}}T();xe();import{basename as Kn,extname as lc,join as Jo}from"node:path";import{existsSync as Qo,mkdirSync as uc,readFileSync as pc}from"node:fs";Gn();Y();T();ne();Ke();en();import{createInterface as fc}from"node:readline/promises";async function Ko(e,t,n=!1){if(n||e==="json"||e==="raw"||!process.stdin.isTTY||!process.stderr.isTTY)throw new c("E2009",{option:"yes",reason:"非交互或机器可读模式下删除必须显式传入 --yes"});let o=fc({input:process.stdin,output:process.stderr});try{return(await o.question(`确认删除 ${t} 个对象?(y/n): `,{signal:I()})).toLowerCase()==="y"}finally{o.close()}}function ei(e,t){for(let n of e){let o=t===void 0?"附件警告":`对象 ${t} 附件警告`;console.error(`${o}:${JSON.stringify(n)}`)}}function ti(e){let{meta:t,fileWarnings:n,resultObjectType:o}=e;if(!o&&!n?.length)return t;return{...t,...o&&{resultObjectType:o},...n?.length&&{fileWarnings:n}}}function mc(e,t,n){let o=t.format??n.defaultOutputFormat??"markdown";if(o!=="json"&&e.fileWarnings?.length)ei(e.fileWarnings);if(e.action.path==="/files/{fileID}/read"&&o!=="json"){if(o==="raw"){let i=e.rawResponse;process.stdout.write(i instanceof ArrayBuffer?Buffer.from(i):String(i))}else console.log(e.data);return}let r=Xe(e.data,{format:o,isList:e.isList,fields:e.fields,pager:e.pager,meta:o==="json"?ti(e):e.meta,jsonPretty:n.jsonPretty,rawResponse:e.rawResponse});if(o==="markdown"&&e.action.type==="get"){let{color:i="auto"}=t;if((i==="always"||i==="auto"&&process.stdout.isTTY&&process.env.NO_COLOR===void 0)&&typeof Bun<"u"&&typeof Bun.markdown?.ansi==="function")r=Bun.markdown.ansi(r)}if(r)console.log(r);else if(o==="markdown"||o==="table"){let s=e.rawResponse?.message;console.log(typeof s==="string"&&s.trim()?s:"操作成功")}}async function ni(e,t,n,o){let r=n??".";uc(r,{recursive:!0});let i=me("file").actions.find((a)=>a.name==="read"),s=await Jt(e,i,t,Jo(r,`file_${t}`),{resolvePath:(a)=>{let d=a.get("Content-Disposition")??"",u=d.match(/filename\*\s*=\s*(?:UTF-8'')?["']?([^"';\n]+)["']?/i),m=d.match(/filename\s*=\s*(?:"([^"]+)"|'([^']+)'|([^;\n]+))/i),g=(u?.[1]??m?.[1]??m?.[2]??m?.[3])?.trim()||`file_${t}`;if(u)try{g=decodeURIComponent(g)}catch{}let f=Jo(r,Kn(g));if(Qo(f))throw new c("E2009",{option:"output",reason:`目标文件已存在: ${f}`});return f},noClobber:!0});if(o==="json"||o==="raw")console.log(JSON.stringify({ok:!0,data:{file:s.path,size:s.bytes}}));else console.log(`已下载: ${s.path} (${s.bytes} bytes)`)}var Yo={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".svg":"image/svg+xml",".avif":"image/avif"};async function ri(e,t,n,o,r){let i=Vo(t.name),s=t.actions.find((g)=>g.name==="comment"),a=s?he(s):void 0;if(!i||!a)throw new c("E2005",{module:t.name});let d=n[a]??n.id;if(d===void 0)throw new c("E2003",{param:a});let u={...n.data},m=typeof u.comment==="string"?u.comment:"",p=[];for(let g of o){let f=r?.marks.get(g);if(f!==void 0){p.push(f);continue}if(!Qo(g))throw new c("E2009",{option:"image",reason:`图片文件不存在: ${g}`});let h=lc(g).toLowerCase(),y=Yo[h];if(!y)throw new c("E2009",{option:"image",reason:`不支持的图片格式 ${h||"(无扩展名)"},支持 ${Object.keys(Yo).join(" ")}`});let b=new FormData;b.append("file",new Blob([pc(g)],{type:y}),Kn(g)),b.append("objectType",i),b.append("objectID",String(d));let k;try{k=await e.request("/files",{method:"POST",body:b})}catch(z){throw N(z)}if(!k||typeof k!=="object"||k.id===void 0||k.status&&k.status!=="success")throw new c("E2008",{url:"/files",status:"",serverResponse:JSON.stringify(k).slice(0,300)});let w=k.url??`/file-read-${k.id}${h}`,v=`<img src="${Xo(w)}" alt="${Xo(Kn(g))}" />`;r?.marks.set(g,v),p.push(v)}return u.comment=m?`${m}
|
|
931
|
-
${
|
|
932
|
-
`)}`:p.join(`
|
|
933
|
-
`),{...n,data:u}}function Xo(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}function gc(e){let t=e instanceof Error?e:Error(String(e));return{...t instanceof c&&X(t.details)?{recoveryMessage:It(t,"table")}:{},error:{...t instanceof c?{code:t.code,details:t.details}:{},message:t.message}}}function hc(e,t,n,o){if(t==="json"||t==="raw")return gt({ok:e.errors.size===0,data:e.ids.map((i)=>{let s=e.data.get(i);if(s)return{objectID:i,ok:!0,data:s.value??null,...s.meta&&{meta:s.meta}};let a=e.errors.get(i);return a?{objectID:i,ok:!1,error:a.error}:{objectID:i,ok:!1,skipped:!0}}),meta:{success:e.data.size,failed:e.errors.size,skipped:e.skipped.length}},n);let r=[];if(o&&e.data.size){let i=Array.from(e.data,([a,{value:d}])=>d&&typeof d==="object"&&!Array.isArray(d)?{...d,objectID:a}:{objectID:a,value:d}),s=Xe(i,{format:"markdown",isList:!0});if(s)r.push(s)}if(r.push(`操作成功:${e.data.size?[...e.data.keys()].join(", "):"无"}`,`操作失败:${e.errors.size?[...e.errors.keys()].join(", "):"无"}`),e.skipped.length>0)r.push(`已跳过:${e.skipped.join(", ")}`);for(let[i,s]of e.errors){let a=s.error.code?`E${s.error.code}: `:"";r.push(`${i}: ${s.recoveryMessage??a+s.error.message}`)}return r.join(`
|
|
934
|
-
`)}function oi(e,t){let n=kr(e.name),o=t.format??"markdown",r=Xe(n,{format:o,isList:!1});if(r)console.log(r)}async function Yn(e,t,n,o,r,i){let s=K(r),a=i.batchFailFast??s.batchFailFast??!1,d=i.format??s.defaultOutputFormat??"markdown",u=De(t,n);if(!u)throw new c("E2005",{module:t.name});let m=Ot(u,o,i.ids);if(m){if(d==="raw")throw new c("E2009",{option:"raw/ids",reason:"原始响应不支持批量组合,请使用 json"});if(u.type==="delete"&&!i.yes){if(!await Ko(d,m.length,i.machineReadable||i.input===!1))return}let g={ids:m,skipped:[],data:new Map,errors:new Map},f=he(u),{outcomes:h,skipped:y}=await tn({ids:m,failFast:a,throwIfAborted:()=>I()?.throwIfAborted(),onError:(b,k)=>{if(I()?.aborted&&k instanceof c&&X(k.details))throw k},execute:(b)=>St(e,t,n,{...o,id:b,...f?{[f]:b}:{}},i,s)});g.skipped=y;for(let b of h)if(b.ok){if(g.data.set(b.id,{value:u.type==="delete"?null:b.value.data,meta:ti(b.value)}),d!=="json"&&b.value.fileWarnings?.length)ei(b.value.fileWarnings,b.id)}else g.errors.set(b.id,gc(b.error));if(console.log(hc(g,d,s.jsonPretty??!1,u.type!=="delete")),g.errors.size>0)process.exitCode=1;return}if(u.type==="delete"&&!i.yes){if(!await Ko(d,1,i.machineReadable||i.input===!1))return}let p=await St(e,t,n,o,i,s);mc(p,i,s)}Ke();T();var ii={assistant:"string",profile:"string",format:"string",config:"string",color:"string",output:"string",ids:"string",maxItems:"string",pick:"string",sort:"string",searchFields:"string",page:"string",recPerPage:"string",data:"string",filter:"stringArray",search:"stringArray",preferPassword:"boolean",input:"boolean",quiet:"boolean",insecure:"boolean",all:"boolean",yes:"boolean",batchFailFast:"boolean",htmlToMarkdown:"boolean",machineReadable:"boolean",timeout:"number",deadline:"number",markdown:"markdown"};function at(e,t){throw new c("E2009",{option:`--options.${e}`,reason:t})}function yc(e,t){let n=ii[e];if(!n)at(e,`未知选项;可用选项: ${Object.keys(ii).sort().join(", ")}`);switch(n){case"string":if(typeof t==="number"&&Number.isFinite(t))return String(t);if(typeof t!=="string")at(e,`必须是字符串,收到 ${typeof t}`);return t;case"stringArray":if(!Array.isArray(t)||t.some((o)=>typeof o!=="string"))at(e,"必须是字符串数组");return t;case"boolean":if(typeof t!=="boolean")at(e,`必须是布尔值,收到 ${typeof t}`);return t;case"number":if(typeof t!=="number"||!Number.isFinite(t))at(e,`必须是数字,收到 ${typeof t}`);return t;case"markdown":if(t!==!0&&typeof t!=="string")at(e,"必须是 true 或逗号分隔的字段字符串");return t}}function si(e){if(e.options===void 0)return e;let t;try{t=JSON.parse(e.options)}catch{throw new c("E2009",{option:"--options",reason:"必须是有效的 JSON 对象"})}if(t===null||typeof t!=="object"||Array.isArray(t))throw new c("E2009",{option:"--options",reason:"必须是 JSON 对象"});let n={};for(let[o,r]of Object.entries(t))n[o]=yc(o,r);for(let[o,r]of Object.entries(e)){if(o==="options"||r===void 0)continue;if(Array.isArray(r)&&r.length===0)continue;n[o]=r}return delete n.options,n}function Qn(e,t=[]){return t.concat([e])}function ai(e){for(let t of wr()){let n=me(t),o=e.command(t).description(n.display??t);if(o.argument("[target]",l`对象 ID 简写,等价于 zentao ${t} get <target>`),o.action(async(r,i,s)=>{if(r===void 0){o.outputHelp();return}let a=ut(r.trim());if(!/^\d+$/.test(a)||!Number.isSafeInteger(Number(a))||Number(a)<1)throw new c("E2009",{option:"target",reason:l`无法识别 "${r}";查看对象请使用 zentao ${t} get <id>,全部操作见 zentao ${t} --help`});let d=n.actions.find((g)=>g.name==="get");if(!d)throw new c("E2009",{option:"target",reason:l`模块 ${t} 没有 get 操作,请查看 zentao ${t} --help`});let u=s.optsWithGlobals(),m=await Un(n,d,a,u,{}),p=await le(u);await kt(p,u,(g,f)=>Yn(g,n,"get",m,f,u))}),o.command("props").description("返回对象字段定义(离线)").action((r,i)=>{oi(n,i.optsWithGlobals())}),t==="file")o.command("download").description("下载附件到本地文件(原始字节流,支持 Content-Disposition 命名)").argument("<fileID>","附件 ID").option("--output <dir>","输出目录,默认当前目录").action(async(...r)=>{let s=r.at(-1).optsWithGlobals(),a=r[0];if(!/^\d+$/.test(a))throw new c("E2009",{option:"fileID",reason:"需要有效数字"});let d=await le(s);await kt(d,s,(u)=>ni(u,a,typeof s.output==="string"?s.output:void 0,s.format??"markdown"))});for(let r of n.actions){let i=ge(n.name,r.name),s=Me(n,r,i),a=t==="file"&&r.name==="read",d=ae(t,r.name),u=o.command(Oe(r.name)).description(`${r.display??r.name}(最低版本:${r.minVersion.join(" / ")})`);if(s.target)u.argument("[target]",d?"单个附件标识或当前站点的附件 URL,--file-id 可单独指定标识":`单个 ${s.target};也可使用命名参数`);let m=[],p=s.pagination,g=new Set(p?[p.page,p.pageSize]:[]);for(let f of s.parameters){if(g.has(f.name)||m.some((b)=>b.name===f.name))continue;let h=f.flag.slice(2),y=new Xn(`--${h} ${f.type==="boolean"?"[boolean]":"<value>"}`,`${f.description??f.name}${f.required&&!(d&&f.name==="fileID")?"(必填)":""}`);if(f.type==="array")y.argParser((b,k=[])=>k.concat(b));if(f.type==="boolean")y.preset(!0);if(u.addOption(y),m.push({name:f.name,attribute:y.attributeName()}),f.type==="boolean")u.addOption(new Xn(`--no-${h}`,`将 ${f.name} 设为 false`).default(void 0));if(f.type!=="array"){let b,k=()=>{let w=f.name==="id"||f.name.endsWith("ID"),v=We(u.getOptionValue(y.attributeName()),f,w);if(b!==void 0&&!bc(b,v))throw new c("E2009",{option:h,reason:"重复选项的输入值冲突"});b=v};if(u.on(`option:${y.name()}`,k),f.type==="boolean")u.on(`option:no-${h}`,k)}}for(let f of["product","project","execution"]){if(!Tt(i,f)||m.some((y)=>y.name===f))continue;let h=new Xn(`--${f} <id>`,`${f}ID 或 scope/scopeID 别名`);u.addOption(h),m.push({name:f,attribute:h.attributeName()})}if(r.requestBody)u.option("--data <json|@file|@->","JSON 对象、文件或显式标准输入");if(u.option("--options <json>","CLI 调用选项(JSON 对象;显式命令行参数优先)"),s.markdownFields.length){let f=s.markdownFields.join(", "),h=t==="doc"?"(content 需显式指定 --content-type html)":"";u.option("--markdown [fields]",`将 Markdown 转为 HTML。可选 ${f}${h},多个字段用逗号分隔,省略时转换本次提供的全部 HTML 字段`)}if(a)u.option("--output <path>","流式保存附件,下载完成后替换目标文件");if(s.batch)u.option("--ids <ids>","批量目标 ID,逗号分隔并去重").option("--batch-fail-fast","失败后跳过剩余目标");if(r.name==="comment")u.option("--image <path>","随备注上传并内嵌到正文的图片路径(可多次)",Qn);if(r.type==="delete")u.option("--yes","确认删除");if(r.type==="list"||r.type==="get"&&!a)u.option("--fields <fields>","返回字段,逗号分隔").option("--html-to-markdown","显式将富文本字段转换为 Markdown");if(r.type==="list")u.option("--max-items <number>","整次命令最多返回条数"),u.option("--filter <expr>","当前获取范围内过滤;组内 AND,多次指定为 OR",Qn),u.option("--search <keywords>","当前获取范围内搜索",Qn),u.option("--search-fields <fields>","本地搜索字段"),u.option("--sort <expr>","当前获取范围内排序,如 id:asc");if(p)u.option("--page <number>","指定页,从 1 开始").option("--page-size <number>","每次服务端请求的页大小").option("--all","显式遍历全部页面");u.action(async(...f)=>{let y=f.at(-1).optsWithGlobals(),b=si({...y,pick:y.fields,recPerPage:y.pageSize}),k=Object.fromEntries(m.map((x)=>[x.name,y[x.attribute]])),w,v=await Un(n,r,s.target?f[0]:void 0,b,k,(x)=>{w=Se(b.profile),Ne(x,w.server)}),z=await le(b,w);if(a&&b.output!==void 0){let x=b.format??K(z.profile).defaultOutputFormat;if(x==="raw")throw new c("E2009",{option:"output",reason:"写入文件时请使用 table、markdown 或 json 输出下载结果"});await kt(z,b,async(A)=>{let O=await Jt(A,r,String(v.fileID),b.output,b);P(O,{format:x})});return}let F=y.image,C=F?.length?{marks:new Map}:void 0;await kt(z,b,async(x,A)=>{let O=C?await ri(x,n,v,F,C):v;await Yn(x,n,r.name,O,A,b)})})}}}L();or();T();function Oi(e){let t=cr(e.command("mcp").description(l("启动 MCP 服务,支持本地 stdio 或多客户端 HTTP 访问禅道数据")).option("--transport <type>","传输方式 (stdio|http)","stdio")).action((n)=>dr(n,e.optsWithGlobals()));return cr(t.command("serve").description("启动 MCP 服务").option("--transport <type>","传输方式 (stdio|http)","stdio")).action((n,o)=>{let r=o.optsWithGlobals();return dr(r,r)}),cr(e.command("mcp-server").description(l("启动 HTTP MCP 服务,供多个客户端访问固定禅道站点")).argument("[url]",l("禅道站点地址,与 --url 二选一;省略时读取 ZENTAO_URL"))).addHelpText("after",l(`
|
|
918
|
+
`+J("请确认 zentao-cli 安装完整,或从源码目录运行。"))}async function qL(){if(!process.stdin.isTTY||!process.stderr.isTTY)throw new B("E2009",{option:"agent",reason:`未指定 agent,请显式传入: ${P0.join("|")}|all`});let T=[...P0,"all"],$=[...P0.map((Y)=>OT[Y].label),"全部安装"],L=ML({input:process.stdin,output:process.stderr});process.stderr.write(`请选择要安装的 AI Agent:
|
|
919
|
+
`),$.forEach((Y,W)=>{process.stderr.write(` ${W+1}) ${Y}
|
|
920
|
+
`)});try{let Y=await L.question(`请输入编号 (1-${T.length}): `,{signal:A()}),W=Number(Y.trim());if(!Number.isInteger(W)||W<1||W>T.length)throw new B("E2009",{option:"agent",reason:`无效选择: ${Y||"(empty)"}`});let H=T[W-1];return H==="all"?[...P0]:[H]}finally{L.close()}}function zL(T){let $=T.toLowerCase();if($==="all")return[...P0];if(OT[$])return[$];throw new B("E2009",{option:"agent",reason:`不支持的 agent: ${T}
|
|
921
|
+
可用选项: ${P0.join("、")}、all`})}function NL(T,$){let L=RL(rT(T),rT($)),Y=".."+OL;if(L===""||!wL(L)&&L!==".."&&!L.startsWith(Y))throw Error("技能目标路径不能是技能源目录或其子目录: "+$)}function F$(T,$){if(T.type==="directory")NL(T.path,$);if(aT($)&&!K$($).isDirectory())throw Error(`技能目标路径必须是目录: ${$}`)}function C$(T,$){if(F$(T,$),T.type==="directory"){CL(T.path,$,{recursive:!0,dereference:!0});return}for(let[L,Y]of Object.entries(T.files)){let W=p($,L);_L(I$(W),{recursive:!0}),DL(W,Buffer.from(Y,"base64"))}}function ZL(T){let $=T.trim();if(!$)throw Error("导出路径不能为空");let L=$==="~"?K0():$.replace(/^~[\\/]/,`${K0()}/`),Y=rT(L);if(aT(Y)&&!K$(Y).isDirectory())throw Error(`导出路径必须是目录: ${Y}`);return Y}function AL(T,$){let L=OT[T],Y=V$($),W=p(L.dir,$);return C$(Y,W),{skill:$,agent:T,path:W}}function yL(T){let $=ZL(T),L=U$.map((Y)=>({skillName:Y,source:V$(Y),destDir:p($,Y)}));for(let{source:Y,destDir:W}of L)F$(Y,W);for(let{skillName:Y,source:W,destDir:H}of L)C$(W,H);return L.map(({skillName:Y,destDir:W})=>({skill:Y,path:W}))}function _$(T){T.command("install").description("安装技能到指定 Agent").argument("[agent]",P0.join("|")+"|all").action(async($,L,Y)=>{let W=Y.optsWithGlobals();if(!$&&W.input===!1)throw new B("E2009",{option:"agent",reason:"--no-input 时必须指定安装目标"});let H=$?zL($):await qL();Z(H.flatMap((Q)=>U$.map((X)=>AL(Q,X))),W)}),T.command("export").description("导出技能到指定目录").argument("<directory>").action(($,L,Y)=>Z(yL($),Y.optsWithGlobals()))}b();$0();v0();S();import{chmodSync as D$,existsSync as eT,mkdirSync as PL,readFileSync as O$,renameSync as kL,unlinkSync as bL,writeFileSync as jL}from"node:fs";import{homedir as xL}from"node:os";import{dirname as EL,join as o}from"node:path";import{createInterface as hL}from"node:readline/promises";import{parseTOML as w$}from"toml-eslint-parser";var g0=J("zentao-cli"),L0=xL();function R$(...T){switch(process.platform){case"darwin":return o(L0,"Library","Application Support",...T);case"win32":return o(process.env.APPDATA||o(L0,"AppData","Roaming"),...T);default:return o(L0,".config",...T)}}var e0={cursor:{label:"Cursor",configPath:o(L0,".cursor","mcp.json"),format:"mcpServers"},"claude-desktop":{label:"Claude Desktop",configPath:R$("Claude","claude_desktop_config.json"),format:"mcpServers"},"claude-code":{label:"Claude Code",configPath:o(L0,".claude.json"),format:"mcpServers"},windsurf:{label:"Windsurf",configPath:o(L0,".codeium","windsurf","mcp_config.json"),format:"mcpServers"},cline:{label:"Cline",configPath:o(L0,".cline","data","settings","cline_mcp_settings.json"),format:"mcpServers"},trae:{label:"Trae",configPath:o(L0,".trae","mcp.json"),format:"mcpServers"},vscode:{label:"VS Code",configPath:R$("Code","User","mcp.json"),format:"vscode"},"cherry-studio":{label:"Cherry Studio",configPath:"",format:"cherry-studio"},opencode:{label:"OpenCode",configPath:o(L0,".config","opencode","opencode.json"),format:"opencode"},codex:{label:"Codex",configPath:o(L0,".codex","config.toml"),format:"codex"},antigravity:{label:"Antigravity",configPath:o(L0,".gemini","antigravity","mcp_config.json"),format:"mcpServers"},gemini:{label:"Gemini",configPath:o(L0,".gemini","mcp_config.json"),format:"mcpServers"}},k0=Object.keys(e0);function T1(T){if(!eT(T))return{};let $=O$(T,"utf-8").trim();if(!$)return{};try{let L=JSON.parse($);if(!L||typeof L!=="object"||Array.isArray(L))throw Error("Config root must be an object");return L}catch{throw Error(`无法安全更新包含注释或无效 JSON 的配置文件,请手动配置: ${T}`)}}function $1(T,$,L){let Y=T;for(let W=0;W<$.length-1;W++){let H=$[W];if(!Y[H]||typeof Y[H]!=="object"||Array.isArray(Y[H]))Y[H]={};Y=Y[H]}Y[$[$.length-1]]=L}function L1(T,$){S$(T,JSON.stringify($,null,2)+`
|
|
922
|
+
`)}function S$(T,$){PL(EL(T),{recursive:!0,mode:448});let L=`${T}.${process.pid}.tmp`;try{if(jL(L,$,{encoding:"utf-8",mode:384}),process.platform!=="win32")D$(L,384);if(kL(L,T),process.platform!=="win32")D$(T,384)}catch(Y){if(eT(L))bL(L);throw Y}}async function fL(T){let{profile:$}=await H0(T);return{url:$.server,account:$.account,token:$.token}}async function vL(){if(!process.stdin.isTTY||!process.stderr.isTTY)throw new B("E2009",{option:"agent",reason:`未指定 agent,请显式传入: ${k0.join("|")}|all`});let T=[...k0,"all"],$=[...k0.map((Y)=>e0[Y].label),"全部配置"],L=hL({input:process.stdin,output:process.stderr});process.stderr.write(`请选择要配置的 AI Agent:
|
|
923
|
+
`),$.forEach((Y,W)=>{let H=String(W+1).padStart(2);process.stderr.write(` ${H}) ${Y}
|
|
924
|
+
`)});try{let Y=await L.question(`请输入编号 (1-${T.length}): `,{signal:A()}),W=Number(Y.trim());if(!Number.isInteger(W)||W<1||W>T.length)throw new B("E2009",{option:"agent",reason:`无效选择: ${Y||"(empty)"}`});let H=T[W-1];return H==="all"?[...k0]:[H]}finally{L.close()}}function gL(T){let $=T.toLowerCase();if($==="all")return[...k0];if(e0[$])return[$];throw Error(`不支持的 agent: ${T}
|
|
925
|
+
可用选项: ${k0.join("、")}、all`)}function M$(T){return{command:J("zentao"),args:["mcp","serve"],env:{[J("ZENTAO_URL")]:T.url,[J("ZENTAO_ACCOUNT")]:T.account,[J("ZENTAO_TOKEN")]:T.token}}}function uL(T,$){let L=T1(T);$1(L,["mcpServers",g0],M$($)),L1(T,L)}function cL(T,$){let L=T1(T);$1(L,["servers",g0],{type:"stdio",...M$($)}),L1(T,L)}function mL(T,$){let L=T1(T);$1(L,["mcp",g0],{type:"local",command:[J("zentao"),"mcp","serve"],environment:{[J("ZENTAO_URL")]:$.url,[J("ZENTAO_ACCOUNT")]:$.account,[J("ZENTAO_TOKEN")]:$.token},enabled:!0}),L1(T,L)}function dL(T,$){let L=T.lastIndexOf(`
|
|
926
|
+
`,$.range[0]-1)+1,Y=T.indexOf(`
|
|
927
|
+
`,$.range[1]);return[L,Y<0?T.length:Y+1]}function lL(T,$,L){let H=w$(T).body[0].body.filter((X)=>X.type==="TOMLTable"&&X.resolvedKey[0]==="mcp_servers"&&X.resolvedKey[1]===g0).map((X)=>dL(T,X)),Q=T;if(H.length>0)for(let X=H.length-1;X>=0;X--){let[G,U]=H[X];Q=Q.slice(0,G)+(X===0?$:"")+Q.slice(U)}else{let X=!T||T.endsWith(L+L)?"":T.endsWith(`
|
|
928
|
+
`)?L:L+L;Q=T+X+$}return w$(Q),Q}function pL(T,$){try{let L=eT(T)?O$(T,"utf-8"):"",Y=L.match(/\r?\n/)?.[0]??`
|
|
929
|
+
`,W=[`[mcp_servers.${g0}]`,J('command = "zentao"'),'args = ["mcp", "serve"]',J`env = { ZENTAO_URL = ${JSON.stringify($.url)}, ZENTAO_ACCOUNT = ${JSON.stringify($.account)}, ZENTAO_TOKEN = ${JSON.stringify($.token)} }`].join(Y)+Y;S$(T,lL(L,W,Y))}catch{throw new B("E1005",{path:T})}}function iL(T,$){let L=e0[T];switch(L.format){case"mcpServers":uL(L.configPath,$);break;case"vscode":cL(L.configPath,$);break;case"opencode":mL(L.configPath,$);break;case"codex":pL(L.configPath,$);break;case"cherry-studio":return}}function Y1(T,$="install"){T.command($).description(J("配置禅道 MCP 服务到 AI Agent")).argument("[agent]",`目标 Agent (${k0.join("|")}|all)`).action(async(L)=>{let Y=T.optsWithGlobals();if(!L&&Y.input===!1)throw new B("E2009",{option:"agent",reason:"--no-input 时必须指定安装目标"});let W=L?gL(L):await vL(),H=await fL(Y);for(let Q of W)iL(Q,H);Z(W.map((Q)=>({agent:Q,path:e0[Q].configPath,...Q==="cherry-studio"?{manual:{name:g0,type:"stdio",command:J("zentao"),args:["mcp","serve"]}}:{}})),Y)})}S();import{isDeepStrictEqual as I9}from"node:util";import{Option as K1}from"commander";J0();MT();NT();AT();O0();S();X1();AT();O0();i0();import{isDeepStrictEqual as L9}from"node:util";function Q0(T,$){throw new B("E2009",{option:T,reason:$})}function b0(T,$){if($.type==="array"){if(typeof T==="string"&&T.startsWith("["))try{return JSON.parse(T)}catch{Q0("data","数组不是有效 JSON")}return(Array.isArray(T)?T:[String(T)]).flatMap((L)=>{if(L.startsWith("[")){try{let Y=JSON.parse(L);if(Array.isArray(Y))return Y}catch{}Q0("data","数组不是有效 JSON")}return[b0(L,$.items??{type:"string"})]})}if(typeof T==="boolean")return T;if(Array.isArray(T))Q0("data","此字段不能重复");if($.type==="number"||$.type==="integer"){let L=typeof T==="string"?xT(T):T;if(!String(L).trim()||!/^[+-]?(?:\d+\.?\d*|\.\d+)$/.test(String(L)))Q0("data","需要有效数字");return Number(L)}if($.type==="boolean"){if(T==="true")return!0;if(T==="false")return!1;Q0("data","布尔值只接受 true 或 false")}if($.type==="object")try{return JSON.parse(T)}catch{Q0("data","需要 JSON 对象")}return T}async function P$(T,$,L,Y,W){if(Y.format==="raw"&&(Y.ids||Y.all||Y.maxItems||Y.pick||Y.filter?.length||Y.search?.length||Y.sort||Y.searchFields||Y.htmlToMarkdown))Q0("raw","原始响应不能与本地处理或自动翻页组合");let H={},Q=E0(T,$),X=(V,C)=>{if(C===void 0)return;if(Object.hasOwn(H,V)&&!L9(H[V],C))Q0(V,"同一字段的输入值冲突");H[V]=C};for(let[V,C]of Object.entries(W)){if(C===void 0)continue;let _=Q.find((q)=>q.name===V);X(V,_?b0(C,_):Number(C))}let G=B0(T,$).target;if(L!==void 0){if(!G)Q0("target","此操作没有位置参数");X(G,b0(L,Q.find((V)=>V.name===G)))}if(Y.data!==void 0)H.data=await zT(Y.data);let U=U0(T,$);if(U){if(Y.page!==void 0)X(U.page.name,b0(Y.page,U.page));if(Y.recPerPage!==void 0)X(U.size.name,b0(Y.recPerPage,U.size))}if(Y.all&&U&&(H[U.page.name]!==void 0||H.data?.[U.page.name]!==void 0))Q0("all/page","--all 与 --page 不能同时使用");if(Y.maxItems!==void 0&&(!/^\d+$/.test(Y.maxItems)||!Number.isSafeInteger(Number(Y.maxItems))||Number(Y.maxItems)<1))Q0("max-items","必须为正安全整数");let K=QT($,H,Y.ids),F={};for(let V of["product","project","execution"])if(H[V]!==void 0&&!Q.some((C)=>C.name===V))F[V]=H[V],delete H[V];let I=ZT(T,$,{...F,params:K?{...H,[N0($)]:K[0]}:H});if(K)delete I[N0($)];return I}v0();S();J0();NT();MT();T0();import{basename as H9,join as Q9}from"node:path";import{writeFileSync as X9}from"node:fs";import{createInterface as J9}from"node:readline/promises";function Y9(T,$="markdown"){if($==="markdown")return W9(T);return T}function W9(T){let $=process.argv.slice(2),L="auto";for(let W=0;W<$.length;W++)if($[W]==="--color")L=$[++W];else if($[W].startsWith("--color="))L=$[W].slice(8);return(L==="always"||L==="auto"&&process.stdout.isTTY&&process.env.NO_COLOR===void 0)&&typeof Bun<"u"&&typeof Bun.markdown.ansi==="function"?Bun.markdown.ansi(T):T}function k$(T,$,L){return Y9(G0(T,{format:$,isList:!1,fields:L?.fields}),$)}S();$0();i0();async function b$(T,$,L=!1){if(L||T==="json"||T==="raw"||!process.stdin.isTTY||!process.stderr.isTTY)throw new B("E2009",{option:"yes",reason:"非交互或机器可读模式下删除必须显式传入 --yes"});let Y=J9({input:process.stdin,output:process.stderr});try{return(await Y.question(`确认删除 ${$} 个对象?(y/n): `,{signal:A()})).toLowerCase()==="y"}finally{Y.close()}}function B9(T,$,L){let Y=$.format??L.defaultOutputFormat??"markdown";if(Y==="raw"){let H=G0(T.data,{format:Y,isList:T.isList,fields:T.fields,pager:T.pager,meta:T.meta,jsonPretty:L.jsonPretty,rawResponse:T.rawResponse});if(H)console.log(H);return}if(T.action.type==="list"){let H=G0(T.data,{format:Y,isList:!0,fields:T.fields,pager:T.pager,meta:T.meta,jsonPretty:L.jsonPretty});if(H)console.log(H);return}if(T.action.type==="get"){let H=k$(T.data,Y,{fields:T.fields});if(H)console.log(H);return}let W=G0(T.data,{format:Y,isList:!1,fields:T.fields,jsonPretty:L.jsonPretty});if(W)console.log(W);else if(Y==="markdown"||Y==="table"){let Q=T.rawResponse?.message;console.log(typeof Q==="string"&&Q.trim()?Q:"操作成功")}}async function B1(T,$,L,Y){let W=`/files/${$}/download?fileID=${$}`,H;try{H=await T.request(W,{method:"GET",responseType:"response"})}catch(C){throw v(C)}let Q=H.headers.get("Content-Disposition")??"",X=Q.match(/filename\*\s*=\s*(?:UTF-8'')?["']?([^"';\n]+)["']?/i),G=Q.match(/filename\s*=\s*(?:"([^"]+)"|'([^']+)'|([^;\n]+))/i),K=(X?.[1]??G?.[1]??G?.[2]??G?.[3])?.trim()||`file_${$}`;if(X)try{K=decodeURIComponent(K)}catch{}let I=Q9(L??".",H9(K)),V=await H.arrayBuffer();try{X9(I,Buffer.from(V),{flag:"wx"})}catch(C){let _=C.code==="EEXIST"?`目标文件已存在: ${I}`:`无法写入目标文件: ${I}`;throw new B("E2009",{option:"output",reason:_})}if(Y==="json"||Y==="raw")console.log(JSON.stringify({ok:!0,data:{file:I,size:V.byteLength}}));else console.log(`已下载: ${I} (${V.byteLength} bytes)`)}function G9(T,$){let L=$ instanceof Error?$:Error(String($));return{objectID:T,error:{...L instanceof B?{code:L.code,details:L.details}:{},message:L.message}}}function K9(T,$,L){if($==="json"||$==="raw")return n0({ok:T.failed.length===0,data:T.ids.map((W)=>T.success.includes(W)?{objectID:W,ok:!0,data:T.data?.find((H)=>H.objectID===W)?.value??null}:T.skipped.includes(W)?{objectID:W,ok:!1,skipped:!0}:{objectID:W,ok:!1,error:T.errors.find((H)=>H.objectID===W).error}),meta:{success:T.success.length,failed:T.failed.length,skipped:T.skipped.length}},L);let Y=[];if(T.data?.length){let W=T.data.map(({objectID:Q,value:X})=>X&&typeof X==="object"&&!Array.isArray(X)?{...X,objectID:Q}:{objectID:Q,value:X}),H=G0(W,{format:"markdown",isList:!0});if(H)Y.push(H)}if(Y.push(`操作成功:${T.success.length>0?T.success.join(", "):"无"}`,`操作失败:${T.failed.length>0?T.failed.join(", "):"无"}`),T.skipped.length>0)Y.push(`已跳过:${T.skipped.join(", ")}`);for(let W of T.errors){let H=W.error.code?`E${W.error.code}: `:"";Y.push(`${W.objectID}: ${H}${W.error.message}`)}return Y.join(`
|
|
930
|
+
`)}function j$(T,$){let L=j1(T.name),Y=$.format??"markdown",W=G0(L,{format:Y,isList:!1});if(W)console.log(W)}async function G1(T,$,L,Y,W,H,Q){let X=t(W),G=H.batchFailFast??X.batchFailFast??!1,U=H.format??X.defaultOutputFormat??"markdown",K=q0($,L);if(!K)throw new B("E2005",{module:$.name});let F=Q??ST(H,L,Y),I=QT(K,F,H.ids);if(I){if(U==="raw")throw new B("E2009",{option:"raw/ids",reason:"原始响应不支持批量组合,请使用 json"});if(K.type==="delete"&&!H.yes){if(!await b$(U,I.length,H.machineReadable||H.input===!1))return}let C={ids:I,success:[],failed:[],skipped:[],...K.type==="delete"?{}:{data:[]},errors:[]};for(let _=0;_<I.length;_++){A()?.throwIfAborted();let q=I[_],z=Number(q);try{let w=await c0(T,$,L,[],H,X,{...F,id:q});C.success.push(z),C.data?.push({objectID:z,value:w.data})}catch(w){if(A()?.throwIfAborted(),C.failed.push(z),C.errors.push(G9(z,w)),G){C.skipped.push(...I.slice(_+1).map(Number));break}}}if(console.log(K9(C,U,X.jsonPretty??!1)),C.failed.length>0)process.exitCode=1;return}if(K.type==="delete"&&!H.yes){if(!await b$(U,1,H.machineReadable||H.input===!1))return}let V=await c0(T,$,L,[],H,X,F);B9(V,H,X)}function x$(T,$=[]){return $.concat([T])}function E$(T){for(let $ of k1()){let L=I0($),Y=T.command($).description(L.display??$);if(Y.action(()=>Y.outputHelp()),Y.command("props").description("返回对象字段定义(离线)").action((W,H)=>{j$(L,H.optsWithGlobals())}),$==="file")Y.command("download").description("下载附件到本地文件(原始字节流,支持 Content-Disposition 命名)").argument("<fileID>","附件 ID").option("--output <dir>","输出目录,默认当前目录").action(async(...W)=>{let Q=W.at(-1).optsWithGlobals(),X=W[0];if(!/^\d+$/.test(X))throw new B("E2009",{option:"fileID",reason:"需要有效数字"});let{client:G,profile:U}=await H0(Q);try{await B1(G,X,typeof Q.output==="string"?Q.output:void 0,Q.format??"markdown")}catch(K){if(K instanceof B&&K.code==="1004"){let F=await iT(U,Q);if(F){await B1(F.client,X,typeof Q.output==="string"?Q.output:void 0,Q.format??"markdown");return}}throw K}});for(let W of L.actions){let H=B0(L,W),Q=Y.command(R0(W.name)).description(`${W.display??W.name}(最低版本:${W.minVersion.join(" / ")})`);if(H.target)Q.argument("[target]",`单个 ${H.target};也可使用命名参数`);let X=[],G=U0(L,W),U=new Set(G?[G.page.name,G.size.name]:[]);for(let K of E0(L,W)){if(U.has(K.name)||X.some((V)=>V.name===K.name))continue;let F=ET(K.name).slice(2),I=new K1(`--${F} ${K.type==="boolean"?"[boolean]":"<value>"}`,`${K.description??K.name}${K.required?"(必填)":""}`);if(K.type==="array")I.argParser((V,C=[])=>C.concat(V));if(K.type==="boolean")I.preset(!0);if(Q.addOption(I),X.push({name:K.name,attribute:I.attributeName()}),K.type==="boolean")Q.addOption(new K1(`--no-${F}`,`将 ${K.name} 设为 false`).default(void 0));if(K.type!=="array"){let V,C=()=>{let _=b0(Q.getOptionValue(I.attributeName()),K);if(V!==void 0&&!I9(V,_))throw new B("E2009",{option:F,reason:"重复选项的输入值冲突"});V=_};if(Q.on(`option:${I.name()}`,C),K.type==="boolean")Q.on(`option:no-${F}`,C)}}for(let K of["product","project","execution"]){if(!TT(L,W,K)||X.some((I)=>I.name===K))continue;let F=new K1(`--${K} <id>`,`${K}ID 或 scope/scopeID 别名`);Q.addOption(F),X.push({name:K,attribute:F.attributeName()})}if(W.requestBody)Q.option("--data <json|@file|@->","JSON 对象、文件或显式标准输入");if(H.batch)Q.option("--ids <ids>","批量目标 ID,逗号分隔并去重").option("--batch-fail-fast","失败后跳过剩余目标");if(W.type==="delete")Q.option("--yes","确认删除");if(W.type==="list"||W.type==="get")Q.option("--fields <fields>","返回字段,逗号分隔").option("--html-to-markdown","显式将富文本字段转换为 Markdown");if(W.type==="list")Q.option("--max-items <number>","整次命令最多返回条数"),Q.option("--filter <expr>","当前获取范围内过滤;组内 AND,多次指定为 OR",x$),Q.option("--search <keywords>","当前获取范围内搜索",x$),Q.option("--search-fields <fields>","本地搜索字段"),Q.option("--sort <expr>","当前获取范围内排序,如 id:asc");if(G)Q.option("--page <number>","指定页,从 1 开始").option("--page-size <number>","每次服务端请求的页大小").option("--all","显式遍历全部页面");Q.action(async(...K)=>{let I=K.at(-1).optsWithGlobals(),V={...I,pick:I.fields,recPerPage:I.pageSize},C=Object.fromEntries(X.map((w)=>[w.name,I[w.attribute]])),_=await P$(L,W,H.target?K[0]:void 0,V,C),{client:q,profile:z}=await H0(V);try{await G1(q,L,W.name,[],z,V,_)}catch(w){if(w instanceof B&&w.code==="1004"){let D=await iT(z,V);if(D){await G1(D.client,L,W.name,[],D.profile,V,_);return}}throw w}})}}}b();C1();S();function H2(T){let $=R1(T.command("mcp").description(J("启动 MCP 服务,支持本地 stdio 或多客户端 HTTP 访问禅道数据")).option("--transport <type>","传输方式 (stdio|http)","stdio")).action((L)=>O1(L,T.optsWithGlobals()));return R1($.command("serve").description("启动 MCP 服务").option("--transport <type>","传输方式 (stdio|http)","stdio")).action((L,Y)=>{let W=Y.optsWithGlobals();return O1(W,W)}),R1(T.command("mcp-server").description(J("启动 HTTP MCP 服务,供多个客户端访问固定禅道站点")).argument("[url]",J("禅道站点地址,与 --url 二选一;省略时读取 ZENTAO_URL"))).addHelpText("after",J(`
|
|
935
931
|
示例:
|
|
936
932
|
zentao mcp-server https://zentao.example.com
|
|
937
933
|
zentao mcp-server --url https://zentao.example.com
|
|
938
934
|
ZENTAO_URL=https://zentao.example.com zentao mcp-server
|
|
939
|
-
`)).action((
|
|
940
|
-
`);let
|
|
941
|
-
`);let
|
|
935
|
+
`)).action((L,Y)=>{if(L!==void 0&&Y.url!==void 0)throw new B("E2009",{option:"--url",reason:"位置参数 URL 与 --url 不能同时提供"});return O1({...Y,url:L??Y.url,transport:"http"},T.optsWithGlobals())}),$}function R1(T){return T.option("--host <host>","HTTP 监听地址(默认 127.0.0.1)").option("--port <port>","HTTP 监听端口(默认 9090)").option("--url <url>",J("HTTP 模式的固定禅道站点地址(亦可通过 ZENTAO_URL 设置)")).option("--read-only","仅提供查询工具,禁止业务写入和账号切换").option("--modules <names>","仅提供指定业务模块(逗号分隔,如 product,story,task)",($)=>$.split(",").map((L)=>L.trim())).option("--split-tools","按模块分为 _read 查询工具和 _write 写入工具")}async function O1(T,$){let L={assistant:$.assistant,insecure:$.insecure,timeout:$.timeout,profile:$.profile,readOnly:T.readOnly,modules:T.modules,splitTools:T.splitTools};if(T.transport!=="stdio"&&T.transport!=="http")throw new B("E2009",{option:"--transport",reason:"必须为 stdio 或 http"});if(T.transport==="stdio"){for(let F of["host","port","url"])if(T[F]!==void 0)throw new B("E2009",{option:`--${F}`,reason:"仅适用于 --transport http"});await F1(L);return}let Y=T.url??process.env[J("ZENTAO_URL")];if(!Y?.trim())throw new B("E2009",{option:"--url",reason:J("HTTP 模式必须指定禅道站点,或设置 ZENTAO_URL")});let W=T.port===void 0?9090:Number(T.port);if(T.port!==void 0&&!/^\d+$/.test(T.port)||!Number.isInteger(W)||W<1||W>65535)throw new B("E2009",{option:"--port",reason:"必须为 1–65535 的整数"});let{startMcpHttpServer:H}=await Promise.resolve().then(() => (W2(),Y2)),Q=await H({...L,url:Y,host:T.host,port:W});process.stderr.write(`MCP HTTP 服务已启动:${Q.url.href}
|
|
936
|
+
`);let X=new URL(Q.url);if(X.hostname==="0.0.0.0")X.hostname="127.0.0.1";if(X.hostname==="[::]")X.hostname="[::1]";process.stderr.write(`用户接入页面:${new URL("/start",X).href}
|
|
937
|
+
`);let G={mcpServers:{[J("zentao-remote")]:{type:"http",url:X.href,headers:{token:J("<your-zentao-token>")}}}};process.stderr.write([J(`
|
|
942
938
|
客户端配置示例(请替换为自己的禅道 Token,并合并到已有配置):`),`
|
|
943
|
-
Codex(~/.codex/config.toml):`,
|
|
944
|
-
Claude Code / Cursor(JSON):`,"Claude Code:~/.claude.json","Cursor:~/.cursor/mcp.json(或项目内 .cursor/mcp.json)",JSON.stringify(
|
|
939
|
+
Codex(~/.codex/config.toml):`,J("[mcp_servers.zentao-remote]"),`url = ${JSON.stringify(X.href)}`,J('http_headers = { token = "<your-zentao-token>" }'),`
|
|
940
|
+
Claude Code / Cursor(JSON):`,"Claude Code:~/.claude.json","Cursor:~/.cursor/mcp.json(或项目内 .cursor/mcp.json)",JSON.stringify(G,null,2),J(`
|
|
945
941
|
也可将 token 请求头替换为 Authorization: Bearer <your-zentao-token>,两种认证头任选其一。`),`远程客户端请将 url 替换为可访问的 HTTPS 服务地址。
|
|
946
942
|
`].join(`
|
|
947
|
-
`));let
|
|
948
|
-
`),process.exitCode=1}).finally(()=>{process.removeListener("SIGINT",
|
|
949
|
-
`);let
|
|
950
|
-
`);let{status:
|
|
951
|
-
${
|
|
952
|
-
`),process.exitCode
|
|
943
|
+
`));let U=!1,K=()=>{if(U)return;U=!0,Q.close().catch(()=>{process.stderr.write(`MCP HTTP 服务关闭失败
|
|
944
|
+
`),process.exitCode=1}).finally(()=>{process.removeListener("SIGINT",K),process.removeListener("SIGTERM",K)})};process.once("SIGINT",K),process.once("SIGTERM",K)}$0();S();Z0();import{createInterface as n9}from"node:readline/promises";b();import{spawn as m9}from"node:child_process";import{fileURLToPath as d9}from"node:url";var Q2=J("zentao-cli"),l9=`https://registry.npmjs.org/${Q2}/latest`;function kT(T){let $=T.trim().replace(/^v/,"").match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(!$)return null;return{major:Number($[1]),minor:Number($[2]),patch:Number($[3]),prerelease:$[4]??""}}function p9(T,$){let L=T.split("."),Y=$.split("."),W=Math.max(L.length,Y.length);for(let H=0;H<W;H++){let Q=L[H],X=Y[H];if(Q===void 0)return-1;if(X===void 0)return 1;let G=/^\d+$/.test(Q),U=/^\d+$/.test(X);if(G&&U){let K=Number(Q),F=Number(X);if(K!==F)return K>F?1:-1}else if(G!==U)return G?-1:1;else if(Q!==X)return Q>X?1:-1}return 0}function X2(T,$){for(let L of["major","minor","patch"])if(T[L]!==$[L])return T[L]>$[L]?1:-1;if(!T.prerelease&&$.prerelease)return 1;if(T.prerelease&&!$.prerelease)return-1;if(T.prerelease===$.prerelease)return 0;return p9(T.prerelease,$.prerelease)}function i9(T){let $=kT(T);return!!$&&$.prerelease===""}async function J2(T,$=1e4){let L=new AbortController,Y=()=>L.abort();if(T?.addEventListener("abort",Y,{once:!0}),T?.aborted)Y();let W=setTimeout(Y,$),H;try{H=await fetch(l9,{headers:{Accept:"application/json"},signal:L.signal})}catch(X){throw Error(`无法连接到 npm registry: ${X.message}`)}finally{clearTimeout(W),T?.removeEventListener("abort",Y)}if(!H.ok)throw Error(`npm registry 返回错误: ${H.status} ${H.statusText}`);let Q=await H.json();if(typeof Q.version==="string"&&i9(Q.version))return Q.version;if(typeof Q.version!=="string")throw Error("npm registry 返回数据格式异常");throw Error("npm registry 未找到正式版本")}function B2(){let T="";try{T=d9(import.meta.url)}catch{T=process.argv[1]??""}let $=T.replace(/\\/g,"/");if(/\/\.bun\/|\/bun\/install\//.test($))return"bun";return"npm"}function S1(T,$="latest"){let L=`${Q2}@${$}`;if(T==="bun")return{cmd:"bun",args:["add","-g",L]};return{cmd:"npm",args:["install","-g",L]}}async function G2(T,$="latest",L){let{cmd:Y,args:W}=S1(T,$);return{status:await new Promise((Q,X)=>{let G=m9(Y,W,{stdio:["ignore","pipe","pipe"],shell:process.platform==="win32",signal:L});G.stdout?.on("data",(U)=>process.stderr.write(U)),G.stderr?.on("data",(U)=>process.stderr.write(U)),G.once("error",X),G.once("close",Q)}),cmd:Y,args:W}}async function s9(T,$){if(!process.stdin.isTTY||!process.stderr.isTTY)throw new B("E2009",{option:"yes",reason:"非交互模式下必须显式确认升级"});let L=n9({input:process.stdin,output:process.stderr});try{return(await L.question(`发现新版本 ${T} → ${$},是否立即升级?[y/N] `,{signal:A()})).trim().toLowerCase()==="y"}finally{L.close()}}function K2(T){T.command("update").description("检查并升级 CLI 到最新版本").option("-y, --yes","跳过确认,直接升级").action(async($)=>{let L=T.optsWithGlobals(),Y=!!L.quiet,W=a();if(!Y)process.stderr.write(`正在检查最新版本...
|
|
945
|
+
`);let H=await J2(A(),L.timeout),Q=kT(W),X=kT(H);if(!Q||!X)throw Error(`版本号格式无法解析: 当前=${W}, 最新=${H}`);if(X2(Q,X)>=0){Z({current:W,latest:H,updated:!1},L);return}if(!$.yes&&L.input===!1)throw new B("E2009",{option:"yes",reason:"--no-input 时必须显式确认升级"});if(!($.yes||await s9(W,H))){Z({updated:!1,cancelled:!0},L);return}let U=B2(),{cmd:K,args:F}=S1(U,H);if(!Y)process.stderr.write(`执行: ${K} ${F.join(" ")}
|
|
946
|
+
`);let{status:I}=await G2(U,H,A());if(I===0)Z({previous:W,current:H,updated:!0},L);else throw Error(`升级失败,请手动运行:
|
|
947
|
+
${K} ${F.join(" ")}`)})}V1();function I2(T){yT(),f1(T),nT(T),tT(T),H$(T);let $=T.command("auth").description("认证与凭据");$.action(()=>$.outputHelp()),nT($),tT($),a1($),Q$(T),X$(T),B$(T),G$(T);let L=T.command("skill").description("安装或导出技能");L.action(()=>L.outputHelp()),_$(L);let Y=H2(T);Y1(Y),Y1(T,"add-mcp"),E$(T);let W=T.command("self").description("管理本机 CLI 安装");W.action(()=>W.outputHelp()),K2(W)}Z0();S();b();Y0();function V2(T){if(!/^\d+$/.test(T)||!Number.isSafeInteger(Number(T))||Number(T)<1)throw new B("E2009",{option:"timeout/deadline",reason:"必须为正安全整数(毫秒)"});return Number(T)}function F2(){let T=new t9,$=(L)=>L.replace(/^Usage:/gm,"用法:").replace(/^Options:/gm,"选项:").replace(/^Commands:/gm,"命令:").replace(/display help for command/g,"显示命令帮助");return T.configureOutput({writeOut:(L)=>process.stdout.write($(L)),writeErr:(L)=>process.stderr.write($(L)),outputError:()=>{}}),T.name(J("zentao")).description(J("禅道命令行工具")).version(a(),"-V, --version","显示 CLI 版本号").helpOption("-h, --help","显示命令帮助").addOption(new U2("--format <format>","输出格式").choices(["table","json","markdown","raw"])).option("--profile <key>","仅本次命令选择账号(优先于环境凭据)").option("--assistant <value>","本次操作来源标记;空字符串关闭标记",h0).option("--config <file>",J("配置文件路径(也支持 ZENTAO_CONFIG_FILE)")).option("--no-input","禁止浏览器、输入提示和选择菜单").option("-y, --yes","确认操作,不补全缺失参数").option("--quiet","压制进度和提示,保留结果和错误").addOption(new U2("--color <mode>","颜色控制").choices(["auto","always","never"]).default("auto")).option("--insecure","跳过 TLS 证书验证").option("--timeout <ms>","单次 HTTP 请求超时",V2).option("--deadline <ms>","整次命令期限,含认证和预取",V2).exitOverride(),I2(T),T.action(()=>T.outputHelp()),T}S();T0();$0();var q1=process.argv.slice(2);function C2(T){let $;for(let L=0;L<q1.length;L++){let Y=q1[L];if(Y==="--")break;let W=Y.indexOf("="),H=W<0?Y:Y.slice(0,W),Q=z1.options.find((G)=>G.long===H||G.short===H);if(!Q)continue;let X=W>=0?Y.slice(W+1):Q.required?q1[++L]:void 0;if(Q.long===T)$=X}return $}var z1=F2(),_2;z1.hook("preAction",(T,$)=>{let L=$.optsWithGlobals();if(L.format==="raw"&&$.name()!=="token"&&!I0($.parent?.name()??"")?.actions.some((Y)=>R0(Y.name)===$.name()))throw new B("E2009",{option:"raw",reason:"raw 仅适用于具有原始服务端响应的业务命令"});_2=s1(L)});try{let T=C2("--config")??process.env[J("ZENTAO_CONFIG_FILE")];if(T?.trim())i1(T);await z1.parseAsync(process.argv)}catch(T){if(T instanceof M1&&T.exitCode===0)process.exitCode=0;else{let $=n1(),L=$?new B($==="deadline"?"E5001":"E5003"):T instanceof M1?new B("E2009",{option:"argv",reason:T.message.replace(/^error: /,"").trim()}):T instanceof B?T:v(T),Y=L instanceof B?L:new B("E2008",{url:"",status:"",serverResponse:L instanceof Error?L.message:String(L)});process.stderr.write(E1(Y,C2("--format")??"table")+`
|
|
948
|
+
`),process.exitCode=$==="interrupt"||["5003","1008"].includes(Y.code)?130:T instanceof M1||["2001","2003","2004","2005","2007","2009"].includes(Y.code)?2:1}}finally{_2?.()}
|