@baocang/zentao-cli 0.5.1-enh.1 → 0.5.1-enh.2
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/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
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
|
|
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 E=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(o){n=[o]}if(n)throw n[0];return t};function u(e,...t){if(typeof e!=="string")return e.reduce((n,o,r)=>n+u(o)+(r<t.length?String(t[r]):""),"");return un(e,void 0)}function un(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"?un(e,n):e;let o=hr.get(n);if(!o)hr.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))?un(s,n):je(s,t||i==="examples"||i==="example",n)]));if(Object.freeze(r),!t)o.set(e,r);return r}function Ot(e,t){return(void 0)?.logoSvg?(void 0).logoSvg.replace("<svg ",`<svg class="${t}" aria-hidden="true" `):e}function yr(e,...t){return e.raw.reduce((n,o,r)=>n+u(o)+(r<t.length?String(t[r]):""),"")}var ke=void 0,hr;var L=E(()=>{hr=new WeakMap});import{extendModuleAction as Gi,getModule as br,getModuleAction as wr,getModuleNames as vr,getObjectProps as Vi,getModuleActionParams as Ji}from"zentao-api";function me(e){if(!e)return;try{return je(br(e))}catch{return}}function kr(){return vr()}function xr(){return vr().map((e)=>je(br(e)))}function zr(e){return Object.fromEntries(Object.entries(Vi(e)??{}).map(([t,n])=>[t,u(n)]))}function De(e,t){return je(wr(e.name,t))}var ge=(e,t,n)=>{let o=Ji(e,t,n);if(o.some((r)=>r.role==="body"&&r.textType==="html")&&!o.some((r)=>r.name==="uid")){let r=wr(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();Gi("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 Ki}from"zentao-api";function Tr(e){if(!e||typeof e!=="object")return!1;let t=e.code;return typeof t==="string"&&t.startsWith("E_")}function pn(e){return typeof e==="number"&&Number.isSafeInteger(e)&&e>0}function Cr(e){return typeof e==="string"&&e.length>0&&!/[^A-Za-z0-9_-]/.test(e)}function Q(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e,n=Cr(t.uid)?t.uid:void 0,o=Array.isArray(t.fileIDs)?t.fileIDs.filter(pn):[],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 l={stage:s,code:a,message:d};for(let f of["field","path","name","objectType"])if(typeof i[f]==="string")l[f]=i[f];if(pn(i.fileID))l.fileID=i.fileID;if(pn(i.objectID))l.objectID=i.objectID;if(Cr(i.uid))l.uid=i.uid;r.push(l)}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(!Tr(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??"")},Q(r));case"E_FILE_UPLOAD_FAILED":return new c("E2014",void 0,Q(r));case"E_FILE_SESSION_CHANGED":return new c("E2015",void 0,Q(r));case"E_FILE_SAVE_UNCONFIRMED":{let a=Q(r);if(!t)return new c("E2016",void 0,a);let d=e,l=new Set;while(!l.has(d)&&Tr(d.cause)&&d.cause.code===n)l.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:Xi(e)},r)}}function Xi(e){let t=Ki[e.code];if(!t)return e.message??String(e.code);return Sr(u(t),e.params)}function Sr(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=Q(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 Yi,c;var T=E(()=>{L();Yi={E1001:u("必须提供有效的禅道服务地址、用户名和密码或 TOKEN"),E1002:u("所提供的禅道服务地址 {url} 无法访问"),E1003:"当前用户名和密码不正确",E1004:u("所提供的 Token 已失效:终端执行 `zentao login` 重新登录,或更新 profile 中的 TOKEN;自动化环境提供 ZENTAO_URL + ZENTAO_ACCOUNT + ZENTAO_PASSWORD 后重试,命令会自动重连一次"),E1005:"配置文件损坏或无法读取,请检查 {path}",E1006:u("未找到可用的用户配置,请执行 `zentao login --web` 在浏览器中登录;终端登录使用 `zentao login --no-browser`"),E1007:u("指定的用户配置不存在,请通过 `zentao profile list` 查看可用配置"),E1008:"浏览器登录已取消",E1009:u("浏览器登录等待超时,请重新执行 `zentao login --web`"),E1010:u("无法启动本地登录服务,请检查本机网络权限,或使用 `zentao login --no-browser`"),E1011:"配置文件写入失败,请检查 {path} 的目录权限和磁盘空间",E1012:u("未能确认远端会话已撤销,已保留本地登录记录,请重试或联系禅道管理员"),E1013:"Token 所属账号为 {actual},与指定账号 {account} 不一致",E2001:u("未找到指定的模块 {module},请通过 `zentao help` 查看支持的模块"),E2002:"未找到指定的对象 {object},请检查对象 ID 是否正确",E2003:u("缺少必要参数 {fields},请通过 `zentao {module} --help` 查看必要参数"),E2004:"{field} 参数值 {value} 无效,请检查参数格式是否正确",E2005:u("不支持的操作,请通过 `zentao {module} --help` 查看支持的操作"),E2006:"当前用户没有权限执行此操作",E2007:"`--data` 参数中的 JSON 数据格式无效",E2008:u("禅道服务端返回错误(Url:{url},Status:{status}),请查看详细错误信息:{serverResponse}"),E2009:"选项 {option} 的值无效,{reason}",E2010:u("操作 {action} 不支持当前禅道版本 {version},最低版本要求:{minVersion},请升级对应系列的禅道版本"),E2011:u("无法识别禅道版本 {version},仅支持点分数字的正式版本(如 22.5、biz13.5、max8.5、ipd5.5)"),E2012:u("无法识别禅道服务端配置,请检查站点根地址的 ?mode=getconfig 是否返回包含 version 的 JSON 对象"),E2013:"无法解析富文本图片引用 {path}",E2014:"上传响应未提供有效的附件 ID",E2015:"图片上传期间登录会话已改变,本次操作已中止",E2016:"服务端未确认本次对象的保存结果",E5001:u("请求超时,请检查网络连接或禅道服务是否正常"),E5002:u("SSL/TLS 证书验证失败,请检查禅道服务地址是否正确"),E5003:"请求已取消",E5004:"无法启动 MCP HTTP 服务:{reason}",E5005:"无法写入附件 {path}:{reason}"};c=class c extends Error{code;details;constructor(e,t,n){let o=Sr(Yi[e],t);super(o);this.name=u("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 Mt(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 Qi}from"zentao-api";function ce(e,t){return e==="file"&&(t==="get"||t==="read")}function fn(){return new c("E2009",{option:"url",reason:"请提供当前站点的附件读取或下载链接"})}function Ne(e,t){let n=Qi(e,t);if(n===void 0)throw fn();return n}function Er(e,t){if(!/^(?:https?:)?\/\//i.test(e.trim()))return Ne(e);if(!t)throw fn();let n;try{n=new URL(e,"https://zentao.invalid/").origin}catch{throw fn()}let o=Ne(e,n);return t(e),o}var Ye=E(()=>{T()});function Ie(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 mn(e){let t=Ie(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 gn(e,t,n){if(!n.endsWith("ID"))return;return e.name==="file"&&t.name==="get"&&n==="fileID"?["integer","string"]:"integer"}function Ar(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"?gn(e,t,r.name):void 0)??"string"}))}function _e(e,t,n){if(t.type!=="list"||!t.pagerGetter)return;let o=n??Ar(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 hn(e){if(!e)return[];if(e==="user")return["id","account","realname","dept","role","status"];return["id","title","name","status",...e==="bug"?["severity"]:[],"assignedTo"]}function yn(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=Ar(e,t,n),r=_e(e,t,o),i=o.find((a)=>a.role==="path"&&!["scope","scopeID"].includes(a.name)),s=t.description;if(ce(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} ${Ie(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:mn(a.name)})),markdownFields:yn(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:Rt(t),destructive:!Rt(t)&&["update","delete","action"].includes(t.type),autoFill:pt(e,t),resultObjectType:t.resultObjectType,defaultFields:hn(typeof t.resultObjectType==="string"?t.resultObjectType:void 0),localFiles:t.requestBody?.mediaType==="multipart/form-data"}}function Rt(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 bn,Pr,ft,ee;var mt=E(()=>{bn=["table","json","markdown","raw"],Pr=ye.number().int().positive().max(1000),ft=ye.object({autoAssistant:ye.boolean(),defaultOutputFormat:ye.enum(bn),defaultRecPerPage:Pr,insecure:ye.boolean(),timeout:ye.number().int().positive(),htmlToMarkdown:ye.boolean(),batchFailFast:ye.boolean(),pagers:ye.record(ye.string(),Pr),jsonPretty:ye.boolean()}),ee={autoAssistant:!0,defaultOutputFormat:"table",defaultRecPerPage:20,insecure:!1,timeout:1e4,htmlToMarkdown:!0,batchFailFast:!1,pagers:{},jsonPretty:!1}});import{existsSync as is,readFileSync as ss}from"node:fs";import{dirname as as,join as wn}from"node:path";import{fileURLToPath as cs}from"node:url";function de(){return"0.5.1-enh.2"}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?ds[n]:""}var vn,ds;var be=E(()=>{L();T();Fe();vn=`${ke?.packageName??"zentao-cli"} ${de()}`,ds={cli:`CLI <${vn}>`,stdio:`AI <${vn}, mcp: stdio>`,http:`AI <${vn}, mcp: http>`}});function fs(e){return typeof e==="string"&&ls.test(e)&&us.test(e)&&ps.test(e)}function yt(e){if(fs(e))throw new c("E1004",void 0,{responseType:"login-page"})}async function $r(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 jr(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,l=a.value.subarray(0,d);s+=l.byteLength,i+=r.decode(l,{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 ls,us,ps,ht=65536;var Dr=E(()=>{T();ls=/^\s*<!doctype\s+html\b|^\s*<html\b/i,us=/(?:id|name)\s*=\s*["']loginForm["']|user-login(?:\.html)?/i,ps=/<input\b[^>]*\bname\s*=\s*["']account["'][^>]*>/i});import{ZentaoClient as ms}from"zentao-api";function U(e,t,n){return new Nr({baseUrl:e,token:t,insecure:n?.insecure,timeout:n?.timeout,actionAssistant:n?.actionAssistant??H()})}function te(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 Nr;var le=E(()=>{be();T();Dr();Nr=class Nr extends ms{async request(e,t){let n=await super.request(e,t);if(n instanceof Response)await jr(n);else if(n instanceof ArrayBuffer||n instanceof Blob)await $r(n);else yt(n);return n}}});import gs from"configstore";import{chmodSync as hs,existsSync as ys,mkdirSync as _r,rmdirSync as bs}from"node:fs";import{dirname as ws,isAbsolute as Fr,join as kn,resolve as vs}from"node:path";import{homedir as xn}from"node:os";import{z as ne}from"zod";function xs(){let e=process.env.XDG_CONFIG_HOME;return kn(e&&Fr(e)?e:kn(xn(),".config"),u("zentao"),u("zentao.json"))}function Ur(){if(!Lt)Lt=new gs(u("zentao-cli"),void 0,{configPath:Z,clearInvalidConfig:!1});return Lt}function zs(){try{if(ys(Z))hs(Z,384)}catch{}}function Ts(e){try{Ur().set(e),zs()}catch(t){let n=t?.code;throw new c("E1011",{path:Z},{operation:"write",reason:"write_failed",path:Z,...n?{systemCode:n}:{}})}}function $t(e){let t=`${Z}.lock`,n=!1;try{_r(ws(Z),{recursive:!0,mode:448});let o=Date.now()+5000;while(!n)try{_r(t,{mode:448}),n=!0}catch(s){if(s.code!=="EEXIST")throw s;if(Date.now()>=o)throw new c("E1011",{path:Z},{reason:"lock_timeout",path:t});Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,10)}let r=Re(),i=e(r);return Ts(r),i}catch(o){if(o instanceof c)throw o;throw new c("E1011",{path:Z},{operation:"write",reason:"write_failed",path:Z,systemCode:o.code})}finally{if(n)bs(t)}}function Cs(e){if(e==="~")return xn();if(e.startsWith("~/")||e.startsWith("~\\"))return kn(xn(),e.slice(2));return e}function Hr(e){if(typeof e!=="string"||e.trim()==="")throw Error("setConfigPath: path must be a non-empty string");let t=Cs(e),n=Fr(t)?t:vs(t);if(Lt&&n!==Z)throw Error("setConfigPath: cannot change config path after store has been initialized");Z=n}function Re(){let e;try{e=Ur().all}catch(t){let n=t?.code;throw new c("E1005",{path:Z},{operation:"read",reason:t instanceof SyntaxError?"invalid_json":"unreadable",path:Z,...n?{systemCode:n}:{}})}if(!ks.safeParse(e).success)throw new c("E1005",{path:Z},{operation:"read",reason:"invalid_structure",path:Z});return e}function q(e,t){return`${e}@${t}`}function J(e){return e.replace(/\/+$/,"")}function we(e=Re()){if(!e.currentProfile||!e.profiles?.length)return;return e.profiles.find((t)=>q(t.account,t.server)===e.currentProfile)}function et(e,t){let n=Re(),o=J(t);return n.profiles?.find((r)=>r.account===e&&J(r.server)===o)}function K(e,t=Re()){let n=t.profiles??[],o=n.find((i)=>q(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)=>q(i.account,i.server))});return r[0]}function tt(e){$t((t)=>{let n=J(e.server),o=(d)=>d.account===e.account&&J(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 jt(e,t){return $t((n)=>{let o=n.profiles??[];if(n.profiles=o.filter((r)=>q(r.account,r.server)!==e||t!==void 0&&r.token!==t),n.currentProfile===e&&!n.profiles.some((r)=>q(r.account,r.server)===e))n.currentProfile=void 0;return n.profiles.length!==o.length})}function wt(e){return $t((t)=>{let n=K(e,t);if(!n)return;return t.currentProfile=q(n.account,n.server),n})}function Br(){return Re().profiles??[]}function Y(e){return{...ee,...e.config}}function zn(e,t,n){$t((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 Dt(){return Z}function Ce(e,t,n,o,r,i){let s=new Date().toISOString();return{...i,server:J(e),account:t,token:n,user:i?{...i.user,...r}:r,loginTime:s,lastUsedTime:s,serverConfig:o??i?.serverConfig}}var ks,Z,Lt=null;var X=E(()=>{L();T();mt();ks=ne.object({currentProfile:ne.string().optional(),profiles:ne.array(ne.object({server:ne.string().url(),account:ne.string(),token:ne.string(),loginTime:ne.string().optional(),lastUsedTime:ne.string().optional(),user:ne.record(ne.string(),ne.unknown()).optional(),config:ft.partial().passthrough().optional(),serverConfig:ne.object({version:ne.string()}).passthrough().optional()}).passthrough()).optional()}).passthrough();Z=xs()});function I(){return Nt?.signal}function Zr(){return _t}function qr(e){Nt=new AbortController,_t=void 0;let t=()=>{_t="interrupt",Nt.abort(new c("E5003"))};process.once("SIGINT",t);let n=e.deadline?setTimeout(()=>{_t="deadline",Nt.abort(new c("E5001"))},e.deadline):void 0;return n?.unref(),()=>{clearTimeout(n),process.removeListener("SIGINT",t)}}var Nt,_t;var re=E(()=>{T()});import{getModuleAction as Ss,request as Wr}from"zentao-api";function Tn(e){return Boolean(Ss("my","profile",{version:e}))}async function vt(e,t,n){let{version:o}=await bt(e);if(Tn(o)){let{data:a}=await Wr("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 Wr("user/list",{browseType:"inside",orderBy:"id_asc",recPerPage:100,pageID:a,filters:[{field:"account",operator:"=",value:t}]},{client:e,throwOnFail:!0,actionAssistant:n}),l=Array.isArray(d.data)?d.data:[];if(i||=l.length>0,r=l.find((p)=>p.account===t),r||!l.length)break;let f=JSON.stringify(l.map((p)=>[p.id,p.account]));if(f===s||d.pager&&d.pager.page!==a)throw new c("E2008",{url:e.siteUrl,status:"",serverResponse:"用户列表分页未向前推进,无法确认当前用户详情"});if(s=f,d.pager?a*d.pager.recPerPage>=d.pager.total:l.length<100)break}return{user:r,hadUsers:i}}var Cn=E(()=>{le();T()});import{readFileSync as Es,statSync as As}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=te(r,o?.signal),s;try{s=await i.login(t,n)}catch(l){let f=N(l);if(f instanceof c&&f.code==="1002")throw new c("E1002",{url:e},f.details);throw f}let a,d=await bt(i);try{({user:a}=await vt(i,t))}catch(l){if(Tn(d.version))throw N(l)}if(o?.signal?.aborted)throw new c("E5003");return{client:r,token:s,user:a,serverConfig:d}}async function Gr(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[u("ZENTAO_URL")],account:process.env[u("ZENTAO_ACCOUNT")],password:process.env[u("ZENTAO_PASSWORD")],token:process.env[u("ZENTAO_TOKEN")]},t=process.env[u("ZENTAO_CREDENTIALS_FILE")];if(!t?.trim())return e;let n={};try{let s=As(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(Es(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?J(e.url):void 0,i=n.ZENTAO_URL?J(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();Cn();le();T();X()});function Se(e){if(typeof e==="string"){let o=K(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:J(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 ue(e,t){let n=e?.signal??I();if(n?.aborted)throw new c("E5003");let o=t??Se(e?.profile),r=o.source==="profile"?Y(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:te(U(s,d.value,i),n),profile:Ce(s,a,d.value)};let l=await Ue(s,a,d.value,{...i,signal:n});return{client:te(l.client,n),profile:Ce(s,a,l.token,l.serverConfig,l.user)}}return{client:te(U(o.server,o.token,i),n),profile:o.profile}}async function Ps(e,t){let n=He();if(!n.url||!n.account||!n.password)return;let o;try{o=J(n.url)}catch{return}if(o!==J(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:te(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 Ps(e.profile,t);if(r)return n(r.client,r.profile)}throw o}}var ot=E(()=>{le();T();X();re();rt();be()});import{createLink as Us,parseLink as oo,ZentaoError as so}from"zentao-api";function pe(e,t){throw new c("E2009",{option:e,reason:t})}function Hs(e){let t;try{t=new URL(e)}catch{return pe("server","请提供完整的 HTTP(S) 站点地址")}if(!/^https?:\/\//i.test(e)||t.username||t.password||/[?#]/.test(e))return pe("server","请提供不含凭据、查询参数或片段的 HTTP(S) 站点地址");return t}function Ut(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 pe("link","页面参数包含无效的 Unicode 字符")}}function io(e){if(e instanceof so&&typeof e.params.param==="string"&&e.params.param.startsWith("profile.serverConfig."))return e.params.param.slice(21)}async function Ht(e,t,n){let o=Hs(e.server);if(t.action==="parse"){if(!t.url.trim())return pe("url","请提供页面链接");let i;try{i=new URL(t.url,o)}catch{return pe("url","无效的页面链接")}if(i.username||i.password)return pe("url","页面链接中不能包含登录凭据");if(i.origin!==o.origin||!["http:","https:"].includes(i.protocol))return oo({server:o.href},t.url,{requestType:"auto"})}else if(!t.module.trim()||!t.method.trim())return pe("link","请提供页面模块名和方法名");let r=(i)=>{let s={server:o.href,serverConfig:i};if(t.action==="parse")return oo(s,t.url,{requestType:"auto"});let a=i?.requestType!=="GET"&&typeof i?.requestFix==="string"?i.requestFix:void 0,d=t.vars?.map((f)=>{let p=f.indexOf("=");if(p<1||!f.slice(0,p).trim())return pe("var","请使用 名称=值,可重复传入");return[Ut(f.slice(0,p)),Ut(f.slice(p+1),a)]}),l=Us(s,{moduleName:Ut(t.module,a),methodName:Ut(t.method,a),vars:d,relative:t.relative??!1});if(new URL(l,o).origin!==o.origin)return pe("link","页面链接超出当前站点");if(/\/(?:\.|%2e){1,2}(?:\/|$)/i.test(l))return pe("var","路径变量不能解析为 . 或 .. 目录");return l};try{let i=r(e.serverConfig);if(!(typeof i==="object"&&i.external&&!e.serverConfig?.requestType))return i}catch(i){let s=io(i);if(!(s&&i instanceof so&&i.code==="E_MISSING_PARAM")){if(s)return pe("serverConfig",`页面路由配置 ${s} 无效`);throw N(i)}}try{return r(await n())}catch(i){let s=io(i);if(s)return pe("serverConfig",`站点未提供有效的页面路由配置 ${s}`);throw N(i)}}var En=E(()=>{T()});function Bt(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[u("ZENTAO_URL")];if(e.profile===void 0&&t)return{server:t};let n=e.profile===void 0?we():K(e.profile);if(!n){if(e.profile!==void 0)throw new c("E1007");throw new c("E2009",{option:"server",reason:u("请用 --server 或 ZENTAO_URL 指定站点,或选择已保存的配置")})}return{server:n.server,serverConfig:n.serverConfig,timeout:n.config?.timeout,insecure:n.config?.insecure}}var An=E(()=>{L();T();X()});async function Zt(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 Pn=E(()=>{le();T()});import{isDeepStrictEqual as Ca}from"node:util";function Fn(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(!Fn(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 Ao(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=(f,p)=>{throw new c("E2009",{option:f,reason:p})};if(t.type==="update"&&!["auditplan","baseline","weekly"].includes(e.name)&&(r.comment!==void 0||n.comment!==void 0))s("comment",u`update 请求不支持 comment 字段(服务端会静默丢弃整个更新),添加备注请使用 zentao ${e.name} comment <id> --comment <text>`);for(let f of Object.keys(n)){if(f==="data"&&i)continue;if(!o.some((p)=>p.name===f))s(f,`操作 ${e.name}/${t.name} 不支持此参数`)}for(let f of Object.keys(r)){if(!o.some((p)=>p.name===f&&p.role==="body"))s(`data.${f}`,"不是此操作的请求体字段");if(n[f]!==void 0&&!Ca(n[f],r[f]))s(f,"params 与 params.data 中的参数值冲突")}let a=_e(e,t);if(a)for(let[f,p]of[[a.page,void 0],[a.size,a.size.maximum??1000]]){let g=r[f.name]??n[f.name];if(g!==void 0)qe(f.name,g,{...f,type:"integer",minimum:1,maximum:p})}let d=pt(e,t),l=t.requestBody?.schema.properties;for(let f of o){let g=f.role==="body"&&Object.hasOwn(r,f.name)?r[f.name]:n[f.name];if(g===void 0){if(f.required&&f.defaultValue===void 0&&!(f.role==="body"&&d)){let h=f.name==="scope"?"scope(查询范围:--product <id>、--project <id>、--execution <id>,或 --scope products --scope-id <id>)":f.name.endsWith("ID")?`${f.name}(如 ${mn(f.name)} <id>,或直接作位置参数)`:f.name;throw new c("E2003",{fields:h,module:e.name})}continue}let m=f.role==="path"?gn(e,t,f.name):void 0;if(qe(f.name,g,{...f,type:f.type??m,...f.role==="body"?l?.[f.name]:{}}),f.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((m||f.name.endsWith("ID")||["pageID","recPerPage"].includes(f.name))&&(!Number.isSafeInteger(g)||g<0))s(f.name,"必须为非负安全整数");if((f.name==="pageID"||f.name==="recPerPage")&&g<1)s(f.name,"必须为大于 0 的整数");if(f.name==="recPerPage"&&g>1000)s(f.name,"不能超过 1000")}}}var Wt=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 Gt(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(!ce(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=Er(n.url,o)}let l=(p,g)=>{if(g===void 0)return;let m=r[p],h=typeof m==="string"&&typeof g==="number"&&m===String(g)||typeof m==="number"&&typeof g==="string"&&String(m)===g;if(m!==void 0&&m!==g&&!h)d(p,"简写与 params 中的参数值冲突");r[p]=g};for(let p of["product","project","execution"]){let g=n[p],m=`${p}ID`;if(a){let h=[g,r[p],r[m]].filter((y)=>y!==void 0);if(h.length){l("scope",`${p}s`);for(let y of h)l("scopeID",y);delete r[p],delete r[m]}}else if(g!==void 0){let h=Tt(i,p);if(!h)d(p,`操作 ${e.name}/${t.name} 不支持此数字简写,请按字段类型使用 params`);l(h,g)}}let f=s.find((p)=>p.endsWith("ID")&&p!=="scopeID");if(n.id!==void 0||r.id!==void 0){if(!f)d("id",`操作 ${e.name}/${t.name} 没有可简写的路径 ID`);l(f,n.id),l(f,r.id),delete r.id}if(l("pageID",n.page),l("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 Ao(e,t,r,i),r}var Vt=E(()=>{xe();T();Wt();Ye()});import{realpath as Aa}from"node:fs/promises";import{homedir as Pa}from"node:os";import{basename as Oo,resolve as Hn}from"node:path";import{fileURLToPath as Oa,pathToFileURL as Ia}from"node:url";function Ct(e){return/^file:(?:\.\.?\/|~\/|\/\/)/i.test(e)}async function Io(e,t){let n=e.slice(5),o;if(n.startsWith("//"))try{let i=n.slice(2);o=/^(?:\/|localhost(?:\/|$))/i.test(i)?Oa(e):Hn(decodeURIComponent(i))}catch{return{url:e,filename:Oo(n)||"图片"}}else o=n.startsWith("~/")?Hn(Pa(),"."+n.slice(1)):Hn(n);let r=t.get(o);if(!r)r=await Aa(o).catch(()=>o),t.set(o,r);return{url:Ia(r).href,filename:Oo(o)||"图片"}}var Bn=()=>{};import Za from"turndown";function qa(){if(!qn)qn=new Za({headingStyle:"atx",codeBlockStyle:"fenced"});return qn}function Lo(e){return Wa.test(e)}function Ga(e){if(!e||!Lo(e))return e;return qa().turndown(e).trim()}function Yt(e){let t={...e};for(let n of["desc","description","content","steps","spec","verify","comment","bio"]){let o=t[n];if(typeof o==="string"&&Lo(o))t[n]=Ga(o)}return t}function $o(e){return e.map(Yt)}var qn=null,Wa;var jo=E(()=>{Wa=/<[a-z][\s\S]*>/i});import{AsyncLocalStorage as Va}from"node:async_hooks";import{realpathSync as Do}from"node:fs";import{sep as No}from"node:path";import{extendModuleAction as Ja}from"zentao-api";function st(){return Wn.getStore()===!0}function Fo(){let e=Wn.getStore();return e&&e!==!0?e.root:void 0}function Xt(e,t){let n,o;try{n=Do(e),o=Do(t)}catch{throw new c("E2009",{option:"file",reason:"文件或根目录不存在"})}if(n!==o&&!n.startsWith(o.endsWith(No)?o:o+No))throw new c("E2009",{option:"file",reason:"上传路径超出允许的根目录 ZENTAO_MCP_UPLOAD_ROOT"})}function Uo(e,t){if(!_o)Ja("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):{}}}}),_o=!0;return Wn.run(t?{root:t}:!0,e)}var Ge="HTTP MCP 不支持通过本地路径上传服务端文件,请使用本地 CLI 或 stdio MCP",Wn,_o=!1;var Qt=E(()=>{T();Wn=new Va});import{parseFragment as Zo}from"parse5";import{fileURLToPath as Ka}from"node:url";import{extendModuleAction as Ya}from"zentao-api";function en(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Xa(e){let t=[...Zo(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 Qa(e,t,n){for(let i of t){if(!Ct(i.src))continue;if(i.local=await Io(i.src,n),st())throw new c("E2009",{option:"file",reason:Ge});let s=Fo();if(s&&i.local.url.startsWith("file:"))Xt(Ka(i.local.url),s)}let o=t.map(({src:i,alt:s,local:a})=>{let d=!a&&s?' alt="'+en(s)+'"':"";return'<img src="'+en(a?.url??i)+'"'+d+">"}).join("");function r(i){let s=Zo(i).childNodes,a=[],d=0;for(let[l,f]of t.entries()){let p=s[l],g=p&&"tagName"in p&&p.tagName==="img"?p.attrs:[],m=g.find((b)=>b.name==="src")?.value,h=f.local,y=h&&g.some((b)=>b.name==="alt");if(!m||h&&!y&&m===h.url)throw new c("E2014");if(y)a.push(e.slice(d,f.tag.startOffset),"图片未上传:",en(f.alt.trim()||h.filename)),d=f.tag.endOffset;else{let{startOffset:b,endOffset:k}=f.attribute,w=e.slice(b,k),v=/^[^=]+=\s*/.exec(w)[0],z=w[v.length]==="'"?"'":'"';a.push(e.slice(d,b),v,z,en(m),z),d=k}}return a.push(e.slice(d)),a.join("")}return{workingHtml:o,restore:r}}function Gn(e){return typeof e==="string"&&/<img(?=[\t\n\f\r />])/i.test(e)&&/file:|&/i.test(e)}async function ec(e,t,n,o){if(!n.some((p)=>Gn(t[p])))return t;let r=e.action,i=r.requestBody,s=new Map,a=new Map,d=st(),l={...t};for(let[p,g]of o){let m=t[p];if(!Gn(m)||!d&&!g)continue;let h=Xa(m);if(!h.some((k)=>Ct(k.src)))continue;if(d)throw new c("E2009",{option:p,reason:Ge});let{workingHtml:y,restore:b}=await Qa(m,h,a);l[p]=y,s.set(p,b)}let f=Object.fromEntries([...o].filter(([,p])=>p).map(([p])=>[p,{textType:"html"}]));if(e.action={...r,requestBody:{...i,schema:{...i.schema,properties:f}}},s.size)l.toJSON=function(){let p={...this,toJSON:t.toJSON};for(let[g,m]of s)p[g]=m(this[g]);return p};return l}function qo(e,t,n,o){if(!t.requestBody||(t.requestBody.mediaType??"application/json")!=="application/json"||!["post","put"].includes(t.method?.toLowerCase()??""))return!1;let r=yn(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((l)=>!(s&&l==="content")).map((l)=>[l,Object.hasOwn(i,l)||Object.hasOwn(n,l)])),d=o&&r.some((l)=>a.get(l)&&Gn(i[l]??n[l]));if(n[Ho]={fields:a,rawWithImages:d},t.beforeRequest&&Bo.has(t.beforeRequest))return d;return Ya(e,t.name,(l)=>{let f=async(p)=>{let g=await l.beforeRequest?.(p)??{},m=p.params[Ho];if(!m)return g;if(Object.assign(p,g),m.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 ec(p,p.data,r,m.fields);return{}};return Bo.add(f),{...l,beforeRequest:f}}),d}var Ho,Bo;var Wo=E(()=>{T();Bn();Te();Qt();Ho=Symbol("supplied HTML fields"),Bo=new WeakSet});import{request as Vn,processData as tc}from"zentao-api";function Go(e){let t=e?.split(",").map((n)=>n.trim()).filter(Boolean);return t&&t.length>0?t:void 0}function rc(e){let t=e.split(",").map((n)=>n.trim()).find((n)=>!nc.test(n));if(t!==void 0)throw new c("E2009",{option:"sort",reason:`无效的排序表达式 "${t}",示例 id:asc 或 pri_desc;多字段用逗号分隔`})}function oc(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)rc(r.sort);let a={...o};if(t.name==="relation"&&s.name==="unlink"){let C=["objectType","objectID","relatedObjectType","relatedObjectID","relationName"].filter((P)=>Object.hasOwn(a,P));if(C.length)throw new c("E2009",{option:C.join(", "),reason:"解除关联已改用关系记录 relationID,请从 relation list 的返回结果获取,不能用对象 ID 或 relationKey 代替"})}let d=`${t.name}/${s.name}`,l=Go(r.pick),f=r.format??i.defaultOutputFormat??"table",p=f==="raw",g=r.htmlToMarkdown??(f!=="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 m=_e(t,s);if(r.all&&!m)throw new c("E2009",{option:"all",reason:"此操作不支持分页"});let h=a.data??{},y=(C)=>h[C]??a[C],b=(C,P)=>{if(a[C]=P,Object.hasOwn(h,C))h[C]=P};if(m){let C=Number(y(m.page.name)??r.page??1),P=Number(y(m.size.name)??r.recPerPage??i.pagers?.[t.name]??i.defaultRecPerPage??20);qe("page",C,{...m.page,type:"integer",minimum:1}),qe("page-size",P,{...m.size,type:"integer",minimum:1,maximum:m.size.maximum??1000}),b(m.page.name,C),b(m.size.name,P)}let k=!p,w=k&&s.type==="list",v=k&&s.type==="get",z=[],F=qo(t.name,s,a,p),S={client:e,actionAssistant:r.assistant,autoFill:pt(t,s),throwOnFail:!0,continueOnFileUploadError:!st(),onFileError:p?(C)=>{z.push(C)}:void 0,recPerPage:m?String(y(m.size.name)):void 0,timeout:r.timeout,insecure:r.insecure,convert:w&&g?$o:void 0,convertSingle:v&&g?Yt:void 0,filter:w?r.filter:void 0,search:w?r.search:void 0,searchFields:w?Go(r.searchFields):void 0,sort:w?r.sort:void 0,limit:w?r.maxItems:void 0,pick:w||v?l:void 0},x,A=[],M,D=0,_=0;try{if(p){let P,B={...S,onWriteOutcome:(ae)=>{P=ae}},V=F?(await Vn(d,a,{...B,raw:!1,throwOnFail:!1})).data:await Vn(d,a,{...B,raw:!0}),se=V&&typeof V==="object"?V:void 0;if(P==="unknown"){let ae=Q({uid:y("uid"),fileWarnings:z});throw new c("E2016",void 0,{response:V,...ae})}let Oe=!P&&(se?.status==="fail"||s.requestBody&&(se?.status==="error"||se?.result==="fail"||se?.result==="error"));if(P==="rejected"||Oe){let ae=P==="rejected"&&t.name==="file"&&se?.data?V:se?.message;throw new c("E2008",{url:"",status:"",serverResponse:typeof ae==="string"?ae:JSON.stringify(ae??V)},z.length?{response:V,fileWarnings:z}:V)}return{action:s,data:V,rawResponse:V,fields:l,isList:s.type==="list",...z.length?{fileWarnings:z}:{}}}let C;for(;;){if(x=await Vn(d,a,{...S,raw:!1,convert:void 0,filter:void 0,search:void 0,sort:void 0,limit:void 0,pick:w?void 0:S.pick}),C===void 0)M=x.resultObjectType;else if(x.resultObjectType!==M)M=void 0;if(!w)break;let P=Array.isArray(x.data)?x.data:[];D+=P.length;for(let se of P)A.push(se);if(!r.all)break;let B=x.pager;if(!B)throw new c("E2008",{url:"",status:"",serverResponse:"服务端未返回分页信息,无法保证全量结果"});let V=JSON.stringify(P);if(B.page!==Number(y(m.page.name))||C!==void 0&&V===C)throw new c("E2008",{url:"",status:"",serverResponse:"服务端分页未向前推进"});if(B.page*B.recPerPage>=B.total)break;if(!P.length)throw new c("E2008",{url:"",status:"",serverResponse:"服务端返回空页但报告仍有数据"});C=V,b(m.page.name,B.page+1)}if(w){if(A.every((P)=>P!==null&&typeof P==="object"&&!Array.isArray(P)))A=tc(A,{...S,limit:void 0});else M=void 0;if(_=A.length,r.maxItems)A=A.slice(0,Number(r.maxItems))}}catch(C){throw N(C,p)}let G=x.pager?{pageID:x.pager.page,recPerPage:x.pager.recPerPage,recTotal:x.pager.total}:void 0;if(s.type==="list"){let C=A;if(r.sort&&C.length&&!l){let se=(Oe,ae)=>ae.split(".").reduce((Pt,lt)=>Pt&&typeof Pt==="object"?Pt[lt]:void 0,Oe);for(let Oe of r.sort.split(",")){let ae=oc(Oe.trim());if(!C.some((lt)=>lt&&typeof lt==="object"&&ae.some((Wi)=>se(lt,Wi)!==void 0)))throw new c("E2009",{option:"sort",reason:`排序字段 "${ae[0]}" 不在返回数据中,请检查字段名(示例 id:asc)`})}}let P=G?G.pageID*G.recPerPage<G.recTotal:null,B={returned:C.length,fetched:D,page:G?.pageID??null,pageSize:G?.recPerPage??null,total:G?.recTotal??null,hasMore:P,truncated:_>C.length,processingScope:r.all?"all":"page",totalScope:"serverBeforeLocalProcessing"},V=f==="table"&&!l&&M?hn(M).filter((se)=>C.some((Oe)=>Oe!=null&&Object.hasOwn(Oe,se))):l;return{action:s,data:C,rawResponse:x,resultObjectType:M,pager:G,fields:V?.length?V:void 0,isList:!0,meta:B}}if(s.type==="get"){let C=x.data instanceof ArrayBuffer?Buffer.from(x.data).toString("base64"):x.data??{};if(g&&C&&typeof C==="object"&&!Array.isArray(C)&&Array.isArray(C.actions)){let P=C;C={...P,actions:P.actions.map((B)=>B&&typeof B==="object"&&!Array.isArray(B)?Yt(B):B)}}return{action:s,data:C,rawResponse:x,resultObjectType:x.resultObjectType,fields:l,isList:!1}}return{action:s,data:x.data,rawResponse:x,resultObjectType:x.resultObjectType,fields:l,isList:!1,...x.fileWarnings?.length?{fileWarnings:x.fileWarnings}:{}}}var nc;var Jn=E(()=>{T();jo();xe();Te();Wt();Qt();Wo();nc=/^[A-Za-z_][\w.]*?(?::(?:asc|desc)|_(?:asc|desc))?$/i});import{defineModuleActions as Ee,extendModuleAction as Et,getModuleAction as ic}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 ac(){Ee("bug",[Le("bug","assignto","指派Bug","bugID",{properties:Kn,required:["assignedTo"]})]),Ee("task",[Le("task","pause","暂停任务","taskID",{properties:Vo}),Le("task","cancel","取消任务","taskID",{properties:Vo}),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:sc},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:Kn,required:["assignedTo"]})]),Ee("ticket",[Le("ticket","assignto","指派工单","ticketID",{properties:Kn,required:["assignedTo"]})])}function cc(){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 dc(){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 lc(){for(let e of["create","update"])Et("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});Et("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}),Et("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 uc(e){let{status:t,...n}=e??{};return Object.values(n).filter((o)=>o&&typeof o==="object")}function Ko(e){return Yn.find((t)=>t.module===e)?.actionObjectType}function pc(){for(let e of Yn){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:uc,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 fc(){Et("task","create",(e)=>{let t=e.requestBody?.schema.required;if(!t)return e;let n=new Set(t);return n.add("estStarted"),n.add("deadline"),{...e,requestBody:e.requestBody?{...e.requestBody,schema:{...e.requestBody.schema,required:[...n]}}:e.requestBody}})}function mc(){for(let e of Yn){if(!e.detailPath)continue;let t=ic(e.module,"get"),n=typeof t?.resultGetter==="string"?t.resultGetter:void 0;if(!n)continue;Et(e.module,"get",{resultGetter:(o)=>{let r=o??{},i=r[n];if(!i||typeof i!=="object")return i;return Array.isArray(r.actions)?{...i,actions:r.actions}:i}})}}function tn(){if(Jo)return;Jo=!0,ac(),cc(),dc(),lc(),pc(),fc(),mc()}var Ae,Kn,Vo,sc,Yn,Jo=!1;var nn=E(()=>{Ae=["22.0","biz13.0","max8.0","ipd5.0"];Kn={assignedTo:{type:"string",description:"指派给"},comment:{type:"string",description:"备注"}},Vo={comment:{type:"string",description:"备注"}},sc=[{value:"pass",label:"通过"},{value:"reject",label:"拒绝"},{value:"clarify",label:"需澄清"}];Yn=[{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 rn(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 mi(e,t){if(t)return e?Sc:Cc;return e?pi: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?Q(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 li,ui,Pe,pi,fi,Cc,Sc;var nr=E(()=>{T();li=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()})),ui=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:ui.optional()}),pi=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()}),fi={fileWarnings:li.optional(),error:ui.extend({details:R.object({uid:R.string().optional(),fileIDs:R.array(R.number()).optional(),fileWarnings:li.optional()}).optional()}).optional()},Cc=Pe.extend(fi),Sc=pi.extend(fi)});import{z as j}from"zod";function At(e){return Rt(e)}function rr(e,t){if(t.readOnly&&!At(e))return!1;if(e.requestBody?.mediaType!=="multipart/form-data")return!0;return t.allowLocalFiles!==!1||t.localUploadRoot!==void 0}function Ec(e){return u`${e.display??e.name}操作;参数、示例和最低版本见 zentao_action_help`}function Ac(e){let t=e.actions.map((n)=>n.name);return[t[0],...t.slice(1)]}function Pc(e){let t=Ac(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(u("路径、查询或请求体参数;必填项见 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)=>ce(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:mi(r,n.some((s)=>s.role==="body"&&s.textType==="html"))}}function Oc(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:u`zentao_${e.name}${n?At(t)?"_read":"_write":""}`,arguments:ce(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 Ic(e,t,n){if(n!==void 0)Qe(n);let{client:o,identity:r}=await e.getContext(t),i=te(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:u("当前禅道版本不支持通过 Token 查询当前用户资料。")}:{}})}async function Mc(e,t){let{identity:n}=await t.switchProfile(e.profileKey),o=`${n.account}@${n.server}`;return ve({status:"success",currentProfile:o})}async function Rc(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(!rr(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 l,f,p=d?.length?he(s):void 0,g=Gt(e,s,p?{...t,params:{...t.params,[p]:d[0]}}:t,(z)=>{if(l=z,f=n.getSiteUrl?.(),f!==void 0)Ne(z,f)});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,S=typeof z==="string"?z:typeof F==="string"?F:void 0;if(!S)throw new c("E2009",{option:"file",reason:"需要本地文件路径"});Xt(S,o.localUploadRoot)}let{client:m,config:h}=await n.getContext(r);if(l!==void 0&&f!==m.siteUrl)Ne(l,m.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(te(m,r),e,s.name,z,y,h),k=(z)=>o.allowLocalFiles===!1?Uo(z,o.localUploadRoot):z();if(d?.length){let z=he(s),{outcomes:F,failed:S,skipped:x}=await rn({ids:d,failFast:t.batchFailFast??!1,throwIfAborted:()=>r?.throwIfAborted(),execute:(D)=>k(()=>b({...g,[z]:D}))}),A=[],M=[];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));M.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:S===0,data:A,meta:{success:d.length-S-x.length,failed:S,skipped:x.length,...M.length?{errors:M}:{}}},{isError:S>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 Lc(e){let t=e.every(At),n=e.some((o)=>["update","delete","action"].includes(o.type));return{readOnlyHint:t,destructiveHint:n,openWorldHint:!0}}function gi(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}):xr();if(!o.length)throw new c("E2009",{option:"modules",reason:"至少指定一个模块"});if(e.registerTool(u("zentao_action_help"),{description:u("查看禅道操作的路径、参数定义和最低版本要求,无需登录;调用业务工具前可按需查询"),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),...ce(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)&&rr(a,n),...n.allowLocalFiles===!1&&n.localUploadRoot===void 0&&a.requestBody?.mediaType==="multipart/form-data"?{unavailableReason:Ge}:{},example:Oc(s,a,n.splitTools)})}catch(s){return Ve(s,{module:r,action:i})}}),e.registerTool(u("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 Ic(t,i.signal,r.assistant??n.assistant)}catch(s){return Ve(s)}}),t.switchProfile&&!n.readOnly)e.registerTool(u("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 Mc(r,t)}catch(i){return Ve(i)}});for(let r of new Set(o)){let i=r.actions.filter((a)=>rr(a,n)),s=n.splitTools?[{suffix:"_read",actions:i.filter(At)},{suffix:"_write",actions:i.filter((a)=>!At(a))}]:[{suffix:"",actions:i}];for(let a of s){if(!a.actions.length)continue;let d={...r,actions:a.actions},l=u`zentao_${d.name}${a.suffix}`,f=Ec(d),p=Pc(d),g=Lc(d.actions);e.registerTool(l,{description:f,...p,annotations:g},async(m,h)=>{let y=m;try{if(!a.actions.some((b)=>b.name===y.action))throw new c("E2006");return await Rc(r,y,t,n,h.signal)}catch(b){return Ve(b,{module:d.name,action:y.action})}})}}}var hi=E(()=>{L();Cn();Te();Qt();xe();xe();Jn();T();le();be();Vt();Ye();nr();Ke()});import{z as $e}from"zod";function on(e,t){let n,o,r;return(i,s)=>{if(s?.aborted)throw new c("E5003");let a=e();return Ht(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 l=n.getZentaoConfig({timeout:t?.timeout??a.timeout});if(!s)return l;let f,p=new Promise((g,m)=>{if(f=()=>m(new c("E5003")),s.addEventListener("abort",f,{once:!0}),s.aborted)f()});try{return await Promise.race([l,p])}finally{s.removeEventListener("abort",f)}})}}function yi(e,t){e.registerTool(u("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 or=E(()=>{le();En();L();T();nr()});import{McpServer as $c}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as jc}from"@modelcontextprotocol/sdk/server/stdio.js";function sn({client:e,profile:t}){return{client:e,config:Y(t),identity:{server:t.server,account:t.account}}}function Dc(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:on(()=>Bt({profile:s}),e),async getContext(a){if(a?.aborted)throw new c("E5003");if(!n){let k=new AbortController,w=ue({...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,l=i,f=o?.promise===d?o:void 0;if(f)f.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(f&&--f.waiters===0&&f.pending){if(f.controller.abort(),n===d)n=void 0}}if(a?.aborted)throw new c("E5003");if(l)return sn(g);let m=et(g.profile.account,g.profile.server);if(!m?.token)throw new c("E1006");if(n===d)s=q(m.account,m.server);let h=Y(m),y=Y(g.profile);if(m.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 sn({client:g.client,profile:m});let b=ue({...t,profile:m});if(n===d)n=b;return sn(await b)},async switchProfile(a){let d=K(a);if(!d)throw new c("E1007");let l=await ue({...t,profile:d});return n=Promise.resolve(l),i=!1,s=q(d.account,d.server),sn(l)}}}function ct(e,t){tn();let n=new $c({name:u("zentao-cli"),version:de()},{capabilities:{tools:{}}});if(gi(n,e,t),e.pageLink)yi(n,e.pageLink);return n}async function ir(e){let t=ct(Dc(e),e),n=new jc;await t.connect(n)}var sr=E(()=>{L();ot();X();An();rt();T();hi();Fe();be();or();nn()});var Nc,_c,dt;var ar=E(()=>{L();Nc={language:"语言",darkMode:"深色模式",switchDark:"切换至深色模式",switchLight:"切换至浅色模式",title:u("接入禅道 MCP"),site:u("禅道站点"),steps:"接入步骤",progress:"接入进度",step1:"准备 Token",step2:"配置 Agent",step3:"验证连接",method:"Token 获取方式",login:"账号登录",existing:"已有 Token",username:"用户名",password:"密码",usernamePlaceholder:u("禅道用户名"),passwordPlaceholder:"输入密码",personalToken:"个人 Token",getToken:"获取 Token 并继续",continue:"继续配置",trust:u("账号密码经此服务发送至禅道,不保存。"),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:u("发送给 AI 后,Token 可能被 AI 服务商处理,并保存在对话记录或日志中;泄露后他人可能以你的权限访问禅道。预览仍隐藏 Token。"),copyInstructions:"复制接入说明",copiedInstructions:"已复制 · 让 Agent 说明配置位置和 Token 设置方法",previewPrompt:"预览说明",manual:"手动配置",chooseAgent:"选择 Agent",copyConfig:"复制配置",nextVerify:"配置好了,去验证",verifyTitle:"在 Agent 中验证",verifyIntro:"重载或重启 Agent 后,发送这条提问:",verifyPrompt:u("请通过 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:u("请填写禅道用户名和密码。"),invalidToken:"请只粘贴 Token 值,不要包含引号、请求头名称或空格。",tokenRequired:"请填写个人 Token。",submitting:"正在获取…",connecting:u("正在连接禅道,请稍候。"),networkError:"连接失败,请检查网络后重试。",copyFailed:"复制失败,请允许浏览器访问剪贴板,或手动复制预览并填写 Token。",copiedSecret:"已复制,内容包含个人 Token,请妥善保管。",clearedNotice:"页面中的 Token 已清除。已复制或保存到 Agent 的 Token 不受影响。",insecure:"请通过管理员提供的 HTTPS 地址打开,再填写密码或 Token。本机可使用 http://127.0.0.1。",noScript:"请启用 JavaScript 后获取 Token 和复制配置。",readOnly:"仅开放查询",readWrite:"开放查询与操作",allModules:"全部可用模块",accountPermissions:u("实际权限以你的禅道账号为准。"),reachable:"Agent 所在环境需要能访问此地址。",officialDocs:"官方配置文档 ↗",mergeHint:"合并到已有配置,保留其他服务。",noQuery:"请使用不含查询参数的接入页面。",pageMethod:"请通过浏览器打开接入页面。",postOnly:"仅支持 POST。",invalidOrigin:"请求来源不正确,请重新打开接入页面。",expired:"请求来源不正确或服务已重启,请刷新页面后重试。",httpsRequired:"请通过管理员提供的 HTTPS 地址获取 Token。",jsonRequired:"请通过接入页面提交 JSON 登录信息。",busy:"获取 Token 的用户较多,请稍后重试。",tooLarge:"登录信息过长,请检查输入。",bodyTimeout:"接收请求超时,请重试。",invalidJson:"登录信息格式不正确。",invalidCredentialsInput:u("请填写有效的禅道用户名和密码,禅道地址由管理员设置。"),cancelled:"请求已取消。",invalidTokenResponse:u("禅道返回的 Token 格式无效,请联系管理员。"),invalidCredentials:"用户名或密码不正确,或当前账号不允许登录,请检查后重试。",timeout:u("连接禅道超时,请稍后重试。"),certificate:u("禅道的 HTTPS 证书验证失败,请联系管理员。"),loginFailed:u("无法获取 Token,请检查网络,或联系管理员确认禅道服务和 API 登录是否可用。")},_c={language:"Language",darkMode:"Dark mode",switchDark:"Switch to dark mode",switchLight:"Switch to light mode",title:u("Connect ZenTao MCP"),site:u("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:u("ZenTao username"),passwordPlaceholder:"Enter your password",personalToken:"Personal token",getToken:"Get token and continue",continue:"Continue to setup",trust:u("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:u("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:u("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:u("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:u("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:u("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:u("Enter a valid ZenTao username and password. The site address is set by your administrator."),cancelled:"Request cancelled.",invalidTokenResponse:u("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:u("The ZenTao connection timed out. Try again later."),certificate:u("ZenTao’s HTTPS certificate could not be verified. Contact your administrator."),loginFailed:u("Could not get a token. Check your network, or ask your administrator to check ZenTao and API sign-in.")},dt={zh:Nc,en:_c}});var bi;var wi=E(()=>{L();bi=yr`
|
|
4
4
|
(() => {
|
|
5
5
|
const $ = id => document.getElementById(id);
|
|
6
6
|
const root = document.documentElement;
|
|
@@ -241,7 +241,7 @@ 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
241
|
feedback('zt-login-feedback', 'trust');
|
|
242
242
|
render();
|
|
243
243
|
})();
|
|
244
|
-
`});function
|
|
244
|
+
`});function Fc(e,t,n,o="zh"){if(e==="codex")return`[mcp_servers.zentao-remote]
|
|
245
245
|
url = ${JSON.stringify(t)}
|
|
246
246
|
http_headers = { token = ${JSON.stringify(n)} }`;if(e==="cherry"&&o==="en")return`Name: zentao-remote
|
|
247
247
|
Type: Streamable HTTP
|
|
@@ -251,9 +251,9 @@ Authentication: Personal token (no OAuth)`;if(e==="cherry")return`名称:zenta
|
|
|
251
251
|
类型:Streamable HTTP
|
|
252
252
|
URL:${t}
|
|
253
253
|
请求头:token: ${n}
|
|
254
|
-
认证:个人 Token(无需 OAuth)`;let r={token:n};if(e==="opencode")return JSON.stringify({mcp:{"zentao-remote":{type:"remote",url:t,headers:r,oauth:!1,enabled:!0}}},null,2);let i=e==="gemini"?{httpUrl:t,headers:r}:{type:e==="cline"?"streamableHttp":"http",url:t,headers:r};return JSON.stringify({[e==="vscode"?"servers":"mcpServers"]:{"zentao-remote":i}},null,2)}function
|
|
254
|
+
认证:个人 Token(无需 OAuth)`;let r={token:n};if(e==="opencode")return JSON.stringify({mcp:{"zentao-remote":{type:"remote",url:t,headers:r,oauth:!1,enabled:!0}}},null,2);let i=e==="gemini"?{httpUrl:t,headers:r}:{type:e==="cline"?"streamableHttp":"http",url:t,headers:r};return JSON.stringify({[e==="vscode"?"servers":"mcpServers"]:{"zentao-remote":i}},null,2)}function Uc(e,t,n,o="zh"){if(o==="en")return["Help me configure our ZenTao MCP service in the Agent I am currently using.","","Server name: zentao-remote",`ZenTao site: ${e}`,`MCP server URL: ${t}`,"Transport: Streamable HTTP",`Authentication header: token: ${n}`,"","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(`
|
|
255
255
|
`);return["请帮我在当前使用的 Agent 中配置公司的禅道 MCP 服务。","","服务名称:zentao-remote",`禅道地址:${e}`,`MCP 服务地址:${t}`,"传输方式:Streamable HTTP",`认证请求头:token: ${n}`,"","请按当前 Agent 的官方文档准备用户级 MCP 配置,保留已有服务。","请告知需要修改的 MCP 配置文件完整路径,以及设置 token 请求头的具体字段和方法;若通过界面配置,请给出入口和字段。","Token 为占位符时,由我在本机填写真实值。不要要求我在对话中提供禅道密码或 Token。","本机无需安装 zentao-cli 或启动 MCP 进程。","Token 只用于请求头。不要在回复中显示真实 Token,也不要提交到项目仓库。","等我在本机设置好 Token 后,再指导我重载或重启 Agent。","最后验证连接:请通过 zentao-remote MCP 查询我有权访问的产品列表,只显示 ID 和名称。"].join(`
|
|
256
|
-
`)}function
|
|
256
|
+
`)}function ki(e){let t=(r)=>r.replace(/[&<>"']/g,(i)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[i]),n=(r)=>t(dt.zh[r]),o=JSON.stringify({site:e.url,key:e.key,readOnly:!!e.readOnly,modules:e.modules,guides:vi,messages:dt}).replace(/</g,"\\u003c");return u`<!doctype html>
|
|
257
257
|
<html lang="zh-CN">
|
|
258
258
|
<head>
|
|
259
259
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
@@ -442,7 +442,7 @@ button:active:not(:disabled) { opacity: .85; }
|
|
|
442
442
|
<body>
|
|
443
443
|
|
|
444
444
|
<header class="zt-topbar">
|
|
445
|
-
<div class="zt-brand">${
|
|
445
|
+
<div class="zt-brand">${Ot('<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
446
|
<div class="zt-preferences">
|
|
447
447
|
<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
448
|
<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>
|
|
@@ -518,7 +518,7 @@ button:active:not(:disabled) { opacity: .85; }
|
|
|
518
518
|
<p id="zt-copy-feedback" class="zt-feedback zt-action-feedback" role="status" aria-live="polite"></p>
|
|
519
519
|
</div>
|
|
520
520
|
<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">${
|
|
521
|
+
<label class="zt-label" for="zt-client" data-i18n="chooseAgent">选择 Agent</label><select id="zt-client" class="zt-input">${vi.map((r)=>`<option value="${r.id}">${r.name}</option>`).join("")}</select>
|
|
522
522
|
<p id="zt-agent-steps" class="zt-caption zt-guide-text"></p>
|
|
523
523
|
<a id="zt-agent-docs" class="zt-caption" target="_blank" rel="noreferrer" data-i18n="officialDocs"></a>
|
|
524
524
|
<pre id="zt-config" class="zt-code" tabindex="0"></pre>
|
|
@@ -547,29 +547,35 @@ button:active:not(:disabled) { opacity: .85; }
|
|
|
547
547
|
|
|
548
548
|
<script nonce="${t(e.nonce)}">
|
|
549
549
|
const data = ${o};
|
|
550
|
-
const makeConfig = ${
|
|
551
|
-
const makePrompt = ${
|
|
552
|
-
${
|
|
550
|
+
const makeConfig = ${u(Fc.toString())};
|
|
551
|
+
const makePrompt = ${u(Uc.toString())};
|
|
552
|
+
${bi}
|
|
553
553
|
</script>
|
|
554
|
-
</body></html>`}var
|
|
555
|
-
`)}function
|
|
554
|
+
</body></html>`}var vi;var xi=E(()=>{L();ar();wi();vi=[{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:u("将配置合并到 ~/.codex/config.toml。重新加载 MCP 或重启应用 / CLI,再确认 zentao-remote 已启用。"),stepsEn:u("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 zi}from"node:crypto";function Ti(e){let t=H(e.assistant,!0,"http"),n=zi(32).toString("hex"),o=0;return async({path:r,method:i,headers:s,signal:a,readBody:d})=>{let l=zi(18).toString("base64"),f={...i==="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-${l}'; style-src 'nonce-${l}'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`},p=(m,h,y)=>Response.json({error:dt.zh[h],errorCode:h},{status:m,headers:{...f,...y}});if(r.includes("?"))return p(400,"noQuery");if(r==="/start"||r==="/start/"){if(i!=="GET")return p(405,"pageMethod",{Allow:"GET"});return new Response(ki({...e,nonce:l,key:n}),{headers:{...f,"Content-Type":"text/html; charset=utf-8"}})}if(i!=="POST")return p(405,"postOnly",{Allow:"POST"});let g;try{g=new URL(s.get("origin")??"")}catch{return p(403,"invalidOrigin")}if(!["http:","https:"].includes(g.protocol)||g.origin!==s.get("origin")||g.host!==s.get("host")?.toLowerCase()||s.get(u("x-zentao-start"))!==n||![null,"same-origin","none"].includes(s.get("sec-fetch-site")))return p(403,"expired");if(g.protocol!=="https:"&&!["localhost","127.0.0.1","[::1]"].includes(g.hostname))return p(403,"httpsRequired");if(s.get("content-type")?.split(";")[0].trim().toLowerCase()!=="application/json")return p(415,"jsonRequired");if(o>=8)return p(429,"busy",{"Retry-After":"5"});o++;try{let{body:m,status:h}=await d();if(h)return p(h,h===413?"tooLarge":h===408?"bodyTimeout":"invalidJson");if(!m||typeof m!=="object"||Array.isArray(m))return p(400,"required");let y=m;if(Object.keys(y).some((k)=>!["account","password"].includes(k))||typeof y.account!=="string"||!y.account.trim()||y.account.length>256||typeof y.password!=="string"||!y.password||y.password.length>4096)return p(400,"invalidCredentialsInput");if(a.aborted)return p(400,"cancelled");let b=await Zt(e.url,y.account.trim(),y.password,{...e,actionAssistant:t,signal:a});if(!/^[A-Za-z0-9\-._~+/]+=*$/.test(b))return p(502,"invalidTokenResponse");return Response.json({token:b},{headers:f})}catch(m){let h=m instanceof c?m.code:"";if(["1003","1004","2006"].includes(h))return p(401,"invalidCredentials");if(h==="5001")return p(504,"timeout");if(h==="5002")return p(502,"certificate");return p(502,"loginFailed")}finally{o--}}}var cr=16384,an=(e)=>["/start","/start/","/start/token"].includes(e);var Ci=E(()=>{L();Pn();T();xi();ar();be()});import{createServer as Hc}from"node:http";import{StreamableHTTPServerTransport as Bc}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{WebStandardStreamableHTTPServerTransport as Zc}from"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";function qc(e){let t=[];for(let i=0;i<e.length;i+=2){let s=e[i].toLowerCase();if(s==="token"||s==="authorization")t.push([s,e[i+1]])}if(t.length!==1)return;let[n,o]=t[0];return(n==="token"?/^([A-Za-z0-9\-._~+/]+=*)$/:/^Bearer ([A-Za-z0-9\-._~+/]+=*)$/i).exec(o)?.[1]}function Ai(e,t,n,o){if(o.some((i,s)=>s%2===0&&i.toLowerCase()==="origin"))return{status:403,message:"不支持浏览器 Origin 请求"};if(e==="/healthz"&&t==="GET")return{status:200};if(e!=="/mcp")return{status:404,message:"未找到接口"};if(t!=="POST")return{status:405,message:"仅支持 POST"};let r=qc(o);if(!r||n)return{status:401,message:u("请通过单个 token 或 Authorization: Bearer 请求头提供禅道 Token")};return{token:r}}function Pi(e,t,n,o){let r=t==="/mcp"||t==="/healthz"||an(t)?t:"/unknown",i=["POST","GET","DELETE","PUT","PATCH","HEAD","OPTIONS"].includes(e)?e:"OTHER";process.stderr.write(`[mcp-http] ${i} ${r} ${n} ${Date.now()-o}ms
|
|
555
|
+
`)}function Oi(e){return e===413?"请求体超过 1 MiB":e===408?"接收请求超时":"JSON 请求体无效"}function cn(e,t,n){if(e.destroyed||e.writableEnded)return;if(e.headersSent){e.destroy();return}e.writeHead(t,{"Content-Type":"application/json; charset=utf-8",...e.req.method==="POST"?{Connection:"close"}:{}}),e.end(JSON.stringify({error:n}))}function Si(e,t=dr){return new Promise((n)=>{let o=[],r=0,i=!1,s=(p)=>{if(i)return;i=!0,clearTimeout(f),e.off("data",a),e.off("end",d),e.off("error",l),e.off("aborted",l),n(p)},a=(p)=>{if(r+=p.length,r>t)s({status:413}),e.resume();else o.push(p)},d=()=>{try{s({body:JSON.parse(Buffer.concat(o).toString("utf8"))})}catch{s({status:400})}},l=()=>s({status:400}),f=setTimeout(()=>{s({status:408}),e.resume()},dn);f.unref(),e.on("data",a),e.once("end",d),e.once("error",l),e.once("aborted",l)})}async function Ii(e){let t=H(e.assistant,!0,"http");if(e={...e,allowLocalFiles:!1},e.localUploadRoot===void 0){let m=process.env[u("ZENTAO_MCP_UPLOAD_ROOT")];if(m?.trim())e={...e,localUploadRoot:m.trim()}}if(!process.versions.bun){let[m,h,y]=process.versions.node.split(".").map(Number);if(m<18||m===18&&(h<14||h===14&&y<1))throw new c("E5004",{reason:"HTTP 模式需要 Node.js 18.14.1 或更新版本"})}for(let[m,h]of[["timeout",e.timeout],["port",e.port]])if(h!==void 0&&(!Number.isInteger(h)||h<(m==="port"?0:1)||h>(m==="port"?65535:2147483647)))throw new c("E2009",{option:m,reason:m==="port"?"必须为 0–65535 的整数":"必须为 1–2147483647 的整数毫秒数"});if(e.host!==void 0&&!e.host.trim())throw new c("E2009",{option:"host",reason:"监听地址不能为空"});let n;try{if(n=new URL(e.url),!["http:","https:"].includes(n.protocol)||n.username||n.password||n.search||n.hash)throw Error()}catch{throw new c("E2009",{option:"url",reason:u("请提供不含凭证、查询参数或片段的 HTTP(S) 禅道站点地址")})}let o=U(n.toString()).siteUrl,r={...ee,pagers:{},timeout:e.timeout??ee.timeout,insecure:e.insecure??ee.insecure},i=Ti({...e,url:o,timeout:r.timeout}),s=on(()=>({server:o}),r),a=(m)=>({pageLink:s,getSiteUrl:()=>o,async getContext(){return{client:U(o,m,{...r,actionAssistant:t}),config:r,identity:{server:o}}}});if(await ct(a(),e).close(),process.versions.bun)return Wc(e,r.timeout,a,i);let d=new Set,l=new Set,f=Hc({requestTimeout:dn},(m,h)=>{let y=Date.now(),b=m.url?.split("?")[0]??"",k=m.method??"",w,v,z=!1,F=new AbortController,S=()=>{if(z)return;z=!0,F.abort(),clearTimeout(v),d.delete(x),m.socket.off("close",S),w?.close().catch(()=>{}),Pi(k,b,h.writableFinished?h.statusCode:499,y)},x=()=>{S(),m.destroy(),h.destroy()};d.add(x),h.once("finish",S),h.once("close",S),h.once("error",S),m.once("aborted",S),m.once("error",S),m.socket.once("close",S),(async()=>{if(an(b)){let G=new Headers;for(let P=0;P<m.rawHeaders.length;P+=2)G.append(m.rawHeaders[P],m.rawHeaders[P+1]);let C=await i({path:m.url,method:m.method,headers:G,signal:F.signal,readBody:()=>Si(m,cr)});if(z)return;h.writeHead(C.status,Object.fromEntries(C.headers)),h.end(await C.text());return}let A=Ai(b,k,Boolean(m.url?.includes("?")),m.rawHeaders);if(A.status===200){h.writeHead(200,{"Content-Type":"application/json"}),h.end('{"status":"ok"}');return}if(A.status){if(A.status===405)h.setHeader("Allow","POST");cn(h,A.status,A.message);return}let{body:M,status:D}=await Si(m);if(z)return;if(D){cn(h,D,Oi(D));return}v=setTimeout(()=>{cn(h,504,"工具调用超时"),S()},Math.max(60000,r.timeout)),v.unref(),w=ct(a(A.token),e);let _=new Bc({sessionIdGenerator:void 0});if(await w.connect(_),z){await w.close();return}await _.handleRequest(m,h,M)})().catch(()=>{cn(h,500,"MCP 请求处理失败"),S()})});f.on("connection",(m)=>{l.add(m),m.once("close",()=>l.delete(m))}),f.on("clientError",(m,h)=>h.destroy()),await new Promise((m,h)=>{f.once("error",h),f.listen(e.port??9090,e.host??"127.0.0.1",()=>{f.off("error",h),m()})}).catch((m)=>{throw new c("E5004",{reason:typeof m?.code==="string"?m.code:"监听失败"})});let p,g=f.address();return{url:new URL(`http://${g.family==="IPv6"?`[${g.address}]`:g.address}:${g.port}/mcp`),close(){return p??=new Promise((m)=>{let h=setTimeout(()=>{for(let y of d)y();for(let y of l)y.destroy()},Ei);h.unref(),f.close(()=>{clearTimeout(h),m()}),f.closeIdleConnections?.()})}}}async function Wc(e,t,n,o){let r=new Set,i,s=!1;try{i=Bun.serve({hostname:e.host??"127.0.0.1",port:e.port??9090,idleTimeout:dn/1000,maxRequestBodySize:dr,async fetch(d){if(s)return Response.json({error:"MCP 服务正在关闭"},{status:503,headers:{Connection:"close"}});let l=Date.now(),f=new URL(d.url),p=f.pathname,g=d.method,m,h,y,b=!1,k=499,w=new AbortController,v=()=>{if(b)return;b=!0,w.abort(),clearTimeout(h),r.delete(z),d.signal.removeEventListener("abort",z),m?.close().catch(()=>{}),y?.cancel().catch(()=>{}),Pi(g,p,k,l)},z=()=>{k=499,v()};r.add(z),d.signal.addEventListener("abort",z,{once:!0});let F=(x,A,M)=>(k=x,v(),Response.json({error:A},{status:x,headers:{...d.method==="POST"?{Connection:"close"}:{},...M}}));async function S(x){y=d.body?.getReader();let A=[],M=0,D=!1;h=setTimeout(()=>{D=!0,y?.cancel().catch(()=>{})},dn),h.unref();try{if(y)while(!0){let _=await y.read();if(_.done)break;if(M+=_.value.byteLength,M>x)return{status:413};A.push(_.value)}if(D)return{status:408};if(b||d.signal.aborted)return{status:400};i.timeout(d,0);try{return{body:JSON.parse(Buffer.concat(A).toString("utf8"))}}catch{return{status:400}}}finally{clearTimeout(h)}}try{if(an(p)){let C=await o({path:f.pathname+f.search,method:g,headers:d.headers,signal:w.signal,readBody:()=>S(cr).catch(()=>({status:400}))});return k=C.status,v(),C}let x=Ai(p,g,d.url.includes("?"),Array.from(d.headers).flat());if(x.status===200)return k=200,v(),Response.json({status:"ok"});if(x.status)return F(x.status,x.message,x.status===405?{Allow:"POST"}:void 0);let{body:A,status:M}=await S(dr);if(M)return F(M,M===400&&(b||d.signal.aborted)?"请求已取消":Oi(M));y=void 0,m=ct(n(x.token),e);let D=new Zc({sessionIdGenerator:void 0});if(await m.connect(D),b)return await m.close(),F(400,"请求已取消");h=setTimeout(()=>{k=504,v()},Math.max(60000,t)),h.unref();let _=await D.handleRequest(d,{parsedBody:A});if(k=_.status,!_.body)return v(),_;y=_.body.getReader();let G=new ReadableStream({async pull(C){try{let P=await y.read();if(P.done)C.close(),v();else C.enqueue(P.value)}catch{C.error(Error("MCP response closed")),v()}},cancel(){k=499,v()}});return new Response(G,{status:_.status,headers:_.headers})}catch{return F(500,"MCP 请求处理失败")}},error(){return Response.json({error:"MCP 请求处理失败"},{status:500})}})}catch(d){let l=d?.code;throw new c("E5004",{reason:l??"监听失败"})}let a;return{url:new URL("/mcp",i.url),close(){return a??=(async()=>{s=!0;let d=setTimeout(()=>{for(let l of r)l();i.stop(!0)},Ei);d.unref();try{await i.stop(!1),await i.stop(!0)}finally{clearTimeout(d)}})()}}}var dr=1048576,dn=30000,Ei=5000;var Mi=E(()=>{L();le();be();mt();T();sr();or();Ci()});xe();L();Te();import{CommanderError as fr}from"commander";mt();import{Command as ed,Option as Ui}from"commander";xe();Te();function Ir(e,t){let n=e.map((i)=>i&&typeof i==="object"&&!Array.isArray(i)?i:{value:i});return{keys:t??[...new Set(n.flatMap(Object.keys))],rows:n,get:t?Rr:(i,s)=>i[s]}}function es(e,t){if(e.length===0)return"0 条";let{keys:n,rows:o,get:r}=Ir(e,t);if(n.length===0)return"";let i=`| ${n.join(" | ")} |`,s=`| ${n.map(()=>"---").join(" | ")} |`,a=o.map((d)=>`| ${n.map((l)=>Mr(r(d,l))).join(" | ")} |`).join(`
|
|
556
556
|
`);return`${i}
|
|
557
557
|
${s}
|
|
558
|
-
${a}`}function
|
|
558
|
+
${a}`}function Or(e,t){return(t??Object.keys(e)).map((o)=>{let r=t?Rr(e,o):e[o];return`* ${o}: ${Mr(r)}`}).join(`
|
|
559
559
|
`)}function gt(e,t=!0){return JSON.stringify(e,null,t?4:0)}function ts(e,t){if(!e)return"";if(!t&&!e.recTotal)return"没有数据";return`
|
|
560
560
|
|
|
561
|
-
已显示 ${t} 项,共 ${e.recTotal} 项,当前第 ${e.pageID} 页,每页 ${e.recPerPage} 条`}function Xe(e,t){if(t.format==="raw")return gt(t.rawResponse??e);if(t.format==="json"){let n=t.meta??(t.isList?{returned:Array.isArray(e)?e.length:0,total:t.pager?.recTotal??null,page:t.pager?.pageID??null,pageSize:t.pager?.recPerPage??null,hasMore:t.pager?t.pager.pageID*t.pager.recPerPage<t.pager.recTotal:null}:{});return gt({ok:!0,data:e??null,meta:n},t.jsonPretty??!1)}if(t.isList&&Array.isArray(e)){let n=t.format==="table"?
|
|
562
|
-
结果已由 --max-items 截断`:"")}if(!t.isList&&e&&typeof e==="object"&&!Array.isArray(e))
|
|
561
|
+
已显示 ${t} 项,共 ${e.recTotal} 项,当前第 ${e.pageID} 页,每页 ${e.recPerPage} 条`}function Xe(e,t){if(t.format==="raw")return gt(t.rawResponse??e);if(t.format==="json"){let n=t.meta??(t.isList?{returned:Array.isArray(e)?e.length:0,total:t.pager?.recTotal??null,page:t.pager?.pageID??null,pageSize:t.pager?.recPerPage??null,hasMore:t.pager?t.pager.pageID*t.pager.recPerPage<t.pager.recTotal:null}:{});return gt({ok:!0,data:e??null,meta:n},t.jsonPretty??!1)}if(t.isList&&Array.isArray(e)){let n=t.format==="table"?rs(e,t.fields):es(e,t.fields),o=ts(t.pager,e.length);return n+o+(t.meta?.truncated?`
|
|
562
|
+
结果已由 --max-items 截断`:"")}if(!t.isList&&e&&typeof e==="object"&&!Array.isArray(e)){let n=e;if(!t.fields&&Array.isArray(n.actions)){let{actions:o,...r}=n,i=Or(r,t.fields),s=ns(o);return s?`${i}
|
|
563
|
+
|
|
564
|
+
${s}`:i}return Or(n,t.fields)}return gt(e)}function ns(e){let t=e.map((n)=>{if(!n||typeof n!=="object"||Array.isArray(n))return"";let o=n,r=[o.date,o.actor,o.action].filter((d)=>typeof d==="string"&&d).join(" ");if(!r)return"";let i=typeof o.comment==="string"?o.comment.trim():"",s=Array.isArray(o.history)?o.history.map((d)=>{if(!d||typeof d!=="object")return"";let{field:l,old:f,new:p}=d;if(typeof l!=="string"||!l)return"";let g=(y)=>{let b=y===null||y===void 0||y===""?"":String(y);return b.length>80?`${b.slice(0,80)}…`:b},m=g(f),h=g(p);return m||h?`${l}: ${m||"空"} -> ${h||"空"}`:""}).filter(Boolean).join("; "):"",a=i?`${r}: ${i.replace(/\r?\n/g,`
|
|
565
|
+
`)}`:r;return s?`- ${a}
|
|
566
|
+
- 变更: ${s}`:`- ${a}`}).filter(Boolean);if(t.length===0)return"";return`## 备注(操作与评论历史)
|
|
567
|
+
${t.join(`
|
|
568
|
+
`)}`}function Mr(e){if(e===null||e===void 0)return"";return(typeof e==="object"?JSON.stringify(e):String(e)).replace(/\r?\n/g,"<br>").replace(/\|/g,"\\|")}function Rr(e,t){let n=t.split("."),o=e;for(let r of n){if(o===null||o===void 0||typeof o!=="object")return;o=o[r]}return o}function rs(e,t){if(!e.length)return"0 条";let{keys:n,rows:o,get:r}=Ir(e,t),i=(p)=>p.charCodeAt(0)>255?2:1,s=(p)=>[...p].reduce((g,m)=>g+i(m),0),a=n.map(s),d=!1,l=(p,g)=>{let m=(typeof p==="object"&&p!==null?JSON.stringify(p):String(p??"")).replace(/\s+/g," "),h=0,y="";for(let b of m){if(h+i(b)>36){d=!0,y+="…",h+=i("…");break}h+=i(b),y+=b}return a[g]=Math.max(a[g],h),y};return[n,...o.map((p)=>n.map((g,m)=>l(r(p,g),m)))].map((p)=>p.map((g,m)=>g+" ".repeat(a[m]-s(g))).join(" ").trimEnd()).join(`
|
|
563
569
|
`)+(d?`
|
|
564
|
-
… 表示终端省略内容;使用 --format=json 查看完整值`:"")}T();function
|
|
565
|
-
`)}if(!s)throw Error("Password or Token is required");let a=o.replace(/\/+$/,"");try{new URL(a)}catch{throw Error(`Invalid URL: ${a}`)}return{url:a,account:r,password:i==="password"?s:"",token:i==="token"?s:""}}finally{n.close()}}
|
|
570
|
+
… 表示终端省略内容;使用 --format=json 查看完整值`:"")}T();function O(e,t={},n={}){if(t.format==="raw")throw new c("E2009",{option:"raw",reason:"raw 仅适用于具有原始服务端响应的业务命令"});console.log(Xe(e,{format:t.format??"table",isList:Array.isArray(e),meta:n}))}T();function os(e){return{name:e.name(),description:e.description(),arguments:e.registeredArguments.map((t)=>({name:t.name(),required:t.required,variadic:t.variadic,description:t.description})),options:e.options.map((t)=>({flags:t.flags,description:t.description,default:t.defaultValue,choices:t.argChoices})),commands:e.commands.map((t)=>({name:t.name(),description:t.description()}))}}function Lr(e){e.command("help").description("离线文本或 JSON 命令定义").argument("[command]").argument("[action]").action((t,n,o,r)=>{let i=r.optsWithGlobals(),s=t?e.commands.find((f)=>f.name()===t):e,a=n?s?.commands.find((f)=>f.name()===n):s;if(!a)throw new c("E2009",{option:"help",reason:"未找到指定命令或操作"});if(i.format!=="json"){a.outputHelp();return}let d=t?me(t):void 0,l=d?.actions.find((f)=>Ie(f.name)===n);O(l?Me(d,l):os(a),i)})}ot();rt();le();T();async function Vr(e,t){let n=new URL("api.php/v1/user",`${e.siteUrl.replace(/\/+$/,"")}/`).href;try{let o=await e.fetch(n,{},t);return typeof o?.profile?.account==="string"?o.profile.account:void 0}catch(o){throw N(o)}}async function Jr(e,t){if(await Vr(e,t.token)!==t.account)throw new c("E1004")}async function Kr(e,t){let n=te(U(e.server,e.token,t),t.signal),o;try{if((await n.post("/users/logout",{}))?.status!=="success")throw new c("E1012")}catch(r){o=N(r)}try{await Vr(n,e.token)}catch(r){if(r instanceof c&&r.code==="1004")return;throw o??r}throw o??new c("E1012")}X();function Yr(e){e.command("status").description("显示认证来源;默认离线").option("--verify","连接服务器验证凭据").action(async(t,n)=>{let o=n.optsWithGlobals(),r=Se(o.profile);if(o.verify){let i=await ue(o,r);await Jr(i.client,i.profile)}O({source:r.source,server:r.server,account:r.account,credentialType:nt(r,o.preferPassword).type,configFile:r.source==="profile"?Dt():null,verified:Boolean(o.verify)},o)})}L();rt();import{readFileSync as _s}from"node:fs";L();re();import{createInterface as Os}from"node:readline/promises";import{Writable as Is}from"node:stream";async function Xr(){let e=!1,t=new Is({write(o,r,i){if(!e)process.stderr.write(o);i()}}),n=Os({input:process.stdin,output:t,terminal:process.stdin.isTTY});try{let o=await n.question(u("禅道服务地址 (URL): "),{signal:I()});if(!o)throw Error("URL is required");let r=await n.question("用户名 (Account): ",{signal:I()});if(!r)throw Error("Account is required");let i=(await n.question("认证方式 (password/token) [password]: ",{signal:I()})).trim().toLowerCase()||"password";if(i!=="password"&&i!=="token")throw Error("Auth method must be password or token");process.stderr.write(i==="token"?"Token: ":"密码 (Password): "),e=!0;let s;try{s=await n.question("",{signal:I()})}finally{e=!1,process.stderr.write(`
|
|
571
|
+
`)}if(!s)throw Error("Password or Token is required");let a=o.replace(/\/+$/,"");try{new URL(a)}catch{throw Error(`Invalid URL: ${a}`)}return{url:a,account:r,password:i==="password"?s:"",token:i==="token"?s:""}}finally{n.close()}}X();T();le();L();rt();import{randomBytes as no}from"node:crypto";import{createServer as js}from"node:http";import{spawn as Ms}from"node:child_process";function Qr(e=process.platform,t=process.env){if(t.SSH_CONNECTION||t.SSH_CLIENT||t.SSH_TTY||t.container||t.CI&&!/^(false|0)$/i.test(t.CI))return!1;if(e==="darwin")return!0;if(e==="win32")return t.SESSIONNAME?.toLowerCase()!=="services";return e==="linux"&&Boolean(t.DISPLAY||t.WAYLAND_DISPLAY)}async function eo(e){let t=process.platform==="darwin"?["open",e]:process.platform==="win32"?["rundll32.exe","url.dll,FileProtocolHandler",e]:process.platform==="linux"?["xdg-open",e]:void 0;if(!t)return!1;return new Promise((n)=>{let o,r=setTimeout(()=>n(!0),5000),i=(s)=>{clearTimeout(r),n(s)};try{o=Ms(t[0],t.slice(1),{stdio:"ignore",windowsHide:!0}),o.once("error",()=>i(!1)),o.once("exit",(s)=>i(s===0)),o.unref()}catch{i(!1)}})}L();Fe();L();var Rs={title:u("登录禅道"),intro:u("完成登录后,回到 ZenTao CLI 即可继续使用禅道。"),language:"语言",theme:"外观",system:"跟随系统",light:"浅色",dark:"深色",server:u("禅道地址"),serverHint:u("填写平时访问禅道的完整地址,保留 /zentao 等子目录。"),httpNotice:"此地址使用 HTTP,账号和密码将通过未加密的连接发送。请确认网络环境可信。",insecureNotice:u("当前已关闭 HTTPS 证书验证。请确认禅道地址属于你信任的服务器。"),account:"用户名",password:"密码",submit:"登录并保存",cancel:"取消",submitting:"正在登录…",cancelling:"正在取消…",privacy:"登录状态保存在本机。密码仅用于本次登录,不会保存到 CLI 配置。",noScript:u("请启用浏览器的 JavaScript,然后从 ZenTao CLI 重新发起登录。"),website:u("禅道官网"),websiteLabel:u("禅道官网(在新标签页打开)"),githubLabel:"GitHub 项目(在新标签页打开)",successTitle:"登录成功",successMessage:u("已登录账号 {account}({server})。登录状态已保存,可以返回 ZenTao CLI 继续操作。"),cancelTitle:"已取消登录",cancelMessage:u("本次登录已取消。需要使用禅道时,可从 ZenTao CLI 重新发起登录。"),finishedIntro:u("你可以关闭此页面,回到 ZenTao CLI 继续操作。"),connectionFailed:u("无法连接登录服务,页面可能已过期。请回到 ZenTao CLI 重新发起登录。"),cancelFailed:u("无法连接登录服务,页面可能已过期。请关闭此页面,回到 ZenTao CLI 查看登录状态。"),requestFailed:"请求处理失败,请重试。",localOnly:"仅允许本机登录请求。",expired:u("此登录页面已失效,请回到 ZenTao CLI 重新发起登录。"),notFound:"页面不存在。",invalidSession:u("登录页面已失效或请求来源不正确,请回到 ZenTao CLI 重新发起登录。"),invalidRequest:"请通过登录页面提交信息。",busy:"正在登录,请稍候。",tooLarge:"登录信息过长,请检查输入。",invalidJson:"登录信息格式不正确。",required:u("请填写禅道地址、用户名和密码。"),invalidUrl:u("请填写完整的禅道地址,例如 https://zentao.example.com。"),unsafeUrl:"请填写 HTTP 或 HTTPS 站点根地址,不要包含账号、密码、查询参数或锚点。",invalidCredentials:"用户名或密码不正确,请检查后重试。",unreachable:u("无法连接禅道,请检查地址和网络连接。"),timeout:u("连接禅道超时,请检查网络后重试。"),certificate:u("禅道的 HTTPS 证书验证失败,请联系管理员检查证书。"),invalidService:u("无法识别禅道服务,请填写禅道站点根地址。"),loginFailed:u("登录或保存失败,请检查禅道地址、账号及本地配置文件权限后重试。")},Ls={title:u("登入禪道"),intro:u("完成登入後,回到 ZenTao CLI 即可繼續使用禪道。"),language:"語言",theme:"外觀",system:"跟隨系統",light:"淺色",dark:"深色",server:u("禪道網址"),serverHint:u("填寫平時存取禪道的完整網址,保留 /zentao 等子目錄。"),httpNotice:"此網址使用 HTTP,帳號和密碼將透過未加密的連線傳送。請確認網路環境可信。",insecureNotice:u("目前已關閉 HTTPS 憑證驗證。請確認禪道網址屬於你信任的伺服器。"),account:"使用者名稱",password:"密碼",submit:"登入並儲存",cancel:"取消",submitting:"正在登入…",cancelling:"正在取消…",privacy:"登入狀態儲存在本機。密碼僅用於本次登入,不會儲存到 CLI 設定。",noScript:u("請啟用瀏覽器的 JavaScript,然後從 ZenTao CLI 重新發起登入。"),website:u("禪道官網"),websiteLabel:u("禪道官網(在新分頁開啟)"),githubLabel:"GitHub 專案(在新分頁開啟)",successTitle:"登入成功",successMessage:u("已登入帳號 {account}({server})。登入狀態已儲存,可以返回 ZenTao CLI 繼續操作。"),cancelTitle:"已取消登入",cancelMessage:u("本次登入已取消。需要使用禪道時,可從 ZenTao CLI 重新發起登入。"),finishedIntro:u("你可以關閉此頁面,回到 ZenTao CLI 繼續操作。"),connectionFailed:u("無法連線至登入服務,頁面可能已過期。請回到 ZenTao CLI 重新發起登入。"),cancelFailed:u("無法連線至登入服務,頁面可能已過期。請關閉此頁面,回到 ZenTao CLI 查看登入狀態。"),requestFailed:"請求處理失敗,請重試。",localOnly:"僅允許本機登入請求。",expired:u("此登入頁面已失效,請回到 ZenTao CLI 重新發起登入。"),notFound:"頁面不存在。",invalidSession:u("登入頁面已失效或請求來源不正確,請回到 ZenTao CLI 重新發起登入。"),invalidRequest:"請透過登入頁面提交資訊。",busy:"正在登入,請稍候。",tooLarge:"登入資訊過長,請檢查輸入內容。",invalidJson:"登入資訊格式不正確。",required:u("請填寫禪道網址、使用者名稱和密碼。"),invalidUrl:u("請填寫完整的禪道網址,例如 https://zentao.example.com。"),unsafeUrl:"請填寫 HTTP 或 HTTPS 網站根網址,不要包含帳號、密碼、查詢參數或錨點。",invalidCredentials:"使用者名稱或密碼不正確,請檢查後重試。",unreachable:u("無法連線至禪道,請檢查網址和網路連線。"),timeout:u("連線至禪道逾時,請檢查網路後重試。"),certificate:u("禪道的 HTTPS 憑證驗證失敗,請聯絡管理員檢查憑證。"),invalidService:u("無法識別禪道服務,請填寫禪道網站根網址。"),loginFailed:u("登入或儲存失敗,請檢查禪道網址、帳號及本機設定檔權限後重試。")},$s={title:u("Log in to ZenTao"),intro:u("After logging in, return to ZenTao CLI to continue using ZenTao."),language:"Language",theme:"Appearance",system:"System",light:"Light",dark:"Dark",server:u("ZenTao URL"),serverHint:u("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:u("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:u("Enable JavaScript in your browser, then start login again from ZenTao CLI."),website:u("ZenTao website"),websiteLabel:u("ZenTao website (opens in a new tab)"),githubLabel:"GitHub project (opens in a new tab)",successTitle:"Login successful",successMessage:u("Logged in as {account} ({server}). Your login has been saved. Return to ZenTao CLI to continue."),cancelTitle:"Login cancelled",cancelMessage:u("This login was cancelled. You can start login again from ZenTao CLI when you need to use ZenTao."),finishedIntro:u("You can close this page and return to ZenTao CLI to continue."),connectionFailed:u("Could not connect to the login service. This page may have expired. Return to ZenTao CLI and start login again."),cancelFailed:u("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:u("This login page has expired. Return to ZenTao CLI and start login again."),notFound:"Page not found.",invalidSession:u("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:u("Enter the ZenTao URL, username, and password."),invalidUrl:u("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:u("Could not connect to ZenTao. Check the URL and your network connection."),timeout:u("The connection to ZenTao timed out. Check your network and try again."),certificate:u("ZenTao HTTPS certificate verification failed. Ask your administrator to check the certificate."),invalidService:u("Could not recognize the ZenTao service. Enter the ZenTao site root URL."),loginFailed:u("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.")},Ft={"zh-CN":Rs,"zh-TW":Ls,en:$s};function to(e){let t=(r)=>r.replace(/[&<>"']/g,(i)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[i]),n=(r)=>t(Ft["zh-CN"][r]),o=`
|
|
566
572
|
color-scheme: dark;
|
|
567
573
|
--page-start: #142746; --page-end: #0c1629; --surface: #1a2639;
|
|
568
574
|
--ink: #eef3fc; --muted: #acb9cf; --accent: #80afff; --button: #2f6dd4; --button-hover: #245fc5;
|
|
569
575
|
--border: #52617a; --input: #152135; --footer: #162133; --brand: #a6c8ff;
|
|
570
576
|
--error: #ffb4b4; --error-bg: #432931; --notice: #f3d392; --notice-bg: #3a3223;
|
|
571
577
|
--success: #9ddbbb; --success-bg: #193c32;
|
|
572
|
-
`;return
|
|
578
|
+
`;return u`<!doctype html>
|
|
573
579
|
<html lang="zh-CN">
|
|
574
580
|
<head>
|
|
575
581
|
<meta charset="utf-8">
|
|
@@ -689,7 +695,7 @@ ${a}`}function es(e,t){return(t??Object.keys(e)).map((o)=>{let r=t?Ir(e,o):e[o];
|
|
|
689
695
|
<header class="page-header">
|
|
690
696
|
<div class="brand">
|
|
691
697
|
<!-- Original Pixel Tao geometry from site/public/brand/pixel-tao-terminal-blue-flat.svg. -->
|
|
692
|
-
${
|
|
698
|
+
${Ot('<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
699
|
<span class="brand-name">ZenTao CLI</span>
|
|
694
700
|
</div>
|
|
695
701
|
<div class="preferences">
|
|
@@ -707,7 +713,7 @@ ${a}`}function es(e,t){return(t??Object.keys(e)).map((o)=>{let r=t?Ir(e,o):e[o];
|
|
|
707
713
|
</header>
|
|
708
714
|
<section class="content" aria-labelledby="title">
|
|
709
715
|
<h1 id="title">${n("title")}</h1>
|
|
710
|
-
<p class="intro" id="intro">${t(e.message??
|
|
716
|
+
<p class="intro" id="intro">${t(e.message??Ft["zh-CN"].intro)}</p>
|
|
711
717
|
${e.insecure?`<p class="notice insecure" data-i18n="insecureNotice">${n("insecureNotice")}</p>`:""}
|
|
712
718
|
<form id="login-form" method="post" action="/login">
|
|
713
719
|
<fieldset id="fields" disabled>
|
|
@@ -737,14 +743,14 @@ ${a}`}function es(e,t){return(t??Object.keys(e)).map((o)=>{let r=t?Ir(e,o):e[o];
|
|
|
737
743
|
</section>
|
|
738
744
|
</main>
|
|
739
745
|
<footer>
|
|
740
|
-
<span>ZenTao CLI v${t(
|
|
746
|
+
<span>ZenTao CLI v${t(de())}</span>
|
|
741
747
|
<a href="https://www.zentao.net/" target="_blank" rel="noopener noreferrer" data-i18n="website" data-i18n-label="websiteLabel" aria-label="${n("websiteLabel")}">${n("website")}</a>
|
|
742
748
|
${!ke||ke.repository?` <a href="${ke?.repository??"https://github.com/easysoft/zentao-cli"}" target="_blank" rel="noopener noreferrer" data-i18n-label="githubLabel" aria-label="${n("githubLabel")}">GitHub</a>`:""}
|
|
743
749
|
</footer>
|
|
744
750
|
</div>
|
|
745
751
|
<script nonce="${t(e.nonce)}">
|
|
746
752
|
(() => {
|
|
747
|
-
const messages = ${JSON.stringify(
|
|
753
|
+
const messages = ${JSON.stringify(Ft).replace(/</g,"\\u003c")};
|
|
748
754
|
let sessionKey = location.hash.slice(1);
|
|
749
755
|
history.replaceState(null, '', location.pathname);
|
|
750
756
|
const form = document.getElementById('login-form');
|
|
@@ -884,69 +890,70 @@ ${!ke||ke.repository?` <a href="${ke?.repository??"https://github.com/easys
|
|
|
884
890
|
})();
|
|
885
891
|
</script>
|
|
886
892
|
</body>
|
|
887
|
-
</html>`}
|
|
893
|
+
</html>`}X();T();function Ds(e){switch(e instanceof c?e.code:""){case"1003":case"1004":return{errorCode:"invalidCredentials",error:"用户名或密码不正确,请检查后重试。"};case"1002":return{errorCode:"unreachable",error:u("无法连接禅道,请检查地址和网络连接。")};case"5001":return{errorCode:"timeout",error:u("连接禅道超时,请检查网络后重试。")};case"5002":return{errorCode:"certificate",error:u("禅道的 HTTPS 证书验证失败,请联系管理员检查证书。")};case"2011":case"2012":return{errorCode:"invalidService",error:u("无法识别禅道服务,请填写禅道站点根地址。")};default:return{errorCode:"loginFailed",error:u("登录或保存失败,请检查禅道地址、账号及本地配置文件权限后重试。")}}}async function Ns(e={}){let t=no(32).toString("hex"),n=no(18).toString("base64"),o=new AbortController,r=new Set,i="",s=!1,a=!1,d,l,f,p=new Promise((w,v)=>{l=w,f=v});p.catch(()=>{});let g=js({requestTimeout:30000,headersTimeout:1e4},(w,v)=>{v.setHeader("Cache-Control","no-store"),v.setHeader("Referrer-Policy","no-referrer"),v.setHeader("X-Content-Type-Options","nosniff"),v.setHeader("Connection","close"),v.setHeader("Content-Security-Policy",`default-src 'none'; script-src 'nonce-${n}'; style-src 'nonce-${n}'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`),b(w,v).catch(()=>{if(!v.headersSent)y(v,500,{errorCode:"requestFailed",error:"请求处理失败,请重试。"});else v.destroy()})});g.on("connection",(w)=>{r.add(w),w.once("close",()=>r.delete(w))});function m(w,v){if(s)return;if(s=!0,clearTimeout(d),e.signal?.removeEventListener("abort",h),o.abort(),process.removeListener("SIGINT",h),process.removeListener("SIGTERM",h),g.close(),setTimeout(()=>{for(let F of r)F.destroy()},250).unref(),w)f(w);else l(v)}function h(){m(new c("E1008"))}function y(w,v,z){w.writeHead(v,{"Content-Type":"application/json; charset=utf-8"}),w.end(JSON.stringify(z))}async function b(w,v){if(w.headers.host!==new URL(i).host){y(v,403,{errorCode:"localOnly",error:"仅允许本机登录请求。"});return}if(s){y(v,410,{errorCode:"expired",error:"登录页面已失效,请重新发起登录。"});return}if(w.method==="GET"&&w.url==="/"){v.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),v.end(to({nonce:n,server:e.server,account:e.account,message:e.message,insecure:e.insecure}));return}if(w.method!=="POST"||!["/login","/cancel"].includes(w.url??"")){y(v,404,{errorCode:"notFound",error:"页面不存在。"});return}if(w.headers.origin!==i||w.headers[u("x-zentao-login")]!==t){y(v,403,{errorCode:"invalidSession",error:"登录页面已失效或请求来源不正确,请重新发起登录。"});return}if(w.url==="/cancel"){v.once("finish",h),v.once("close",h),y(v,200,{ok:!0});return}if(w.headers["content-type"]?.split(";")[0].trim().toLowerCase()!=="application/json"){y(v,415,{errorCode:"invalidRequest",error:"请通过登录页面提交信息。"});return}if(a){y(v,409,{errorCode:"busy",error:"正在登录,请稍候。"});return}a=!0;try{let z=[],F=0;for await(let G of w){if(F+=G.length,F>16384){y(v,413,{errorCode:"tooLarge",error:"登录信息过长,请检查输入。"});return}z.push(Buffer.from(G))}let S;try{S=JSON.parse(Buffer.concat(z).toString("utf8"))}catch{y(v,400,{errorCode:"invalidJson",error:"登录信息格式不正确。"});return}if(!S||typeof S.server!=="string"||typeof S.account!=="string"||typeof S.password!=="string"||!S.server.trim()||!S.account.trim()||!S.password){y(v,400,{errorCode:"required",error:u("请填写禅道地址、用户名和密码。")});return}let x;try{x=new URL(S.server.trim())}catch{y(v,400,{errorCode:"invalidUrl",error:u("请填写完整的禅道地址,例如 https://zentao.example.com。")});return}if(!["http:","https:"].includes(x.protocol)||x.username||x.password||x.search||x.hash){y(v,400,{errorCode:"unsafeUrl",error:"请填写 HTTP 或 HTTPS 站点根地址,不要包含账号、密码、查询参数或锚点。"});return}let A=J(x.toString()),M=S.account.trim(),D=await Ue(A,M,S.password,{...e,signal:o.signal});if(s)return;let _=Ce(A,M,D.token,D.serverConfig,D.user);tt(_),y(v,200,{ok:!0,account:M,server:A}),m(void 0,et(M,A))}catch(z){if(!s)y(v,400,Ds(z))}finally{a=!1}}try{await new Promise((w,v)=>{g.once("error",v),g.listen(0,"127.0.0.1",()=>{g.removeListener("error",v),w()})})}catch{throw g.close(),new c("E1010")}if(i=`http://127.0.0.1:${g.address().port}`,g.on("error",()=>m(new c("E1010"))),process.once("SIGINT",h),process.once("SIGTERM",h),e.signal?.addEventListener("abort",h,{once:!0}),d=setTimeout(()=>m(new c("E1009")),e.waitTimeoutMs??300000),e.signal?.aborted)h();return{url:`${i}/#${t}`,result:p,cancel:h}}async function ro(e={}){let t=await Ns(e);if(process.stderr.write(`请在运行 CLI 的本机浏览器中完成登录(5 分钟内有效):
|
|
888
894
|
${t.url}
|
|
889
|
-
`),e.open!==!1&&!await
|
|
895
|
+
`),e.open!==!1&&!await eo(t.url)){if(e.fallbackToTerminal){t.cancel();try{return await t.result}catch(n){if(!(n instanceof c)||n.code!=="1008")throw n}process.stderr.write(`未能自动打开浏览器,已关闭临时页面,改用终端登录。
|
|
890
896
|
`);return}process.stderr.write(`未能自动打开浏览器,请手动打开上面的链接。
|
|
891
|
-
`)}return t.result}
|
|
897
|
+
`)}return t.result}re();be();async function Fs(){if(process.stdin.isTTY)throw new c("E2009",{option:"--password-stdin",reason:"需要通过管道提供密码,如 zentao login --server <url> --user <account> --password-stdin < pass.txt"});return _s(0,"utf8").replace(/\r?\n$/,"")}function Sn(e){e.command("login").description(u("登录禅道服务")).option("-s, --server <url>",u("禅道服务地址")).option("-u, --user <account>","用户名").option("-p, --password <password>","密码(会留在 shell 历史;优先交互输入或 --password-stdin)").option("--password-stdin","从标准输入读取密码,避免进入 shell 历史与进程列表").option("-t, --token <token>","Token").option("--use-env","强制使用环境变量登录").option("--web","通过本机浏览器页面登录").option("--no-open","仅输出浏览器登录链接,由调用方打开(需 --web)").option("--select","登录成功后将该账号设为当前配置",e.parent?void 0:!0).option("--message <text>","自定义浏览器登录页面的副标题提示语").option("--no-browser","使用终端交互登录,不打开浏览器").action(async(t)=>{let n=e.optsWithGlobals(),o=H(n.assistant);if(t.passwordStdin){if(t.password!==void 0)throw new c("E2009",{option:"--password-stdin",reason:"不能与 --password 同时使用"});if(t.web||t.useEnv)throw new c("E2009",{option:"--password-stdin",reason:"不能与 --web 或 --use-env 同时使用"});t.password=await Fs()}if(t.password!==void 0&&!t.passwordStdin&&n.format!=="json"&&!n.machineReadable&&n.input!==!1)process.stderr.write(`警告:命令行密码会留在 shell 历史,建议改用交互输入或 --password-stdin。
|
|
898
|
+
`);if(t.open===!1&&!t.web)throw new c("E2009",{option:"--no-open",reason:"必须与 --web 一起使用"});if(t.web&&(t.browser===!1||t.useEnv||t.password!==void 0||t.token!==void 0))throw new c("E2009",{option:"--web",reason:"不能与 --no-browser、--useEnv、--password 或 --token 同时使用"});if(n.input===!1&&(t.web||!t.useEnv&&!(t.server&&t.user&&(t.password||t.token))))throw new c("E2009",{option:"no-input",reason:"禁止交互时必须提供完整凭据或 --use-env"});let r=t.server&&t.user&&(t.password||t.token);if(!t.useEnv&&!r&&(t.password!==void 0||t.token!==void 0))throw new c("E1001");let i=Qr();if(t.web||!t.useEnv&&!r&&t.browser!==!1&&i){let m=await ro({actionAssistant:o,server:t.server,account:t.user,message:t.message,insecure:n.insecure,timeout:n.timeout,signal:I(),open:t.open!==!1&&i,fallbackToTerminal:!t.web&&Boolean(process.stdin.isTTY)});if(m){let h=q(m.account,m.server);if(t.select)wt(h);O({saved:h,selected:Boolean(t.select)},n);return}}let s;if(t.useEnv)s=He();else if(r)s={url:t.server,account:t.user,password:t.password,token:t.token};else{if(!process.stdin.isTTY)throw new c("E1006");s=await Xr()}let{url:a,account:d}=s;if(!a||!d)throw new c("E1001");let l=nt(s,n.preferPassword),f=J(a),p;if(l.type==="token"){let m=U(f,l.value,{actionAssistant:o,insecure:n.insecure,timeout:n.timeout}),{serverConfig:h,user:y}=await Gr(te(m,I()),d);p=Ce(f,d,l.value,h,y)}else{let m=await Ue(f,d,l.value,{actionAssistant:o,insecure:n.insecure,timeout:n.timeout,signal:I()});p=Ce(f,d,m.token,m.serverConfig,m.user)}tt(p);let g=q(d,f);if(t.select)wt(g);O({saved:g,selected:Boolean(t.select)},n)})}le();En();An();re();async function ao(e,t){let n=t.optsWithGlobals(),o=Bt(n),r=await Ht(o,e,()=>U(o.server,void 0,{timeout:n.timeout??o.timeout,insecure:n.insecure??o.insecure,actionAssistant:""}).getZentaoConfig({signal:I()}));if(typeof r==="string"&&n.format!=="json")console.log(r);else O(r,n)}function co(e){let t=e.command("link").description("生成或解析站内页面链接").option("--server <url>","指定站点地址,可省略登录凭据");t.action(()=>t.outputHelp()),t.command("create <module> <method>").description("生成页面链接").option("--var <name=value>","路由参数,可按页面参数顺序重复指定",(n,o=[])=>o.concat(n)).option("--relative","输出站内路径").action((n,o,r,i)=>ao({action:"create",module:n,method:o,vars:r.var,relative:r.relative},i)),t.command("parse <url>").description("解析页面链接").action((n,o,r)=>ao({action:"parse",url:n},r))}L();le();Pn();X();T();re();be();function lo(e){e.command("token").description("获取 Token(默认输出纯文本,不保存配置)").argument("[profileKey]","已登录的用户配置(account@server,省略时使用当前账号)").option("-s, --server <url>",u("临时获取 Token 的禅道服务地址")).option("-u, --user <account>","临时获取 Token 的用户名").option("-p, --password <password>","临时获取 Token 的密码").option("--silent","不输出 Token,错误仍写入 stderr").addHelpText("after",`
|
|
892
899
|
省略凭证时只读取本地 Token,不联网验证。
|
|
893
900
|
临时获取必须同时提供 --server、--user、--password,不能与 profileKey 混用。
|
|
894
|
-
使用 --format json 或 --format raw 可同时输出账号、地址和 Token。`).action(async(t,n)=>{let o=e.opts(),r=n.server!==void 0||n.user!==void 0||n.password!==void 0;if(r&&t!==void 0)throw new c("E2009",{option:"profileKey",reason:"不能与 --server、--user 或 --password 同时使用"});let i,s,a;if(r){if(!n.server||!n.user||!n.password)throw new c("E1001");try{a=await
|
|
901
|
+
使用 --format json 或 --format raw 可同时输出账号、地址和 Token。`).action(async(t,n)=>{let o=e.opts(),r=n.server!==void 0||n.user!==void 0||n.password!==void 0;if(r&&t!==void 0)throw new c("E2009",{option:"profileKey",reason:"不能与 --server、--user 或 --password 同时使用"});let i,s,a;if(r){if(!n.server||!n.user||!n.password)throw new c("E1001");try{a=await Zt(n.server,n.user,n.password,{actionAssistant:H(o.assistant),insecure:o.insecure,timeout:o.timeout,signal:I()}),i=U(n.server).siteUrl,s=n.user}catch(d){throw N(d)}}else{let d=t===void 0?we():K(t);if(!d)throw new c(t===void 0?"E1006":"E1007");if(!d.token.trim())throw new c("E1006");({server:i,account:s,token:a}=d)}if(n.silent)return;if(o.format==="json"||o.format==="raw")console.log(JSON.stringify({status:"success",server:i,account:s,token:a},null,4));else console.log(a)})}X();T();re();be();function On(e){e.command("logout").description("删除本地登录记录").argument("[key]").option("--all","清理选定配置文件中的全部账号;空配置也成功").option("--revoke","先撤销并验证远端会话;失败时保留该账号以便重试").action(async(t,n,o)=>{let r=o.optsWithGlobals();if(r.all&&(t||r.profile))throw new c("E2009",{option:"--all",reason:"不能同时指定账号或 --profile"});let i=t??r.profile,s=i?K(i):we();if(!r.all&&!s)throw new c("E1007");let a=r.all?Br():[s],d=[];for(let l of a){if(r.revoke){let p=Y(l);await Kr(l,{timeout:r.timeout??p.timeout,insecure:r.insecure??p.insecure,actionAssistant:H(r.assistant,p.autoAssistant),signal:I()})}let f=q(l.account,l.server);if(jt(f,l.token))d.push(f);else if(r.revoke&&K(f))throw new c("E1012")}O({removed:r.all?d:d[0]??null},r)})}X();T();function In(e,t){return{key:q(e.account,e.server),server:e.server,account:e.account,current:t?.server===e.server&&t.account===e.account}}function uo(e){let t=e.command("profile").description("管理已保存账号;use 才改变默认身份");t.action(()=>t.outputHelp()),t.command("list").description("列出已保存账号").action((n,o)=>{let r=Re(),i=we(r);O((r.profiles??[]).map((s)=>In(s,i)),o.optsWithGlobals())}),t.command("show").argument("[key]","完整 key 或唯一简写").description("查看账号,不验证凭据").action((n,o,r)=>{let i=r.optsWithGlobals(),s=n??i.profile,a=Re(),d=we(a),l=s?K(s,a):d;if(!l)throw new c("E1007");O({...In(l,d),verified:!1},i)}),t.command("use").argument("<key>").description("设置默认身份").action((n,o,r)=>{let i=wt(n);if(!i)throw new c("E1007");O(In(i,i),r.optsWithGlobals())}),t.command("remove").argument("<key>").description("删除本地账号记录").action((n,o,r)=>{let i=K(n);if(!i)throw new c("E1007");let s=q(i.account,i.server);jt(s),O({removed:s},r.optsWithGlobals())})}ot();X();mt();T();function Mn(e){if(!Object.hasOwn(ee,e))throw new c("E2004",{field:e,value:""});return e}function Bs(e,t){let n=()=>new c("E2004",{field:e,value:t}),o=t;if(e==="pagers"){try{o=JSON.parse(t)}catch{throw n()}if(o&&typeof o==="object"&&Object.hasOwn(o,"__proto__")&&!ft.shape.pagers.valueType.safeParse(Reflect.get(o,"__proto__")).success)throw n()}else if(typeof ee[e]==="number")o=Number(t);else if(typeof ee[e]==="boolean"){if(t==="true")o=!0;if(t==="false")o=!1}if(!ft.shape[e].safeParse(o).success)throw n();return o}function po(e){let t=e.command("config").description("查询配置来源并修改已保存账号的偏好");t.action(()=>t.outputHelp());let n=(o)=>{try{return Se(o.optsWithGlobals().profile).profile}catch(r){if(r instanceof c&&r.code==="1006")return;throw r}};t.command("path").description("显示配置文件路径").action((o,r)=>O({path:Dt()},r.optsWithGlobals())),t.command("list").description("列出有效配置及来源").action((o,r)=>{let i=n(r),s=i?Y(i):ee;O(Object.entries(ee).map(([a])=>({key:a,value:s[a],source:i?.config&&Object.hasOwn(i.config,a)?"profile":"default"})),r.optsWithGlobals())}),t.command("get").argument("<key>").description("查看一个配置项").action((o,r,i)=>{let s=Mn(o),a=n(i),d=a?Y(a):ee;O({key:s,value:d[s],source:a?.config&&Object.hasOwn(a.config,s)?"profile":"default"},i.optsWithGlobals())}),t.command("set").argument("<key>").argument("<value>").description("修改一个配置项").action((o,r,i,s)=>{let a=Mn(o),d=Bs(a,r),l=n(s);if(!l)throw new c("E1006");zn(l,a,d),O({key:a,value:d,source:"profile"},s.optsWithGlobals())}),t.command("unset").argument("<key>").description("恢复默认值").action((o,r,i)=>{let s=Mn(o),a=n(i);if(!a)throw new c("E1006");zn(a,s,void 0),O({key:s,value:ee[s],source:"default"},i.optsWithGlobals())})}Fe();import{realpathSync as qs}from"node:fs";var xt={name:"@baocang/zentao-cli",version:"0.5.1-enh.2",type:"module",description:"禅道命令行工具,支持在你喜爱的终端里访问和操作禅道数据,对 AI Agents 友好。",author:"Sun Hao <sunhao@chandao.com>",license:"MIT",repository:{type:"git",url:"git+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","markdown-it":"^14.3.0",parse5:"7.3.0","toml-eslint-parser":"^0.10.0",turndown:"^7.2.0","zentao-api":"0.9.4",zod:"^4.3.6"},devDependencies:{"@resvg/resvg-js":"2.6.2","@types/bun":"^1.3.13","@types/markdown-it":"^14.1.2","@types/turndown":"^5.0.5",typescript:"^5.7.0"},engines:{node:">=18"},publishConfig:{access:"public"}};function fo(e){e.command("version").description("离线显示 CLI、SDK 和运行时版本").action((t,n)=>{O({cli:de(),package:xt.name,path:qs(process.argv[1]??process.cwd()),sdk:xt.dependencies["zentao-api"],runtime:typeof Bun>"u"?`Node ${process.versions.node}`:`Bun ${Bun.version}`,platform:process.platform,arch:process.arch},n.optsWithGlobals())})}L();T();function Ws(e,t){let n=e,o=t.at(-1)??"",r,i=()=>{let s=[...n.options];for(let a=n.parent;a;a=a.parent)s.push(...a.options);return s};for(let s of t.slice(0,-1)){if(r){r=void 0;continue}if(s.startsWith("-")){let a=i().find((d)=>d.long===s.split("=")[0]||d.short===s);if(a?.required&&!s.includes("="))r=a;continue}n=n.commands.find((a)=>a.name()===s)??n}if(r)return(r.argChoices??[]).filter((s)=>s.startsWith(o));return[...new Set([...n.commands.filter((s)=>s.name()!=="candidates").map((s)=>s.name()),...i().flatMap((s)=>[s.long,s.short].filter(Boolean))])].filter((s)=>s.startsWith(o))}function Gs(e,t){if(e==="bash")return u`# bash completion for zentao (no bash-completion dependency)
|
|
895
902
|
_zentao_completion() {
|
|
896
903
|
COMPREPLY=()
|
|
897
904
|
local candidate
|
|
898
905
|
while IFS= read -r candidate; do COMPREPLY+=("$candidate"); done < <(zentao completion candidates -- "\${COMP_WORDS[@]:1:COMP_CWORD}")
|
|
899
906
|
}
|
|
900
907
|
complete -F _zentao_completion zentao
|
|
901
|
-
`;if(e==="zsh")return
|
|
908
|
+
`;if(e==="zsh")return u`#compdef zentao
|
|
902
909
|
_zentao() {
|
|
903
910
|
local -a candidates
|
|
904
911
|
candidates=("\${(@f)$(zentao completion candidates -- "\${words[@]:1:$((CURRENT-1))}")}")
|
|
905
912
|
compadd -- "\${candidates[@]}"
|
|
906
913
|
}
|
|
907
914
|
compdef _zentao zentao
|
|
908
|
-
`;if(e==="fish")return
|
|
915
|
+
`;if(e==="fish")return u`# fish completion for zentao
|
|
909
916
|
function __zentao_candidates
|
|
910
917
|
set -l words (commandline -opc)
|
|
911
918
|
zentao completion candidates -- $words[2..-1] (commandline -ct)
|
|
912
919
|
end
|
|
913
920
|
complete -c zentao -f -a '(__zentao_candidates)'
|
|
914
|
-
`;throw new c("E2009",{option:"shell",reason:"支持 bash、zsh、fish"})}function
|
|
921
|
+
`;throw new c("E2009",{option:"shell",reason:"支持 bash、zsh、fish"})}function mo(e){let t=e.command("completion").description("将补全脚本写入 stdout");t.action(()=>t.outputHelp());for(let n of["bash","zsh","fish"])t.command(n).action(()=>{process.stdout.write(Gs(n))});t.command("candidates",{hidden:!0}).argument("[words...]").allowUnknownOption(!0).action((n)=>{let o=Ws(e,n);if(o.length)process.stdout.write(o.join(`
|
|
915
922
|
`)+`
|
|
916
|
-
`)})}L();
|
|
923
|
+
`)})}L();re();T();import{cpSync as Vs,existsSync as Ln,mkdirSync as Js,statSync as go,writeFileSync as Ks}from"node:fs";import{homedir as ze}from"node:os";import{dirname as ho,isAbsolute as Ys,join as oe,relative as Xs,resolve as Rn,sep as Qs}from"node:path";import{fileURLToPath as ea}from"node:url";import{createInterface as ta}from"node:readline/promises";var yo=[u("zentao-cli"),u("zentao-tour")],qt={"claude-code":{label:"Claude Code",dir:oe(ze(),".claude","skills")},cursor:{label:"Cursor",dir:oe(ze(),".cursor","skills")},"cherry-studio":{label:"Cherry Studio",dir:oe(ze(),".cherrystudio","skills")},codex:{label:"Codex",dir:oe(ze(),".agents","skills")},opencode:{label:"OpenCode",dir:oe(ze(),".config","opencode","skills")},vscode:{label:"VS Code",dir:oe(ze(),".copilot","skills")},antigravity:{label:"Antigravity",dir:oe(ze(),".gemini","antigravity","skills")},gemini:{label:"Gemini",dir:oe(ze(),".gemini","skills")}},Be=Object.keys(qt);function bo(e){let t=ea(import.meta.url),n=ho(t),o=[oe(n,"..","..","skills",e),oe(n,"..","skills",e),oe(n,"..","..","..","skills",e)];for(let r of o)if(Ln(r))return{type:"directory",path:r};throw Error(`找不到技能源目录,已尝试路径:
|
|
917
924
|
${o.map((r)=>` - ${r}`).join(`
|
|
918
925
|
`)}
|
|
919
|
-
`+
|
|
926
|
+
`+u("请确认 zentao-cli 安装完整,或从源码目录运行。"))}async function na(){if(!process.stdin.isTTY||!process.stderr.isTTY)throw new c("E2009",{option:"agent",reason:`未指定 agent,请显式传入: ${Be.join("|")}|all`});let e=[...Be,"all"],t=[...Be.map((o)=>qt[o].label),"全部安装"],n=ta({input:process.stdin,output:process.stderr});process.stderr.write(`请选择要安装的 AI Agent:
|
|
920
927
|
`),t.forEach((o,r)=>{process.stderr.write(` ${r+1}) ${o}
|
|
921
|
-
`)});try{let o=await n.question(`请输入编号 (1-${e.length}): `,{signal:I()}),r=Number(o.trim());if(!Number.isInteger(r)||r<1||r>e.length)throw new c("E2009",{option:"agent",reason:`无效选择: ${o||"(empty)"}`});let i=e[r-1];return i==="all"?[...Be]:[i]}finally{n.close()}}function
|
|
922
|
-
可用选项: ${Be.join("、")}、all`})}function
|
|
923
|
-
`)}function
|
|
928
|
+
`)});try{let o=await n.question(`请输入编号 (1-${e.length}): `,{signal:I()}),r=Number(o.trim());if(!Number.isInteger(r)||r<1||r>e.length)throw new c("E2009",{option:"agent",reason:`无效选择: ${o||"(empty)"}`});let i=e[r-1];return i==="all"?[...Be]:[i]}finally{n.close()}}function ra(e){let t=e.toLowerCase();if(t==="all")return[...Be];if(qt[t])return[t];throw new c("E2009",{option:"agent",reason:`不支持的 agent: ${e}
|
|
929
|
+
可用选项: ${Be.join("、")}、all`})}function oa(e,t){let n=Xs(Rn(e),Rn(t)),o=".."+Qs;if(n===""||!Ys(n)&&n!==".."&&!n.startsWith(o))throw Error("技能目标路径不能是技能源目录或其子目录: "+t)}function wo(e,t){if(e.type==="directory")oa(e.path,t);if(Ln(t)&&!go(t).isDirectory())throw Error(`技能目标路径必须是目录: ${t}`)}function vo(e,t){if(wo(e,t),e.type==="directory"){Vs(e.path,t,{recursive:!0,dereference:!0});return}for(let[n,o]of Object.entries(e.files)){let r=oe(t,n);Js(ho(r),{recursive:!0}),Ks(r,Buffer.from(o,"base64"))}}function ia(e){let t=e.trim();if(!t)throw Error("导出路径不能为空");let n=t==="~"?ze():t.replace(/^~[\\/]/,`${ze()}/`),o=Rn(n);if(Ln(o)&&!go(o).isDirectory())throw Error(`导出路径必须是目录: ${o}`);return o}function sa(e,t){let n=qt[e],o=bo(t),r=oe(n.dir,t);return vo(o,r),{skill:t,agent:e,path:r}}function aa(e){let t=ia(e),n=yo.map((o)=>({skillName:o,source:bo(o),destDir:oe(t,o)}));for(let{source:o,destDir:r}of n)wo(o,r);for(let{source:o,destDir:r}of n)vo(o,r);return n.map(({skillName:o,destDir:r})=>({skill:o,path:r}))}function ko(e){e.command("install").description("安装技能到指定 Agent").argument("[agent]",Be.join("|")+"|all").action(async(t,n,o)=>{let r=o.optsWithGlobals();if(!t&&r.input===!1)throw new c("E2009",{option:"agent",reason:"--no-input 时必须指定安装目标"});let i=t?ra(t):await na();O(i.flatMap((s)=>yo.map((a)=>sa(s,a))),r)}),e.command("export").description("导出技能到指定目录").argument("<directory>").action((t,n,o)=>O(aa(t),o.optsWithGlobals()))}L();re();ot();T();import{chmodSync as xo,existsSync as $n,mkdirSync as ca,readFileSync as Co,renameSync as da,unlinkSync as la,writeFileSync as ua}from"node:fs";import{homedir as pa}from"node:os";import{dirname as fa,join as ie}from"node:path";import{createInterface as ma}from"node:readline/promises";import{parseTOML as zo}from"toml-eslint-parser";var it=u("zentao-cli"),fe=pa();function To(...e){switch(process.platform){case"darwin":return ie(fe,"Library","Application Support",...e);case"win32":return ie(process.env.APPDATA||ie(fe,"AppData","Roaming"),...e);default:return ie(fe,".config",...e)}}var zt={cursor:{label:"Cursor",configPath:ie(fe,".cursor","mcp.json"),format:"mcpServers"},"claude-desktop":{label:"Claude Desktop",configPath:To("Claude","claude_desktop_config.json"),format:"mcpServers"},"claude-code":{label:"Claude Code",configPath:ie(fe,".claude.json"),format:"mcpServers"},windsurf:{label:"Windsurf",configPath:ie(fe,".codeium","windsurf","mcp_config.json"),format:"mcpServers"},cline:{label:"Cline",configPath:ie(fe,".cline","data","settings","cline_mcp_settings.json"),format:"mcpServers"},trae:{label:"Trae",configPath:ie(fe,".trae","mcp.json"),format:"mcpServers"},vscode:{label:"VS Code",configPath:To("Code","User","mcp.json"),format:"vscode"},"cherry-studio":{label:"Cherry Studio",configPath:"",format:"cherry-studio"},opencode:{label:"OpenCode",configPath:ie(fe,".config","opencode","opencode.json"),format:"opencode"},codex:{label:"Codex",configPath:ie(fe,".codex","config.toml"),format:"codex"},antigravity:{label:"Antigravity",configPath:ie(fe,".gemini","antigravity","mcp_config.json"),format:"mcpServers"},gemini:{label:"Gemini",configPath:ie(fe,".gemini","mcp_config.json"),format:"mcpServers"}},Ze=Object.keys(zt);function jn(e){if(!$n(e))return{};let t=Co(e,"utf-8").trim();if(!t)return{};try{let n=JSON.parse(t);if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Config root must be an object");return n}catch{throw Error(`无法安全更新包含注释或无效 JSON 的配置文件,请手动配置: ${e}`)}}function Dn(e,t,n){let o=e;for(let r=0;r<t.length-1;r++){let i=t[r];if(!o[i]||typeof o[i]!=="object"||Array.isArray(o[i]))o[i]={};o=o[i]}o[t[t.length-1]]=n}function Nn(e,t){So(e,JSON.stringify(t,null,2)+`
|
|
930
|
+
`)}function So(e,t){ca(fa(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.tmp`;try{if(ua(n,t,{encoding:"utf-8",mode:384}),process.platform!=="win32")xo(n,384);if(da(n,e),process.platform!=="win32")xo(e,384)}catch(o){if($n(n))la(n);throw o}}async function ga(e){let{profile:t}=await ue(e);return{url:t.server,account:t.account,token:t.token}}async function ha(){if(!process.stdin.isTTY||!process.stderr.isTTY)throw new c("E2009",{option:"agent",reason:`未指定 agent,请显式传入: ${Ze.join("|")}|all`});let e=[...Ze,"all"],t=[...Ze.map((o)=>zt[o].label),"全部配置"],n=ma({input:process.stdin,output:process.stderr});process.stderr.write(`请选择要配置的 AI Agent:
|
|
924
931
|
`),t.forEach((o,r)=>{let i=String(r+1).padStart(2);process.stderr.write(` ${i}) ${o}
|
|
925
|
-
`)});try{let o=await n.question(`请输入编号 (1-${e.length}): `,{signal:I()}),r=Number(o.trim());if(!Number.isInteger(r)||r<1||r>e.length)throw new c("E2009",{option:"agent",reason:`无效选择: ${o||"(empty)"}`});let i=e[r-1];return i==="all"?[...Ze]:[i]}finally{n.close()}}function
|
|
926
|
-
可用选项: ${Ze.join("、")}、all`)}function
|
|
932
|
+
`)});try{let o=await n.question(`请输入编号 (1-${e.length}): `,{signal:I()}),r=Number(o.trim());if(!Number.isInteger(r)||r<1||r>e.length)throw new c("E2009",{option:"agent",reason:`无效选择: ${o||"(empty)"}`});let i=e[r-1];return i==="all"?[...Ze]:[i]}finally{n.close()}}function ya(e){let t=e.toLowerCase();if(t==="all")return[...Ze];if(zt[t])return[t];throw Error(`不支持的 agent: ${e}
|
|
933
|
+
可用选项: ${Ze.join("、")}、all`)}function Eo(e){return{command:u("zentao"),args:["mcp","serve"],env:{[u("ZENTAO_URL")]:e.url,[u("ZENTAO_ACCOUNT")]:e.account,[u("ZENTAO_TOKEN")]:e.token}}}function ba(e,t){let n=jn(e);Dn(n,["mcpServers",it],Eo(t)),Nn(e,n)}function wa(e,t){let n=jn(e);Dn(n,["servers",it],{type:"stdio",...Eo(t)}),Nn(e,n)}function va(e,t){let n=jn(e);Dn(n,["mcp",it],{type:"local",command:[u("zentao"),"mcp","serve"],environment:{[u("ZENTAO_URL")]:t.url,[u("ZENTAO_ACCOUNT")]:t.account,[u("ZENTAO_TOKEN")]:t.token},enabled:!0}),Nn(e,n)}function ka(e,t){let n=e.lastIndexOf(`
|
|
927
934
|
`,t.range[0]-1)+1,o=e.indexOf(`
|
|
928
|
-
`,t.range[1]);return[n,o<0?e.length:o+1]}function
|
|
929
|
-
`)?n:n+n;s=e+a+t}return
|
|
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}
|
|
935
|
+
`,t.range[1]);return[n,o<0?e.length:o+1]}function xa(e,t,n){let i=zo(e).body[0].body.filter((a)=>a.type==="TOMLTable"&&a.resolvedKey[0]==="mcp_servers"&&a.resolvedKey[1]===it).map((a)=>ka(e,a)),s=e;if(i.length>0)for(let a=i.length-1;a>=0;a--){let[d,l]=i[a];s=s.slice(0,d)+(a===0?t:"")+s.slice(l)}else{let a=!e||e.endsWith(n+n)?"":e.endsWith(`
|
|
936
|
+
`)?n:n+n;s=e+a+t}return zo(s),s}function za(e,t){try{let n=$n(e)?Co(e,"utf-8"):"",o=n.match(/\r?\n/)?.[0]??`
|
|
937
|
+
`,r=[`[mcp_servers.${it}]`,u('command = "zentao"'),'args = ["mcp", "serve"]',u`env = { ZENTAO_URL = ${JSON.stringify(t.url)}, ZENTAO_ACCOUNT = ${JSON.stringify(t.account)}, ZENTAO_TOKEN = ${JSON.stringify(t.token)} }`].join(o)+o;So(e,xa(n,r,o))}catch{throw new c("E1005",{path:e})}}function Ta(e,t){let n=zt[e];switch(n.format){case"mcpServers":ba(n.configPath,t);break;case"vscode":wa(n.configPath,t);break;case"opencode":va(n.configPath,t);break;case"codex":za(n.configPath,t);break;case"cherry-studio":return}}function _n(e,t="install"){e.command(t).description(u("配置禅道 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?ya(n):await ha(),i=await ga(o);for(let s of r)Ta(s,i);O(r.map((s)=>({agent:s,path:zt[s].configPath,...s==="cherry-studio"?{manual:{name:it,type:"stdio",command:u("zentao"),args:["mcp","serve"]}}:{}})),o)})}T();L();xe();Vt();Te();import{isDeepStrictEqual as Tc}from"node:util";import{Option as er}from"commander";T();import{isDeepStrictEqual as $a}from"node:util";re();T();import{readFile as Sa}from"node:fs/promises";var Jt;async function Ea(){if(Jt)return Jt;if(process.stdin.isTTY||process.stdin.listenerCount("data")>0)return;return Jt=(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)}})(),Jt}function Un(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 Po(e){if(e==="@-"){let t=await Ea();if(t)return Un(t);throw new c("E2007")}if(e.startsWith("@"))try{return Un(await Sa(e.slice(1),{encoding:"utf8",signal:I()}))}catch(t){if(t instanceof c)throw t;throw new c("E2009",{option:"data",reason:"无法读取 JSON 文件"})}return Un(e)}Bn();var Ma=(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 l=a(d.pos),f="";if(l>d.pos&&n[l]!==")"){let p=i.helpers.parseLinkTitle(n,l,r);if(!p.ok)return!1;f=p.str,l=a(p.pos)}if(l>=r||n[l]!==")")return!1;if(!t){let p=e.push("image","img",0);if(p.attrs=[["src",d.str],["alt",""]],f)p.attrSet("title",f);p.content=n.slice(o+2,s),p.children=[],i.inline.parse(p.content,i,e.env,p.children)}return e.pos=l+1,!0};async function Ra(){let{default:e}=await import("markdown-it"),t=new e({html:!1});return t.inline.ruler.before("image","zentao_file_image",Ma),(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 La;function Mo(){return La??=Ra()}Vt();Te();Ke();Wt();Ye();function W(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{W("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{}W("data","数组不是有效 JSON")}return[We(o,t.items??{type:"string"})]})}if(typeof e==="boolean")return e;if(Array.isArray(e))W("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)))W("data","需要有效数字");return Number(o)}if(t.type==="boolean"){if(e==="true")return!0;if(e==="false")return!1;W("data","布尔值只接受 true 或 false")}if(t.type==="object")try{return JSON.parse(e)}catch{W("data","需要 JSON 对象")}return e}async function ja(e,t,n,o){let r=o.data??{},i=e==="doc"&&(r.contentType??o.contentType)!=="html",s=n===!0?t:n.split(",").map((l)=>l.trim()),a=new Map;for(let l of s){if(!t.includes(l))W("markdown",`无效的字段名「${l}」,可选 HTML 字段为 ${t.join(", ")}`);if(i&&l==="content"){if(n===!0)continue;W("markdown","文档正文可直接传入 Markdown,转换为 HTML 需显式指定 --content-type html")}let f=r[l]??o[l];if(typeof f==="string")a.set(l,f);else if(n!==!0)W("markdown",`本次请求未提供字段 ${l}`)}if(!a.size)return;let d=await Mo();for(let[l,f]of a){let p=d(f);if(Object.hasOwn(o,l))o[l]=p;if(Object.hasOwn(r,l))r[l]=p}}async function Zn(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))W("raw","原始响应不能与本地处理或自动翻页组合");let s={},a=Me(e,t),d=a.parameters,l=(b,k)=>{if(k===void 0)return;if(Object.hasOwn(s,b)&&!$a(s[b],k))W(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");l(b,w?We(k,w,v):Number(k))}if(e.name==="file"&&t.name==="read"&&o.output!==void 0){if(!o.output.trim())W("output","请输入目标文件路径");if(o.ids!==void 0||o.batchFailFast||o.format==="raw"||s.stream===1)W("output","写入单个附件的原始字节时不能同时指定 --ids、--batch-fail-fast、--format=raw 或 --stream=1")}let f=a.target,p;if(n!==void 0){if(!f)W("target","此操作没有位置参数");if(ce(e.name,t.name)&&!Number.isFinite(Number(n))&&!(t.name==="get"&&Fn(n))){if(o.ids!==void 0)W("ids","--ids 与单个附件链接只能指定一个");p=n}else l(f,We(n,d.find((b)=>b.name===f),!0))}if(o.data!==void 0)s.data=await Po(o.data);let g=_e(e,t,d);if(g){if(o.page!==void 0)l(g.page.name,We(o.page,g.page));if(o.recPerPage!==void 0)l(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))W("all/page","--all 与 --page 不能同时使用");if(o.maxItems!==void 0&&(!/^\d+$/.test(o.maxItems)||!Number.isSafeInteger(Number(o.maxItems))||Number(o.maxItems)<1))W("max-items","必须为正安全整数");let m=Mt(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=Gt(e,t,{...h,url:p,params:m?{...s,[he(t)]:m[0]}:s},i);if(o.markdown!==void 0)await ja(e.name,a.markdownFields,o.markdown,y);if(m)delete y[he(t)];return y}ot();Ye();X();T();re();import{randomUUID as Da}from"node:crypto";import{open as Na,link as _a,rename as Fa,rm as Ro}from"node:fs/promises";import{dirname as Ua,join as Ha}from"node:path";import{getModuleAction as Ba}from"zentao-api";async function Kt(e,t,n,o,r){let i=r.signal??I(),{version:s}=await e.getZentaoConfig({timeout:r.timeout,insecure:r.insecure,signal:i});if(!Ba("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=Ha(Ua(o),`.zentao-download-${Da()}`),l=await Na(d,"wx",384).catch(a),f=!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,m=0;if(p.body)for await(let h of p.body)await l.writeFile(h).catch(a),m+=h.byteLength;if(await l.close().catch(a),i?.aborted)throw new c("E5003");if(r.noClobber)await _a(d,g).catch(a),f=!0,await Ro(d,{force:!0});else await Fa(d,g).catch(a),f=!0;return{path:g,bytes:m}}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(!f)try{await l.close()}finally{await Ro(d,{force:!0})}}}T();xe();import{basename as Xn,extname as hc,join as Yo}from"node:path";import{existsSync as ti,mkdirSync as yc,readFileSync as bc}from"node:fs";Jn();X();T();re();Ke();nn();import{createInterface as wc}from"node:readline/promises";async function Xo(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=wc({input:process.stdin,output:process.stderr});try{return(await o.question(`确认删除 ${t} 个对象?(y/n): `,{signal:I()})).toLowerCase()==="y"}finally{o.close()}}function ni(e,t){for(let n of e){let o=t===void 0?"附件警告":`对象 ${t} 附件警告`;console.error(`${o}:${JSON.stringify(n)}`)}}function ri(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 vc(e,t,n){let o=t.format??n.defaultOutputFormat??"markdown";if(o!=="json"&&e.fileWarnings?.length)ni(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"?ri(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 oi(e,t,n,o){let r=n??".";yc(r,{recursive:!0});let i=me("file").actions.find((a)=>a.name==="read"),s=await Kt(e,i,t,Yo(r,`file_${t}`),{resolvePath:(a)=>{let d=a.get("Content-Disposition")??"",l=d.match(/filename\*\s*=\s*(?:UTF-8'')?["']?([^"';\n]+)["']?/i),f=d.match(/filename\s*=\s*(?:"([^"]+)"|'([^']+)'|([^;\n]+))/i),g=(l?.[1]??f?.[1]??f?.[2]??f?.[3])?.trim()||`file_${t}`;if(l)try{g=decodeURIComponent(g)}catch{}let m=Yo(r,Xn(g));if(ti(m))throw new c("E2009",{option:"output",reason:`目标文件已存在: ${m}`});return m},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 Qo={".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 ii(e,t,n,o,r){let i=Ko(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 l={...n.data},f=typeof l.comment==="string"?l.comment:"",p=[];for(let g of o){let m=r?.marks.get(g);if(m!==void 0){p.push(m);continue}if(!ti(g))throw new c("E2009",{option:"image",reason:`图片文件不存在: ${g}`});let h=hc(g).toLowerCase(),y=Qo[h];if(!y)throw new c("E2009",{option:"image",reason:`不支持的图片格式 ${h||"(无扩展名)"},支持 ${Object.keys(Qo).join(" ")}`});let b=new FormData;b.append("file",new Blob([bc(g)],{type:y}),Xn(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="${ei(w)}" alt="${ei(Xn(g))}" />`;r?.marks.set(g,v),p.push(v)}return l.comment=f?`${f}
|
|
931
938
|
${p.join(`
|
|
932
939
|
`)}`:p.join(`
|
|
933
|
-
`),{...n,data:
|
|
934
|
-
`)}function
|
|
940
|
+
`),{...n,data:l}}function ei(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}function kc(e){let t=e instanceof Error?e:Error(String(e));return{...t instanceof c&&Q(t.details)?{recoveryMessage:It(t,"table")}:{},error:{...t instanceof c?{code:t.code,details:t.details}:{},message:t.message}}}function xc(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}])=>{if(d&&typeof d==="object"&&!Array.isArray(d)){let l={...d};return delete l.actions,{...l,objectID:a}}return{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(`
|
|
941
|
+
`)}function si(e,t){let n=zr(e.name),o=t.format??"markdown",r=Xe(n,{format:o,isList:!1});if(r)console.log(r)}async function Qn(e,t,n,o,r,i){let s=Y(r),a=i.batchFailFast??s.batchFailFast??!1,d=i.format??s.defaultOutputFormat??"markdown",l=De(t,n);if(!l)throw new c("E2005",{module:t.name});let f=Mt(l,o,i.ids);if(f){if(d==="raw")throw new c("E2009",{option:"raw/ids",reason:"原始响应不支持批量组合,请使用 json"});if(l.type==="delete"&&!i.yes){if(!await Xo(d,f.length,i.machineReadable||i.input===!1))return}let g={ids:f,skipped:[],data:new Map,errors:new Map},m=he(l),{outcomes:h,skipped:y}=await rn({ids:f,failFast:a,throwIfAborted:()=>I()?.throwIfAborted(),onError:(b,k)=>{if(I()?.aborted&&k instanceof c&&Q(k.details))throw k},execute:(b)=>St(e,t,n,{...o,id:b,...m?{[m]:b}:{}},i,s)});g.skipped=y;for(let b of h)if(b.ok){if(g.data.set(b.id,{value:l.type==="delete"?null:b.value.data,meta:ri(b.value)}),d!=="json"&&b.value.fileWarnings?.length)ni(b.value.fileWarnings,b.id)}else g.errors.set(b.id,kc(b.error));if(console.log(xc(g,d,s.jsonPretty??!1,l.type!=="delete")),g.errors.size>0)process.exitCode=1;return}if(l.type==="delete"&&!i.yes){if(!await Xo(d,1,i.machineReadable||i.input===!1))return}let p=await St(e,t,n,o,i,s);vc(p,i,s)}Ke();T();var ai={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 zc(e,t){let n=ai[e];if(!n)at(e,`未知选项;可用选项: ${Object.keys(ai).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 ci(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]=zc(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 tr(e,t=[]){return t.concat([e])}function di(e){for(let t of kr()){let n=me(t),o=e.command(t).description(n.display??t);if(o.argument("[target]",u`对象 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:u`无法识别 "${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:u`模块 ${t} 没有 get 操作,请查看 zentao ${t} --help`});let l=s.optsWithGlobals(),f=await Zn(n,d,a,l,{}),p=await ue(l);await kt(p,l,(g,m)=>Qn(g,n,"get",f,m,l))}),o.command("props").description("返回对象字段定义(离线)").action((r,i)=>{si(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 ue(s);await kt(d,s,(l)=>oi(l,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=ce(t,r.name),l=o.command(Ie(r.name)).description(`${r.display??r.name}(最低版本:${r.minVersion.join(" / ")})`);if(s.target)l.argument("[target]",d?"单个附件标识或当前站点的附件 URL,--file-id 可单独指定标识":`单个 ${s.target};也可使用命名参数`);let f=[],p=s.pagination,g=new Set(p?[p.page,p.pageSize]:[]);for(let m of s.parameters){if(g.has(m.name)||f.some((b)=>b.name===m.name))continue;let h=m.flag.slice(2),y=new er(`--${h} ${m.type==="boolean"?"[boolean]":"<value>"}`,`${m.description??m.name}${m.required&&!(d&&m.name==="fileID")?"(必填)":""}`);if(m.type==="array")y.argParser((b,k=[])=>k.concat(b));if(m.type==="boolean")y.preset(!0);if(l.addOption(y),f.push({name:m.name,attribute:y.attributeName()}),m.type==="boolean")l.addOption(new er(`--no-${h}`,`将 ${m.name} 设为 false`).default(void 0));if(m.type!=="array"){let b,k=()=>{let w=m.name==="id"||m.name.endsWith("ID"),v=We(l.getOptionValue(y.attributeName()),m,w);if(b!==void 0&&!Tc(b,v))throw new c("E2009",{option:h,reason:"重复选项的输入值冲突"});b=v};if(l.on(`option:${y.name()}`,k),m.type==="boolean")l.on(`option:no-${h}`,k)}}for(let m of["product","project","execution"]){if(!Tt(i,m)||f.some((y)=>y.name===m))continue;let h=new er(`--${m} <id>`,`${m}ID 或 scope/scopeID 别名`);l.addOption(h),f.push({name:m,attribute:h.attributeName()})}if(r.requestBody)l.option("--data <json|@file|@->","JSON 对象、文件或显式标准输入");if(l.option("--options <json>","CLI 调用选项(JSON 对象;显式命令行参数优先)"),s.markdownFields.length){let m=s.markdownFields.join(", "),h=t==="doc"?"(content 需显式指定 --content-type html)":"";l.option("--markdown [fields]",`将 Markdown 转为 HTML。可选 ${m}${h},多个字段用逗号分隔,省略时转换本次提供的全部 HTML 字段`)}if(a)l.option("--output <path>","流式保存附件,下载完成后替换目标文件");if(s.batch)l.option("--ids <ids>","批量目标 ID,逗号分隔并去重").option("--batch-fail-fast","失败后跳过剩余目标");if(r.name==="comment")l.option("--image <path>","随备注上传并内嵌到正文的图片路径(可多次)",tr);if(r.type==="delete")l.option("--yes","确认删除");if(r.type==="list"||r.type==="get"&&!a)l.option("--fields <fields>","返回字段,逗号分隔").option("--html-to-markdown","显式将富文本字段转换为 Markdown");if(r.type==="list")l.option("--max-items <number>","整次命令最多返回条数"),l.option("--filter <expr>","当前获取范围内过滤;组内 AND,多次指定为 OR",tr),l.option("--search <keywords>","当前获取范围内搜索",tr),l.option("--search-fields <fields>","本地搜索字段"),l.option("--sort <expr>","当前获取范围内排序,如 id:asc");if(p)l.option("--page <number>","指定页,从 1 开始").option("--page-size <number>","每次服务端请求的页大小").option("--all","显式遍历全部页面");l.action(async(...m)=>{let y=m.at(-1).optsWithGlobals(),b=ci({...y,pick:y.fields,recPerPage:y.pageSize}),k=Object.fromEntries(f.map((x)=>[x.name,y[x.attribute]])),w,v=await Zn(n,r,s.target?m[0]:void 0,b,k,(x)=>{w=Se(b.profile),Ne(x,w.server)}),z=await ue(b,w);if(a&&b.output!==void 0){let x=b.format??Y(z.profile).defaultOutputFormat;if(x==="raw")throw new c("E2009",{option:"output",reason:"写入文件时请使用 table、markdown 或 json 输出下载结果"});await kt(z,b,async(A)=>{let M=await Kt(A,r,String(v.fileID),b.output,b);O(M,{format:x})});return}let F=y.image,S=F?.length?{marks:new Map}:void 0;await kt(z,b,async(x,A)=>{let M=S?await ii(x,n,v,F,S):v;await Qn(x,n,r.name,M,A,b)})})}}}L();sr();T();function Ri(e){let t=lr(e.command("mcp").description(u("启动 MCP 服务,支持本地 stdio 或多客户端 HTTP 访问禅道数据")).option("--transport <type>","传输方式 (stdio|http)","stdio")).action((n)=>ur(n,e.optsWithGlobals()));return lr(t.command("serve").description("启动 MCP 服务").option("--transport <type>","传输方式 (stdio|http)","stdio")).action((n,o)=>{let r=o.optsWithGlobals();return ur(r,r)}),lr(e.command("mcp-server").description(u("启动 HTTP MCP 服务,供多个客户端访问固定禅道站点")).argument("[url]",u("禅道站点地址,与 --url 二选一;省略时读取 ZENTAO_URL"))).addHelpText("after",u(`
|
|
935
942
|
示例:
|
|
936
943
|
zentao mcp-server https://zentao.example.com
|
|
937
944
|
zentao mcp-server --url https://zentao.example.com
|
|
938
945
|
ZENTAO_URL=https://zentao.example.com zentao mcp-server
|
|
939
|
-
`)).action((n,o)=>{if(n!==void 0&&o.url!==void 0)throw new c("E2009",{option:"--url",reason:"位置参数 URL 与 --url 不能同时提供"});return
|
|
946
|
+
`)).action((n,o)=>{if(n!==void 0&&o.url!==void 0)throw new c("E2009",{option:"--url",reason:"位置参数 URL 与 --url 不能同时提供"});return ur({...o,url:n??o.url,transport:"http"},e.optsWithGlobals())}),t}function lr(e){return e.option("--host <host>","HTTP 监听地址(默认 127.0.0.1)").option("--port <port>","HTTP 监听端口(默认 9090)").option("--url <url>",u("HTTP 模式的固定禅道站点地址(亦可通过 ZENTAO_URL 设置)")).option("--read-only","仅提供查询工具,禁止业务写入和账号切换").option("--modules <names>","仅提供指定业务模块(逗号分隔,如 product,story,task)",(t)=>t.split(",").map((n)=>n.trim())).option("--split-tools","按模块分为 _read 查询工具和 _write 写入工具")}async function ur(e,t){let n={assistant:t.assistant,insecure:t.insecure,timeout:t.timeout,profile:t.profile,readOnly:e.readOnly,modules:e.modules,splitTools:e.splitTools};if(e.transport!=="stdio"&&e.transport!=="http")throw new c("E2009",{option:"--transport",reason:"必须为 stdio 或 http"});if(e.transport==="stdio"){for(let p of["host","port","url"])if(e[p]!==void 0)throw new c("E2009",{option:`--${p}`,reason:"仅适用于 --transport http"});await ir({...n,preferPassword:t.preferPassword});return}let o=e.url??process.env[u("ZENTAO_URL")];if(!o?.trim())throw new c("E2009",{option:"--url",reason:u("HTTP 模式必须指定禅道站点,或设置 ZENTAO_URL")});let r=e.port===void 0?9090:Number(e.port);if(e.port!==void 0&&!/^\d+$/.test(e.port)||!Number.isInteger(r)||r<1||r>65535)throw new c("E2009",{option:"--port",reason:"必须为 1–65535 的整数"});await Promise.resolve().then(() => Mi());let s=await Ii({...n,url:o,host:e.host,port:r});process.stderr.write(`MCP HTTP 服务已启动:${s.url.href}
|
|
940
947
|
`);let a=new URL(s.url);if(a.hostname==="0.0.0.0")a.hostname="127.0.0.1";if(a.hostname==="[::]")a.hostname="[::1]";process.stderr.write(`用户接入页面:${new URL("/start",a).href}
|
|
941
|
-
`);let d={mcpServers:{[
|
|
948
|
+
`);let d={mcpServers:{[u("zentao-remote")]:{type:"http",url:a.href,headers:{token:u("<your-zentao-token>")}}}};process.stderr.write([u(`
|
|
942
949
|
客户端配置示例(请替换为自己的禅道 Token,并合并到已有配置):`),`
|
|
943
|
-
Codex(~/.codex/config.toml):`,
|
|
944
|
-
Claude Code / Cursor(JSON):`,"Claude Code:~/.claude.json","Cursor:~/.cursor/mcp.json(或项目内 .cursor/mcp.json)",JSON.stringify(d,null,2),
|
|
950
|
+
Codex(~/.codex/config.toml):`,u("[mcp_servers.zentao-remote]"),`url = ${JSON.stringify(a.href)}`,u('http_headers = { token = "<your-zentao-token>" }'),`
|
|
951
|
+
Claude Code / Cursor(JSON):`,"Claude Code:~/.claude.json","Cursor:~/.cursor/mcp.json(或项目内 .cursor/mcp.json)",JSON.stringify(d,null,2),u(`
|
|
945
952
|
也可将 token 请求头替换为 Authorization: Bearer <your-zentao-token>,两种认证头任选其一。`),`远程客户端请将 url 替换为可访问的 HTTPS 服务地址。
|
|
946
953
|
`].join(`
|
|
947
|
-
`));let
|
|
948
|
-
`),process.exitCode=1}).finally(()=>{process.removeListener("SIGINT",
|
|
949
|
-
`);let i=await
|
|
950
|
-
`);let{status:g}=await
|
|
951
|
-
${
|
|
952
|
-
`),process.exitCode=t==="interrupt"||["5003","1008"].includes(r.code)?130:e instanceof
|
|
954
|
+
`));let l=!1,f=()=>{if(l)return;l=!0,s.close().catch(()=>{process.stderr.write(`MCP HTTP 服务关闭失败
|
|
955
|
+
`),process.exitCode=1}).finally(()=>{process.removeListener("SIGINT",f),process.removeListener("SIGTERM",f)})};process.once("SIGINT",f),process.once("SIGTERM",f)}re();T();Fe();import{createInterface as Xc}from"node:readline/promises";L();import{spawn as Gc}from"node:child_process";import{fileURLToPath as Vc}from"node:url";var Li=ke?.packageName??xt.name,Jc=`https://registry.npmjs.org/${encodeURIComponent(Li)}/latest`;function ln(e){let t=e.trim().replace(/^v/,"").match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(!t)return null;return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:t[4]??""}}function Kc(e,t){let n=e.split("."),o=t.split("."),r=Math.max(n.length,o.length);for(let i=0;i<r;i++){let s=n[i],a=o[i];if(s===void 0)return-1;if(a===void 0)return 1;let d=/^\d+$/.test(s),l=/^\d+$/.test(a);if(d&&l){let f=Number(s),p=Number(a);if(f!==p)return f>p?1:-1}else if(d!==l)return d?-1:1;else if(s!==a)return s>a?1:-1}return 0}function $i(e,t){for(let n of["major","minor","patch"])if(e[n]!==t[n])return e[n]>t[n]?1:-1;if(!e.prerelease&&t.prerelease)return 1;if(e.prerelease&&!t.prerelease)return-1;if(e.prerelease===t.prerelease)return 0;return Kc(e.prerelease,t.prerelease)}function Yc(e){let t=ln(e);return!!t&&t.prerelease===""}async function ji(e,t=1e4){let n=new AbortController,o=()=>n.abort();if(e?.addEventListener("abort",o,{once:!0}),e?.aborted)o();let r=setTimeout(o,t),i;try{i=await fetch(Jc,{headers:{Accept:"application/json"},signal:n.signal})}catch(a){throw Error(`无法连接到 npm registry: ${a.message}`)}finally{clearTimeout(r),e?.removeEventListener("abort",o)}if(!i.ok)throw Error(`npm registry 返回错误: ${i.status} ${i.statusText}`);let s=await i.json();if(typeof s.version==="string"&&Yc(s.version))return s.version;if(typeof s.version!=="string")throw Error("npm registry 返回数据格式异常");throw Error("npm registry 未找到正式版本")}function Di(){let e="";try{e=Vc(import.meta.url)}catch{e=process.argv[1]??""}let t=e.replace(/\\/g,"/");if(/\/\.bun\/|\/bun\/install\//.test(t))return"bun";return"npm"}function pr(e,t="latest"){let n=`${Li}@${t}`;if(e==="bun")return{cmd:"bun",args:["add","-g",n]};return{cmd:"npm",args:["install","-g",n]}}async function Ni(e,t="latest",n){let{cmd:o,args:r}=pr(e,t);return{status:await new Promise((s,a)=>{let d=Gc(o,r,{stdio:["ignore","pipe","pipe"],shell:process.platform==="win32",signal:n});d.stdout?.on("data",(l)=>process.stderr.write(l)),d.stderr?.on("data",(l)=>process.stderr.write(l)),d.once("error",a),d.once("close",s)}),cmd:o,args:r}}async function Qc(e,t){if(!process.stdin.isTTY||!process.stderr.isTTY)throw new c("E2009",{option:"yes",reason:"非交互模式下必须显式确认升级"});let n=Xc({input:process.stdin,output:process.stderr});try{return(await n.question(`发现新版本 ${e} → ${t},是否立即升级?[y/N] `,{signal:I()})).trim().toLowerCase()==="y"}finally{n.close()}}function _i(e){e.command("update").description("检查并升级 CLI 到最新版本").option("-y, --yes","跳过确认,直接升级").action(async(t)=>{let n=e.optsWithGlobals(),o=!!n.quiet,r=de();if(!o)process.stderr.write(`正在检查最新版本...
|
|
956
|
+
`);let i=await ji(I(),n.timeout),s=ln(r),a=ln(i);if(!s||!a)throw Error(`版本号格式无法解析: 当前=${r}, 最新=${i}`);if($i(s,a)>=0){O({current:r,latest:i,updated:!1},n);return}if(!t.yes&&n.input===!1)throw new c("E2009",{option:"yes",reason:"--no-input 时必须显式确认升级"});if(!(t.yes||await Qc(r,i))){O({updated:!1,cancelled:!0},n);return}let l=Di(),{cmd:f,args:p}=pr(l,i);if(!o)process.stderr.write(`执行: ${f} ${p.join(" ")}
|
|
957
|
+
`);let{status:g}=await Ni(l,i,I());if(g===0)O({previous:r,current:i,updated:!0},n);else throw Error(`升级失败,请手动运行:
|
|
958
|
+
${f} ${p.join(" ")}`)})}nn();function Fi(e){tn(),Lr(e),Sn(e),On(e),lo(e);let t=e.command("auth").description("认证与凭据");t.action(()=>t.outputHelp()),Sn(t),On(t),Yr(t),uo(e),po(e),co(e),fo(e),mo(e);let n=e.command("skill").description("安装或导出技能");n.action(()=>n.outputHelp()),ko(n);let o=Ri(e);_n(o),_n(e,"add-mcp"),di(e);let r=e.command("self").description("管理本机 CLI 安装");r.action(()=>r.outputHelp()),_i(r)}Fe();T();L();be();function Hi(e){if(!/^\d+$/.test(e)||!Number.isSafeInteger(Number(e))||Number(e)<1)throw new c("E2009",{option:"timeout/deadline",reason:"必须为正安全整数(毫秒)"});return Number(e)}function Bi(){let e=new ed,t=(n)=>n.replace(/^Usage:/gm,"用法:").replace(/^Options:/gm,"选项:").replace(/^Commands:/gm,"命令:").replace(/display help for command/g,"显示命令帮助");return e.configureOutput({writeOut:(n)=>process.stdout.write(t(n)),writeErr:(n)=>process.stderr.write(t(n)),outputError:()=>{}}),e.name(u("zentao")).description(u("禅道命令行工具")).version(de(),"-V, --version","显示 CLI 版本号").helpOption("-h, --help","显示命令帮助").addOption(new Ui("--format <format>","输出格式").choices(bn)).option("--profile <key>","仅本次命令选择账号(优先于环境凭据)").option("--prefer-password","同时提供密码和 Token 时,本次优先用密码获取新 Token").option("--assistant <value>","本次操作来源标记;空字符串关闭标记",Qe).option("--config <file>",u("配置文件路径(也支持 ZENTAO_CONFIG_FILE)")).option("--no-input","禁止浏览器、输入提示和选择菜单").option("-y, --yes","确认操作,不补全缺失参数").option("--quiet","压制进度和提示,保留结果和错误").addOption(new Ui("--color <mode>","颜色控制").choices(["auto","always","never"]).default("auto")).option("--insecure","跳过 TLS 证书验证").option("--timeout <ms>","单次 HTTP 请求超时",Hi).option("--deadline <ms>","整次命令期限,含认证和预取",Hi).exitOverride(),Fi(e),e.action(()=>e.outputHelp()),e}T();X();re();var mr=process.argv.slice(2);function Zi(e){let t;for(let n=0;n<mr.length;n++){let o=mr[n];if(o==="--")break;let r=o.indexOf("="),i=r<0?o:o.slice(0,r),s=gr.options.find((d)=>d.long===i||d.short===i);if(!s)continue;let a=r>=0?o.slice(r+1):s.required?mr[++n]:void 0;if(s.long===e)t=a}return t}var gr=Bi(),qi;gr.hook("preAction",(e,t)=>{let n=t.optsWithGlobals();if(n.format==="raw"&&t.name()!=="token"&&!me(t.parent?.name()??"")?.actions.some((o)=>Ie(o.name)===t.name()))throw new c("E2009",{option:"raw",reason:"raw 仅适用于具有原始服务端响应的业务命令"});qi=qr(n)});try{let e=Zi("--config")??process.env[u("ZENTAO_CONFIG_FILE")];if(e?.trim())Hr(e);await gr.parseAsync(process.argv)}catch(e){if(e instanceof fr&&e.exitCode===0)process.exitCode=0;else{let t=Zr(),n=t&&e&&typeof e==="object"&&"details"in e?Q(e.details):void 0,o=t?new c(t==="deadline"?"E5001":"E5003",void 0,n):e instanceof fr?new c("E2009",{option:"argv",reason:e.message.replace(/^error: /,"").trim()}):e instanceof c?e:N(e),r=o instanceof c?o:new c("E2008",{url:"",status:"",serverResponse:o instanceof Error?o.message:String(o)});process.stderr.write(It(r,Zi("--format")??"table")+`
|
|
959
|
+
`),process.exitCode=t==="interrupt"||["5003","1008"].includes(r.code)?130:e instanceof fr||["2001","2003","2004","2005","2007","2009"].includes(r.code)?2:1}}finally{qi?.()}
|