zcode-app-cli 3.14.4-31 → 3.14.4-32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -7
- package/bin/zcode.js +23 -5
- package/docs/CONFIGURATION.md +171 -4
- package/docs/CONFIGURATION.zh-CN.md +151 -4
- package/docs/PROVIDER_CONFIG.md +4 -2
- package/docs/PROVIDER_CONFIG.zh-CN.md +3 -2
- package/package.json +1 -1
- package/vendor/cli-config.cjs +95 -1
- package/vendor/extraction.json +11 -1
- package/vendor/node_modules/@zcode/tui/dist/index.js +4 -2
- package/vendor/zcode.cjs +3 -3
package/vendor/zcode.cjs
CHANGED
|
@@ -2133,7 +2133,7 @@ ${Array.from(n,([s,a])=>`${s}: ${a}`).join(`
|
|
|
2133
2133
|
---
|
|
2134
2134
|
|
|
2135
2135
|
${o}`}function g7s(e){let t=e.replace(/^\uFEFF/,"");if(!t.startsWith("---"))return e;let n=t.split(/\r?\n/);if(n[0]?.trim()!=="---")return e;let o=n.findIndex((s,a)=>a>0&&s.trim()==="---");return o>0?n.slice(o+1).join(`
|
|
2136
|
-
`):e}function _7s(e,t,n){let o=_Gr(e);if(o!==void 0){for(let a of o)Eat(n);return o}let s=(0,Bk.join)(e,"cache",Yp);try{let a=[];for(let l of(0,WF.readdirSync)(s,{withFileTypes:!0})){if(Eat(n),!l.isDirectory())continue;let u=(0,Bk.join)(s,l.name);for(let f of(0,WF.readdirSync)(u,{withFileTypes:!0}))f.isDirectory()&&a.push((0,Bk.join)(u,f.name))}return a}catch(a){return Cat(a)?[]:(t.push({code:"plugin_root_not_found",message:a instanceof Error?a.message:`Failed to scan ${s}`,path:s,severity:"warning"}),[])}}function y7s(e,t){if(!$v(e.rootPath))return t.push({code:"plugin_root_not_found",message:`Plugin root does not exist: ${e.rootPath}`,path:e.rootPath,severity:"warning"}),null;let n=v7s(e.rootPath);if(!n)return t.push({code:"plugin_manifest_not_found",message:`Plugin manifest not found: ${e.rootPath}`,path:e.rootPath,severity:"error"}),null;let o=b7s(n,t);return o?{id:`${o.name}@${e.marketplace}`,manifest:o,manifestPath:n,marketplace:e.marketplace,rootPath:e.rootPath,source:e.source}:null}function v7s(e){let t=(0,Bk.join)(e,qzs);if(bw(t))return t;let n=(0,Bk.join)(e,Wzs);if(bw(n))return n;let o=(0,Bk.join)(e,Vzs);return bw(o)?o:null}function b7s(e,t){try{let n=JSON.parse((0,WF.readFileSync)(e,"utf8"));if(!fu(n))throw new Error("Manifest must be a JSON object");let o=typeof n.name=="string"?n.name.trim():"";if(!Kzs.test(o))throw new Error(`Invalid plugin name: ${o}`);return{...n,name:o,version:typeof n.version=="string"?n.version:Hzs}}catch(n){return t.push({code:"plugin_manifest_invalid",message:n instanceof Error?n.message:`Invalid plugin manifest: ${e}`,path:e,severity:"error"}),null}}function S7s(){return{commandRoots:[],diagnostics:[],hooks:{},mcpServers:{},plugins:[],skillRoots:[]}}function w7s(e=[]){return{commandRoots:[],hooks:{},hookDetails:e,mcpServers:{},skillCount:0,skillRoots:[]}}function k7s(e,t,n){return e.enabledPlugins[t]??n}var WF,Bk,qzs,Wzs,Vzs,Hzs,Gzs,Jzs,Kzs,Zzs,Yzs,Kdn,GOe=Y(()=>{"use strict";WF=require("node:fs"),Bk=require("node:path");nr();q7();kat();Rat();Dun();Mun();Edn();Mat();Edn();Mat();sdn();EZr();qzs=(0,Bk.join)(".zcode-plugin","plugin.json"),Wzs=(0,Bk.join)(".claude-plugin","plugin.json"),Vzs=(0,Bk.join)(".codex-plugin","plugin.json"),Hzs="0.0.0",Gzs=1e3,Jzs=10,Kzs=/^[a-z0-9][a-z0-9._-]{0,127}$/,Zzs=["channels","lspServers","outputStyles","settings"],Yzs=new Set(Object.values(Tl)),Kdn=class{static{r(this,"NodePluginAdapter")}options;constructor(t){this.options=t}async discoverPlugins(t,n){return this.discoverPluginsSync(t,n)}discoverPluginsSync(t,n){if(!t.config.enabled)return S7s();let o=[],s=(0,Bk.join)(t.storageRoot||this.options.storageRoot,"data"),a=this.resolveCandidates(t,o,n),l=[],u={},f={},g=[],_=new Set,b=[],w=Gzs;for(let T of a){Eat(n);let I=y7s(T,o);if(!I||I.source==="official"&&t.config.suppressedBuiltins.includes(I.id))continue;if(_.has(I.id)){o.push({code:"plugin_duplicate_id",message:`Duplicate plugin ignored: ${I.id}`,path:I.rootPath,pluginId:I.id,severity:"warning"});continue}_.add(I.id),n7s(I,o);let E=T.defaultEnabled||(t.officialPluginsEnabledByDefault?.has(I.id)??!1),R=k7s(t.config,I.id,E),L=(0,Bk.join)(s,$7(I.id)),U=gre({diagnostics:o,loaded:I}),B=t7s(I),z=s7s({dataPath:L,diagnostics:o,loaded:I,runnable:B}),$=R?e7s({dataPath:L,diagnostics:o,env:t.env??{},hookEvents:B?z.events:{},hookDetails:z.details,loaded:I,mcpServerDefinitions:U,options:t.config.options[I.id]??{},priority:w,workingDirectory:t.workingDirectory}):w7s(z.details);w+=Jzs,Object.assign(f,$.mcpServers),AZr(u,$.hooks),b.push(...$.skillRoots),l.push(...$.commandRoots),g.push(Qzs(I,$,L,R,Object.keys(U),t.config.options[I.id]??{}))}return{commandRoots:l,diagnostics:o,hooks:u,mcpServers:f,plugins:g,skillRoots:b}}resolveCandidates(t,n,o){let s=[];for(let a of t.config.dirs)s.push({defaultEnabled:!0,marketplace:OZn,rootPath:(0,Bk.resolve)(a),source:"inline"});for(let a of t.officialPluginRoots??[])s.push({defaultEnabled:!1,marketplace:Yp,rootPath:(0,Bk.resolve)(a),source:"official"});s.push(..._7s(t.storageRoot,n,o).map(a=>({defaultEnabled:!1,marketplace:Yp,rootPath:a,source:"official"})));for(let a of X7(t.storageRoot))s.push({defaultEnabled:!1,marketplace:a.marketplace,rootPath:ydn(t.storageRoot,a),source:"cache"});return s}};r(Xzs,"createNodePluginAdapter");r(wct,"discoverNodePluginsSync");r(Qzs,"createPluginMetadata");r(e7s,"resolveEnabledComponents");r(t7s,"canRunPluginHooks");r(n7s,"warnUnsupportedComponents");r(r7s,"resolveSkillRoots");r(o7s,"warnEmptyDeclaredSkillRoots");r(i7s,"resolveCommandRoots");r(s7s,"inspectPluginHooks");r(a7s,"parsePluginHookEvents");r(c7s,"toPluginHookDetail");r(Zdn,"createHookPluginContext");r(l7s,"attachPluginToHook");r(AZr,"mergeHookEvents");r(u7s,"mergeHookInspection");r(PZr,"emptyHookInspection");r(d7s,"countSkillFiles");r(RZr,"resolveComponentRoots");r(p7s,"materializeCommandMetadataRoot");r(f7s,"normalizeGeneratedCommandName");r(m7s,"trimRelativePrefix");r(h7s,"applyCommandMetadataFrontmatter");r(g7s,"stripMarkdownFrontmatter");r(_7s,"scanOfficialCache");r(y7s,"loadPlugin");r(v7s,"findManifest");r(b7s,"readManifest");r(S7s,"emptyOutcome");r(w7s,"emptyComponents");r(k7s,"resolveEnabled")});function OZr(e){let t=e.appId??I7s,n=e.appSecret?.trim()??"",o=e.authorizeUrl??Hpe(process.env,x7s),s=e.tokenUrl??Hpe(process.env,T7s);return{buildAuthorizeUrl(a){let l=new URLSearchParams({appId:t,redirect:a.redirectUri,state:a.state});return`${o}?${l.toString()}`},async exchangeCode(a,l){if(!n)throw new kct("BigModel OAuth appSecret is required.");let u=await e.httpClient.request({body:new TextEncoder().encode(JSON.stringify({appId:t,appSecret:n,authCode:a.code})),headers:{"Content-Type":E7s},maxResponseBytes:64*1024,method:"POST",trace:e.trace,url:s},l),f=JSON.parse(new TextDecoder().decode(u.body)),g=f.data?.accessToken?.trim()??"";if(!g)throw new kct(f.msg??"BigModel token response is missing accessToken.");return{accessToken:g,...f.data?.refreshToken?{refreshToken:f.data.refreshToken}:{}}}}}function MZr(){return(0,DZr.randomBytes)(C7s).toString("hex")}var DZr,x7s,T7s,I7s,C7s,E7s,kct,NZr=Y(()=>{"use strict";DZr=require("node:crypto");ms();x7s="/login",T7s="/api/auth/tokenByAuthCode",I7s="zcode",C7s=32,E7s="application/json",kct=class extends Error{static{r(this,"BigmodelOAuthError")}constructor(t,n={}){super(t,n),this.name="BigmodelOAuthError"}};r(OZr,"createBigmodelOAuthClient");r(MZr,"createBigmodelOAuthState")});async function Ydn(e,t={}){let n=t.platform??process.platform,o=P7s(n,e),s=t.spawnProcess??LZr.spawn;try{let a=s(o.executable,o.args,{detached:!0,stdio:"ignore",windowsHide:!0});return await R7s(a,o.executable,t.timeoutMs)}catch(a){return{command:o.executable,opened:!1,reason:a instanceof Error?a.message:String(a)}}}function P7s(e,t){return e==="darwin"?{executable:"open",args:[t]}:e==="win32"?{executable:"cmd.exe",args:["/c","start","",t]}:{executable:"xdg-open",args:[t]}}function R7s(e,t,n=A7s){return new Promise(o=>{let s=!1,a,l=r(u=>{s||(s=!0,clearTimeout(a),e.removeAllListeners("error"),e.removeAllListeners("spawn"),u.opened&&e.unref(),o(u))},"settle");a=setTimeout(()=>{l({command:t,opened:!0})},n),e.once("spawn",()=>{l({command:t,opened:!0})}),e.once("error",u=>{l({command:t,opened:!1,reason:u.message})})})}var LZr,A7s,FZr=Y(()=>{"use strict";LZr=require("node:child_process"),A7s=1e3;r(Ydn,"openUrlInBrowser");r(P7s,"browserOpenCommand");r(R7s,"waitForBrowserSpawn")});function $Zr(e){return{async resolve(t,n){let o=t.accessToken.trim();if(!o)throw new yG("OAuth access token is required.");if(t.family==="bigmodel")return BZr({authorization:o,host:XAe(process.env),httpClient:e.httpClient,trace:e.trace},n);let s=await M7s(e,o,n);return BZr({authorization:`Bearer ${s}`,host:UZr,httpClient:e.httpClient,requireSecretKey:!0,trace:e.trace},n)}}}async function M7s(e,t,n){let o=await JOe(e.httpClient,{body:new TextEncoder().encode(JSON.stringify({token:t})),headers:{"Content-Type":zZr},method:"POST",trace:e.trace,url:`${UZr}/api/auth/z/login`},n),s=o?.access_token?.trim()??o?.accessToken?.trim()??"";if(!s)throw new yG("Z.AI biz token response is missing access_token.");return s}async function BZr(e,t){let n=await JOe(e.httpClient,{headers:xct(e.authorization),method:"GET",trace:e.trace,url:`${e.host}/api/biz/customer/getCustomerInfo`},t),o=N7s(n);if(!o)throw new yG("Unable to resolve organization and project.");let s=`${e.host}/api/biz/v1/organization/${o.organizationId}/projects/${o.projectId}/api_keys`,u=((await JOe(e.httpClient,{headers:xct(e.authorization),method:"GET",trace:e.trace,url:s},t)??[]).find(_=>_.name===jZr)??await JOe(e.httpClient,{body:new TextEncoder().encode(JSON.stringify({name:jZr})),headers:xct(e.authorization),method:"POST",trace:e.trace,url:s},t))?.apiKey?.trim()??"";if(!u)throw new yG("API key response is missing apiKey.");let g=(await JOe(e.httpClient,{headers:xct(e.authorization),method:"GET",trace:e.trace,url:`${s}/copy/${encodeURIComponent(u)}`},t))?.secretKey?.trim()??"";if(!g){if(e.requireSecretKey)throw new yG("API key copy response is missing secretKey.");return u}return`${u}.${g}`}async function JOe(e,t,n){let o=await e.request({maxResponseBytes:65536,...t},n),s=JSON.parse(new TextDecoder().decode(o.body));if(!L7s(s.code))throw new yG(s.msg??`Remote business error ${s.code}`);return s.data??null}function xct(e){return{Authorization:e,"Content-Type":zZr}}function N7s(e){let t=e?.organizations??[],n=t.find(a=>a.organizationName?.includes(D7s))??t[0],o=n?.projects??[],s=o.find(a=>a.projectName?.includes(O7s))??o[0];return!n?.organizationId||!s?.projectId?null:{organizationId:n.organizationId,projectId:s.projectId}}function L7s(e){return e==null||e===0||e===200||e==="0"||e==="200"}var UZr,zZr,jZr,D7s,O7s,yG,qZr=Y(()=>{"use strict";ms();UZr="https://api.z.ai",zZr="application/json",jZr="zcode-api-key",D7s="\u9ED8\u8BA4\u673A\u6784",O7s="\u9ED8\u8BA4\u9879\u76EE",yG=class extends Error{static{r(this,"CodingPlanApiKeyError")}constructor(t,n={}){super(t,n),this.name="CodingPlanApiKeyError"}};r($Zr,"createCodingPlanApiKeyResolver");r(M7s,"resolveZaiBizToken");r(BZr,"resolveBizApiKey");r(JOe,"requestRemoteData");r(xct,"createBizAuthHeaders");r(N7s,"pickOrgAndProject");r(L7s,"isSuccessfulRemoteCode")});function Xdn(e){let t=z7s(e.baseUrl??F7s),n=new TextEncoder;return{async init(o,s){let a=await WZr(e.httpClient,{body:n.encode(JSON.stringify({provider:j7s})),headers:{Authorization:`Bearer ${o.pollToken}`,"Content-Type":U7s},method:"POST",trace:e.trace,url:`${t}/oauth/cli/init`},s);return $7s(a.data)},async poll(o,s){let a=encodeURIComponent(o.flowId),l=await WZr(e.httpClient,{headers:{Authorization:`Bearer ${o.pollToken}`},method:"GET",trace:e.trace,url:`${t}/oauth/cli/poll/${a}`},s);return q7s(l.data)}}}function HZr(){return(0,VZr.randomBytes)(B7s).toString("hex")}function z7s(e){return e.replace(/\/+$/u,"")}async function WZr(e,t,n){let o=await e.request({maxResponseBytes:65536,...t},n),s=new TextDecoder().decode(o.body),a=V7s(s,o.status),l=KOe(a);if(!l||typeof l.code!="number")throw new Q7("Invalid OAuth response envelope",{httpStatus:o.status});let u=typeof l.msg=="string"?l.msg:void 0;if(o.status<200||o.status>=300)throw new Q7(u??`OAuth HTTP error ${o.status}`,{businessCode:l.code,httpStatus:o.status});if(l.code!==0)throw new Q7(u??`OAuth business error ${l.code}`,{businessCode:l.code,httpStatus:o.status});return{code:l.code,data:l.data,msg:u}}function $7s(e){let t=KOe(e);if(!t||typeof t.flow_id!="string"||typeof t.poll_token!="string"||typeof t.authorize_url!="string"||typeof t.expires_at!="number"||typeof t.poll_interval_sec!="number")throw new Q7("Invalid OAuth init response data");return{authorize_url:t.authorize_url,expires_at:t.expires_at,flow_id:t.flow_id,poll_interval_sec:t.poll_interval_sec,poll_token:t.poll_token}}function q7s(e){let t=KOe(e),n=t?.status;if(n==="pending"||n==="failed")return{status:n};if(n==="ready"&&t)return W7s(t);throw new Q7("Invalid OAuth poll response data")}function W7s(e){let t=KOe(e.user),n=KOe(e.zai);if(typeof e.token!="string"||!t||typeof t.user_id!="string"||!n||typeof n.access_token!="string")throw new Q7("Invalid OAuth ready response data");return{status:"ready",token:e.token,user:{...typeof t.avatar=="string"?{avatar:t.avatar}:{},...typeof t.email=="string"?{email:t.email}:{},...typeof t.name=="string"?{name:t.name}:{},user_id:t.user_id},zai:{access_token:n.access_token}}}function V7s(e,t){try{return JSON.parse(e)}catch{let r=typeof t=="number"&&(t<200||t>=300)?`OAuth HTTP error ${t} (empty or non-JSON response)`:"OAuth response is not valid JSON";throw new Q7(r,{httpStatus:t})}}function KOe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}var VZr,F7s,j7s,B7s,U7s,Q7,GZr=Y(()=>{"use strict";VZr=require("node:crypto"),F7s="https://zcode.z.ai/api/v1",j7s="zai",B7s=32,U7s="application/json",Q7=class extends Error{static{r(this,"ZaiCliOAuthError")}businessCode;httpStatus;constructor(t,n={}){super(t),this.name="ZaiCliOAuthError",this.businessCode=n.businessCode,this.httpStatus=n.httpStatus}};r(Xdn,"createZaiCliOAuthClient");r(HZr,"createZaiCliOAuthPollToken");r(z7s,"normalizeBaseUrl");r(WZr,"requestJsonEnvelope");r($7s,"parseInitData");r(q7s,"parsePollData");r(W7s,"parseReadyData");r(V7s,"parseJson");r(KOe,"asRecord")});function ZZr(e={}){let t=K7s(Z7s(e.env??process.env));return{decrypt(n){if(!J7s(n))return n;let s=n.slice(Qdn.length).split("."),[a,l,u]=s;if(!a||!l||!u||s.length!==3)throw new Error("Credential decrypt failed: invalid ciphertext format");let f=Buffer.from(a,"base64url"),g=Buffer.from(l,"base64url"),_=Buffer.from(u,"base64url");if(f.length!==KZr)throw new Error("Credential decrypt failed: invalid IV length");if(g.length!==H7s)throw new Error("Credential decrypt failed: invalid auth tag length");try{let b=(0,vG.createDecipheriv)(JZr,t,f);return b.setAuthTag(g),Buffer.concat([b.update(_),b.final()]).toString("utf-8")}catch(b){throw new Error("Credential decrypt failed: key mismatch or corrupted ciphertext",{cause:b})}},encrypt(n){let o=(0,vG.randomBytes)(KZr),s=(0,vG.createCipheriv)(JZr,t,o),a=Buffer.concat([s.update(n,"utf-8"),s.final()]),l=s.getAuthTag();return[Qdn,o.toString("base64url"),".",l.toString("base64url"),".",a.toString("base64url")].join("")}}}function J7s(e){return e.startsWith(Qdn)}function K7s(e){return(0,vG.createHash)("sha256").update(e).digest()}function Z7s(e){let t=e[G7s]?.trim();if(t)return t;let n="unknown";try{n=(0,oge.userInfo)().username}catch{}return`zcode-credential-fallback:${(0,oge.platform)()}:${(0,oge.homedir)()}:${n}`}var vG,oge,Qdn,JZr,KZr,H7s,G7s,epn=Y(()=>{"use strict";vG=require("node:crypto"),oge=require("node:os"),Qdn="enc:v1:",JZr="aes-256-gcm",KZr=12,H7s=16,G7s="ZCODE_CREDENTIAL_SECRET";r(ZZr,"createZCodeCredentialCipher");r(J7s,"isEncryptedZCodeCredentialValue");r(K7s,"deriveCipherKey");r(Z7s,"resolveCredentialSecret")});function Q7s(e,t){let n=new Error(`OAuth authorization was rejected by the authorization server: ${e}`);return n.code=X7s,n.oauthError=e,t&&(n.oauthErrorDescription=t),n}async function YOe(e){let t=r(()=>{},"resolveCallback"),n=r(()=>{},"rejectCallback"),o=!1,s=new Promise((f,g)=>{t=f,n=g}),a=(0,XZr.createServer)((f,g)=>{try{let _=new URL(f.url??"/",`http://${tpn}`);if(_.pathname!==e.callbackPath){ige(g,404,ZOe);return}if((_.searchParams.get("state")??"")!==e.state){ige(g,400,ZOe);return}let w=_.searchParams.get("error");if(w){ige(g,400,ZOe),o||(o=!0,n(Q7s(w,_.searchParams.get("error_description"))));return}let T=_.searchParams.get("authCode")??_.searchParams.get("code")??"";if(!T){ige(g,400,ZOe),o||(o=!0,n(new Error("OAuth callback is missing an authorization code.")));return}ige(g,200,Y7s),o||(o=!0,t({code:T,url:_.toString()}))}catch(_){ige(g,500,ZOe),o||(o=!0,n(_ instanceof Error?_:new Error(String(_))))}});await new Promise((f,g)=>{a.once("error",g),a.listen(0,tpn,()=>{a.off("error",g),f()})});let l=a.address();if(!e$s(l))throw await YZr(a),new Error("Unable to resolve localhost callback server address.");let u=`http://${tpn}:${l.port}${e.callbackPath}`;return{callbackPath:e.callbackPath,callbackUrl:u,close:r(async()=>{await YZr(a)},"close"),waitForCallback:r(()=>s,"waitForCallback")}}function ige(e,t,n){e.writeHead(t,{"Content-Type":"text/plain; charset=utf-8"}),e.end(n)}function YZr(e){return e.listening?new Promise((t,n)=>{e.close(o=>{if(o){n(o);return}t()})}):Promise.resolve()}function e$s(e){return typeof e=="object"&&e!==null&&"port"in e}var XZr,tpn,Y7s,ZOe,X7s,Tct=Y(()=>{"use strict";XZr=require("node:http"),tpn="127.0.0.1",Y7s="Authorization successful! You may close this window and return to the CLI.",ZOe="Authorization failed. You may close this window and return to the CLI.",X7s="MCP_OAUTH_CALLBACK_DENIED";r(Q7s,"createCallbackDeniedError");r(YOe,"createLocalhostOAuthCallbackServer");r(ige,"writeText");r(YZr,"closeServer");r(e$s,"isAddressInfo")});function jM(e={}){let t=e.env??process.env,n=n$s(e),o=e.cipher??ZZr({env:t});return{filePath:n,async clearZaiLoginCredentials(){await e$(n,async s=>{let a=s[R1.activeProvider],l=a?o.decrypt(a):null;delete s[R1.zaiAccessToken],delete s[R1.zaiRefreshToken],delete s[R1.zaiUserInfo],delete s[R1.zcodeJwtToken],l===QZr&&delete s[R1.activeProvider]})},async delete(s){let a=VF(s);await e$(n,l=>{delete l[a]})},async deleteIfValue(s,a){let l=VF(s),u=bG(a),f=!1;return await e$(n,g=>{let _=g[l];_===void 0||o.decrypt(_)!==u||(delete g[l],f=!0)}),f},async deleteIfValues(s){let a=Object.entries(s).map(([u,f])=>[VF(u),bG(f)]);if(a.length===0)return{};let l={};return await e$(n,u=>{for(let[f,g]of a){let _=u[f],b=_!==void 0&&o.decrypt(_)===g;l[f]=b,b&&delete u[f]}}),l},async deleteManyIfValue(s,a,l){let u=VF(s),f=bG(a),g=l.map(VF),_=!1;return await e$(n,b=>{let w=b[u];if(!(w===void 0||o.decrypt(w)!==f)){for(let T of g)delete b[T];_=!0}}),_},async load(s){let l=(await npn(n))[VF(s)];return l===void 0?null:o.decrypt(l)},async loadMany(s){let a=s.map(VF),l=await npn(n);return Object.fromEntries(a.map(u=>{let f=l[u];return[u,f===void 0?null:o.decrypt(f)]}))},onDidChange(s){let a=Ict.get(n);return a||(a=new Set,Ict.set(n,a)),a.add(s),()=>{a?.delete(s),a?.size===0&&Ict.delete(n)}},async save(s,a){let l=VF(s),u=o.encrypt(bG(a));await e$(n,f=>{f[l]=u})},async saveMany(s){let a=Object.entries(s).map(([l,u])=>[VF(l),o.encrypt(bG(u))]);await e$(n,l=>{for(let[u,f]of a)l[u]=f})},async saveReplacing(s,a,l){let u=VF(s),f=o.encrypt(bG(a)),g=l.map(VF);await e$(n,_=>{_[u]=f;for(let b of g)b!==u&&delete _[b]})},async saveZaiLoginCredentials(s){let a={activeProvider:o.encrypt(QZr),accessToken:o.encrypt(bG(s.accessToken)),jwtToken:o.encrypt(bG(s.jwtToken)),userInfo:o.encrypt(JSON.stringify(s.user))};await e$(n,l=>{l[R1.activeProvider]=a.activeProvider,l[R1.zaiAccessToken]=a.accessToken,l[R1.zcodeJwtToken]=a.jwtToken,l[R1.zaiUserInfo]=a.userInfo})}}}function n$s(e={}){if(e.filePath)return eYr(e.filePath);let t=e.env??process.env,n=e.baseDir??t[t$s]??(0,Cct.homedir)();return(0,XOe.join)(eYr(n),".zcode","v2","credentials.json")}async function npn(e){let t;try{t=await(0,tYr.readFile)(e,"utf-8")}catch(n){if(o$s(n)==="ENOENT")return{};throw new Error(`Unable to read shared ZCode credentials: ${e}`,{cause:n})}try{return r$s(JSON.parse(t))}catch(n){let o=await Gqt(e).catch(()=>{}),s=o?` Backup: ${o}`:"";throw new Error(`Shared ZCode credentials are corrupt: ${e}.${s}`,{cause:n})}}async function e$(e,t){await lw(e,async()=>{let o=await npn(e);await t(o),await qL(e,`${JSON.stringify(o,null,2)}
|
|
2136
|
+
`):e}function _7s(e,t,n){let o=_Gr(e);if(o!==void 0){for(let a of o)Eat(n);return o}let s=(0,Bk.join)(e,"cache",Yp);try{let a=[];for(let l of(0,WF.readdirSync)(s,{withFileTypes:!0})){if(Eat(n),!l.isDirectory())continue;let u=(0,Bk.join)(s,l.name);for(let f of(0,WF.readdirSync)(u,{withFileTypes:!0}))f.isDirectory()&&a.push((0,Bk.join)(u,f.name))}return a}catch(a){return Cat(a)?[]:(t.push({code:"plugin_root_not_found",message:a instanceof Error?a.message:`Failed to scan ${s}`,path:s,severity:"warning"}),[])}}function y7s(e,t){if(!$v(e.rootPath))return t.push({code:"plugin_root_not_found",message:`Plugin root does not exist: ${e.rootPath}`,path:e.rootPath,severity:"warning"}),null;let n=v7s(e.rootPath);if(!n)return t.push({code:"plugin_manifest_not_found",message:`Plugin manifest not found: ${e.rootPath}`,path:e.rootPath,severity:"error"}),null;let o=b7s(n,t);return o?{id:`${o.name}@${e.marketplace}`,manifest:o,manifestPath:n,marketplace:e.marketplace,rootPath:e.rootPath,source:e.source}:null}function v7s(e){let t=(0,Bk.join)(e,qzs);if(bw(t))return t;let n=(0,Bk.join)(e,Wzs);if(bw(n))return n;let o=(0,Bk.join)(e,Vzs);return bw(o)?o:null}function b7s(e,t){try{let n=JSON.parse((0,WF.readFileSync)(e,"utf8"));if(!fu(n))throw new Error("Manifest must be a JSON object");let o=typeof n.name=="string"?n.name.trim():"";if(!Kzs.test(o))throw new Error(`Invalid plugin name: ${o}`);return{...n,name:o,version:typeof n.version=="string"?n.version:Hzs}}catch(n){return t.push({code:"plugin_manifest_invalid",message:n instanceof Error?n.message:`Invalid plugin manifest: ${e}`,path:e,severity:"error"}),null}}function S7s(){return{commandRoots:[],diagnostics:[],hooks:{},mcpServers:{},plugins:[],skillRoots:[]}}function w7s(e=[]){return{commandRoots:[],hooks:{},hookDetails:e,mcpServers:{},skillCount:0,skillRoots:[]}}function k7s(e,t,n){return e.enabledPlugins[t]??n}var WF,Bk,qzs,Wzs,Vzs,Hzs,Gzs,Jzs,Kzs,Zzs,Yzs,Kdn,GOe=Y(()=>{"use strict";WF=require("node:fs"),Bk=require("node:path");nr();q7();kat();Rat();Dun();Mun();Edn();Mat();Edn();Mat();sdn();EZr();qzs=(0,Bk.join)(".zcode-plugin","plugin.json"),Wzs=(0,Bk.join)(".claude-plugin","plugin.json"),Vzs=(0,Bk.join)(".codex-plugin","plugin.json"),Hzs="0.0.0",Gzs=1e3,Jzs=10,Kzs=/^[a-z0-9][a-z0-9._-]{0,127}$/,Zzs=["channels","lspServers","outputStyles","settings"],Yzs=new Set(Object.values(Tl)),Kdn=class{static{r(this,"NodePluginAdapter")}options;constructor(t){this.options=t}async discoverPlugins(t,n){return this.discoverPluginsSync(t,n)}discoverPluginsSync(t,n){if(!t.config.enabled)return S7s();let o=[],s=(0,Bk.join)(t.storageRoot||this.options.storageRoot,"data"),a=this.resolveCandidates(t,o,n),l=[],u={},f={},g=[],_=new Set,b=[],w=Gzs;for(let T of a){Eat(n);let I=y7s(T,o);if(!I||I.source==="official"&&t.config.suppressedBuiltins.includes(I.id))continue;if(_.has(I.id)){o.push({code:"plugin_duplicate_id",message:`Duplicate plugin ignored: ${I.id}`,path:I.rootPath,pluginId:I.id,severity:"warning"});continue}_.add(I.id),n7s(I,o);let E=T.defaultEnabled||(t.officialPluginsEnabledByDefault?.has(I.id)??!1),R=k7s(t.config,I.id,E),L=(0,Bk.join)(s,$7(I.id)),U=gre({diagnostics:o,loaded:I}),B=t7s(I),z=s7s({dataPath:L,diagnostics:o,loaded:I,runnable:B}),$=R?e7s({dataPath:L,diagnostics:o,env:t.env??{},hookEvents:B?z.events:{},hookDetails:z.details,loaded:I,mcpServerDefinitions:U,options:t.config.options[I.id]??{},priority:w,workingDirectory:t.workingDirectory}):w7s(z.details);w+=Jzs,Object.assign(f,$.mcpServers),AZr(u,$.hooks),b.push(...$.skillRoots),l.push(...$.commandRoots),g.push(Qzs(I,$,L,R,Object.keys(U),t.config.options[I.id]??{}))}return{commandRoots:l,diagnostics:o,hooks:u,mcpServers:f,plugins:g,skillRoots:b}}resolveCandidates(t,n,o){let s=[];for(let a of t.config.dirs)s.push({defaultEnabled:!0,marketplace:OZn,rootPath:(0,Bk.resolve)(a),source:"inline"});for(let a of t.officialPluginRoots??[])s.push({defaultEnabled:!1,marketplace:Yp,rootPath:(0,Bk.resolve)(a),source:"official"});s.push(..._7s(t.storageRoot,n,o).map(a=>({defaultEnabled:!1,marketplace:Yp,rootPath:a,source:"official"})));for(let a of X7(t.storageRoot))s.push({defaultEnabled:!1,marketplace:a.marketplace,rootPath:ydn(t.storageRoot,a),source:"cache"});return s}};r(Xzs,"createNodePluginAdapter");r(wct,"discoverNodePluginsSync");r(Qzs,"createPluginMetadata");r(e7s,"resolveEnabledComponents");r(t7s,"canRunPluginHooks");r(n7s,"warnUnsupportedComponents");r(r7s,"resolveSkillRoots");r(o7s,"warnEmptyDeclaredSkillRoots");r(i7s,"resolveCommandRoots");r(s7s,"inspectPluginHooks");r(a7s,"parsePluginHookEvents");r(c7s,"toPluginHookDetail");r(Zdn,"createHookPluginContext");r(l7s,"attachPluginToHook");r(AZr,"mergeHookEvents");r(u7s,"mergeHookInspection");r(PZr,"emptyHookInspection");r(d7s,"countSkillFiles");r(RZr,"resolveComponentRoots");r(p7s,"materializeCommandMetadataRoot");r(f7s,"normalizeGeneratedCommandName");r(m7s,"trimRelativePrefix");r(h7s,"applyCommandMetadataFrontmatter");r(g7s,"stripMarkdownFrontmatter");r(_7s,"scanOfficialCache");r(y7s,"loadPlugin");r(v7s,"findManifest");r(b7s,"readManifest");r(S7s,"emptyOutcome");r(w7s,"emptyComponents");r(k7s,"resolveEnabled")});function OZr(e){let t=e.appId??I7s,n=e.appSecret?.trim()??"",o=e.authorizeUrl??Hpe(process.env,x7s),s=e.tokenUrl??Hpe(process.env,T7s);return{buildAuthorizeUrl(a){let l=new URLSearchParams({appId:t,redirect:a.redirectUri,state:a.state});return`${o}?${l.toString()}`},async exchangeCode(a,l){if(!n)throw new kct("BigModel OAuth appSecret is required.");let u=await e.httpClient.request({body:new TextEncoder().encode(JSON.stringify({appId:t,appSecret:n,authCode:a.code})),headers:{"Content-Type":E7s},maxResponseBytes:64*1024,method:"POST",trace:e.trace,url:s},l),f=JSON.parse(new TextDecoder().decode(u.body)),g=f.data?.accessToken?.trim()??"";if(!g)throw new kct(f.msg??"BigModel token response is missing accessToken.");return{accessToken:g,...f.data?.refreshToken?{refreshToken:f.data.refreshToken}:{}}}}}function MZr(){return(0,DZr.randomBytes)(C7s).toString("hex")}var DZr,x7s,T7s,I7s,C7s,E7s,kct,NZr=Y(()=>{"use strict";DZr=require("node:crypto");ms();x7s="/login",T7s="/api/auth/tokenByAuthCode",I7s="zcode",C7s=32,E7s="application/json",kct=class extends Error{static{r(this,"BigmodelOAuthError")}constructor(t,n={}){super(t,n),this.name="BigmodelOAuthError"}};r(OZr,"createBigmodelOAuthClient");r(MZr,"createBigmodelOAuthState")});async function Ydn(e,t={}){let n=t.platform??process.platform,o=P7s(n,e),s=t.spawnProcess??LZr.spawn;try{let a=s(o.executable,o.args,{detached:!0,stdio:"ignore",windowsHide:!0});return await R7s(a,o.executable,t.timeoutMs)}catch(a){return{command:o.executable,opened:!1,reason:a instanceof Error?a.message:String(a)}}}function P7s(e,t){return e==="darwin"?{executable:"open",args:[t]}:e==="win32"?{executable:"cmd.exe",args:["/c","start","",t]}:{executable:"xdg-open",args:[t]}}function R7s(e,t,n=A7s){return new Promise(o=>{let s=!1,a,l=r(u=>{s||(s=!0,clearTimeout(a),e.removeAllListeners("error"),e.removeAllListeners("spawn"),u.opened&&e.unref(),o(u))},"settle");a=setTimeout(()=>{l({command:t,opened:!0})},n),e.once("spawn",()=>{l({command:t,opened:!0})}),e.once("error",u=>{l({command:t,opened:!1,reason:u.message})})})}var LZr,A7s,FZr=Y(()=>{"use strict";LZr=require("node:child_process"),A7s=1e3;r(Ydn,"openUrlInBrowser");r(P7s,"browserOpenCommand");r(R7s,"waitForBrowserSpawn")});function $Zr(e){return{async resolve(t,n){let o=t.accessToken.trim();if(!o)throw new yG("OAuth access token is required.");if(t.family==="bigmodel")return BZr({authorization:o,host:XAe(process.env),httpClient:e.httpClient,trace:e.trace},n);let s=await M7s(e,o,n);return BZr({authorization:`Bearer ${s}`,host:UZr,httpClient:e.httpClient,requireSecretKey:!0,trace:e.trace},n)}}}async function M7s(e,t,n){let o=await JOe(e.httpClient,{body:new TextEncoder().encode(JSON.stringify({token:t})),headers:{"Content-Type":zZr},method:"POST",trace:e.trace,url:`${UZr}/api/auth/z/login`},n),s=o?.access_token?.trim()??o?.accessToken?.trim()??"";if(!s)throw new yG("Z.AI biz token response is missing access_token.");return s}async function BZr(e,t){let n=await JOe(e.httpClient,{headers:xct(e.authorization),method:"GET",trace:e.trace,url:`${e.host}/api/biz/customer/getCustomerInfo`},t),o=N7s(n);if(!o)throw new yG("Unable to resolve organization and project.");let s=`${e.host}/api/biz/v1/organization/${o.organizationId}/projects/${o.projectId}/api_keys`,u=((await JOe(e.httpClient,{headers:xct(e.authorization),method:"GET",trace:e.trace,url:s},t)??[]).find(_=>_.name===jZr)??await JOe(e.httpClient,{body:new TextEncoder().encode(JSON.stringify({name:jZr})),headers:xct(e.authorization),method:"POST",trace:e.trace,url:s},t))?.apiKey?.trim()??"";if(!u)throw new yG("API key response is missing apiKey.");let g=(await JOe(e.httpClient,{headers:xct(e.authorization),method:"GET",trace:e.trace,url:`${s}/copy/${encodeURIComponent(u)}`},t))?.secretKey?.trim()??"";if(!g){if(e.requireSecretKey)throw new yG("API key copy response is missing secretKey.");return u}return`${u}.${g}`}async function JOe(e,t,n){let o=await e.request({maxResponseBytes:65536,...t},n),s=JSON.parse(new TextDecoder().decode(o.body));if(!L7s(s.code))throw new yG(s.msg??`Remote business error ${s.code}`);return s.data??null}function xct(e){return{Authorization:e,"Content-Type":zZr}}function N7s(e){let t=e?.organizations??[],n=t.find(a=>a.organizationName?.includes(D7s))??t[0],o=n?.projects??[],s=o.find(a=>a.projectName?.includes(O7s))??o[0];return!n?.organizationId||!s?.projectId?null:{organizationId:n.organizationId,projectId:s.projectId}}function L7s(e){return e==null||e===0||e===200||e==="0"||e==="200"}var UZr,zZr,jZr,D7s,O7s,yG,qZr=Y(()=>{"use strict";ms();UZr="https://api.z.ai",zZr="application/json",jZr="zcode-api-key",D7s="\u9ED8\u8BA4\u673A\u6784",O7s="\u9ED8\u8BA4\u9879\u76EE",yG=class extends Error{static{r(this,"CodingPlanApiKeyError")}constructor(t,n={}){super(t,n),this.name="CodingPlanApiKeyError"}};r($Zr,"createCodingPlanApiKeyResolver");r(M7s,"resolveZaiBizToken");r(BZr,"resolveBizApiKey");r(JOe,"requestRemoteData");r(xct,"createBizAuthHeaders");r(N7s,"pickOrgAndProject");r(L7s,"isSuccessfulRemoteCode")});function Xdn(e){let t=z7s(e.baseUrl??F7s),n=new TextEncoder;return{async init(o,s){let a=await WZr(e.httpClient,{body:n.encode(JSON.stringify({provider:j7s})),headers:{Authorization:`Bearer ${o.pollToken}`,"Content-Type":U7s},method:"POST",trace:e.trace,url:`${t}/oauth/cli/init`},s);return $7s(a.data)},async poll(o,s){let a=encodeURIComponent(o.flowId),l=await WZr(e.httpClient,{headers:{Authorization:`Bearer ${o.pollToken}`},method:"GET",trace:e.trace,url:`${t}/oauth/cli/poll/${a}`},s);return q7s(l.data)}}}function HZr(){return(0,VZr.randomBytes)(B7s).toString("hex")}function z7s(e){return e.replace(/\/+$/u,"")}async function WZr(e,t,n){let o=await e.request({maxResponseBytes:65536,...t},n),s=new TextDecoder().decode(o.body),a=V7s(s,o.status),l=KOe(a);if(!l||typeof l.code!="number")throw new Q7("Invalid OAuth response envelope",{httpStatus:o.status});let u=typeof l.msg=="string"?l.msg:void 0;if(o.status<200||o.status>=300)throw new Q7(u??`OAuth HTTP error ${o.status}`,{businessCode:l.code,httpStatus:o.status});if(l.code!==0)throw new Q7(u??`OAuth business error ${l.code}`,{businessCode:l.code,httpStatus:o.status});return{code:l.code,data:l.data,msg:u}}function $7s(e){let t=KOe(e);if(!t||typeof t.flow_id!="string"||typeof t.poll_token!="string"||typeof t.authorize_url!="string"||typeof t.expires_at!="number"||typeof t.poll_interval_sec!="number")throw new Q7("Invalid OAuth init response data");return{authorize_url:t.authorize_url,expires_at:t.expires_at,flow_id:t.flow_id,poll_interval_sec:t.poll_interval_sec,poll_token:t.poll_token}}function q7s(e){let t=KOe(e),n=t?.status;if(n==="pending"||n==="failed")return{status:n};if(n==="ready"&&t)return W7s(t);throw new Q7("Invalid OAuth poll response data")}function W7s(e){let t=KOe(e.user),n=KOe(e.zai);if(typeof e.token!="string"||!t||typeof t.user_id!="string"||!n||typeof n.access_token!="string")throw new Q7("Invalid OAuth ready response data");return{status:"ready",token:e.token,user:{...typeof t.avatar=="string"?{avatar:t.avatar}:{},...typeof t.email=="string"?{email:t.email}:{},...typeof t.name=="string"?{name:t.name}:{},user_id:t.user_id},zai:{access_token:n.access_token}}}function V7s(e,t){try{return JSON.parse(e)}catch{let r=typeof t=="number"&&(t<200||t>=300)?`OAuth HTTP error ${t} (empty or non-JSON response)`:"OAuth response is not valid JSON";throw new Q7(r,{httpStatus:t})}}function KOe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}var VZr,F7s,j7s,B7s,U7s,Q7,GZr=Y(()=>{"use strict";VZr=require("node:crypto"),F7s="https://zcode.z.ai/api/v1",j7s="zai",B7s=32,U7s="application/json",Q7=class extends Error{static{r(this,"ZaiCliOAuthError")}businessCode;httpStatus;constructor(t,n={}){super(t),this.name="ZaiCliOAuthError",this.businessCode=n.businessCode,this.httpStatus=n.httpStatus}};r(Xdn,"createZaiCliOAuthClient");r(HZr,"createZaiCliOAuthPollToken");r(z7s,"normalizeBaseUrl");r(WZr,"requestJsonEnvelope");r($7s,"parseInitData");r(q7s,"parsePollData");r(W7s,"parseReadyData");r(V7s,"parseJson");r(KOe,"asRecord")});function ZZr(e={}){let t=K7s(Z7s(e.env??process.env));return{decrypt(n){if(!J7s(n))return n;let s=n.slice(Qdn.length).split("."),[a,l,u]=s;if(!a||!l||!u||s.length!==3)throw new Error("Credential decrypt failed: invalid ciphertext format");let f=Buffer.from(a,"base64url"),g=Buffer.from(l,"base64url"),_=Buffer.from(u,"base64url");if(f.length!==KZr)throw new Error("Credential decrypt failed: invalid IV length");if(g.length!==H7s)throw new Error("Credential decrypt failed: invalid auth tag length");try{let b=(0,vG.createDecipheriv)(JZr,t,f);return b.setAuthTag(g),Buffer.concat([b.update(_),b.final()]).toString("utf-8")}catch(b){throw new Error("Credential decrypt failed: key mismatch or corrupted ciphertext",{cause:b})}},encrypt(n){let o=(0,vG.randomBytes)(KZr),s=(0,vG.createCipheriv)(JZr,t,o),a=Buffer.concat([s.update(n,"utf-8"),s.final()]),l=s.getAuthTag();return[Qdn,o.toString("base64url"),".",l.toString("base64url"),".",a.toString("base64url")].join("")}}}function J7s(e){return e.startsWith(Qdn)}function K7s(e){return(0,vG.createHash)("sha256").update(e).digest()}function Z7s(e){let t=e[G7s]?.trim();if(t)return t;let n="unknown";try{n=(0,oge.userInfo)().username}catch{}return`zcode-credential-fallback:${(0,oge.platform)()}:${(0,oge.homedir)()}:${n}`}var vG,oge,Qdn,JZr,KZr,H7s,G7s,epn=Y(()=>{"use strict";vG=require("node:crypto"),oge=require("node:os"),Qdn="enc:v1:",JZr="aes-256-gcm",KZr=12,H7s=16,G7s="ZCODE_CREDENTIAL_SECRET";r(ZZr,"createZCodeCredentialCipher");r(J7s,"isEncryptedZCodeCredentialValue");r(K7s,"deriveCipherKey");r(Z7s,"resolveCredentialSecret")});function Q7s(e,t){let n=new Error(`OAuth authorization was rejected by the authorization server: ${e}`);return n.code=X7s,n.oauthError=e,t&&(n.oauthErrorDescription=t),n}async function YOe(e){let t=r(()=>{},"resolveCallback"),n=r(()=>{},"rejectCallback"),o=!1,s=new Promise((f,g)=>{t=f,n=g}),a=(0,XZr.createServer)((f,g)=>{try{let _=new URL(f.url??"/",`http://${tpn}`);if(_.pathname!==e.callbackPath){ige(g,404,ZOe);return}if((_.searchParams.get("state")??"")!==e.state){ige(g,400,ZOe);return}let w=_.searchParams.get("error");if(w){ige(g,400,ZOe),o||(o=!0,n(Q7s(w,_.searchParams.get("error_description"))));return}let T=_.searchParams.get("authCode")??_.searchParams.get("code")??"";if(!T){ige(g,400,ZOe),o||(o=!0,n(new Error("OAuth callback is missing an authorization code.")));return}ige(g,200,Y7s),o||(o=!0,t({code:T,url:_.toString()}))}catch(_){ige(g,500,ZOe),o||(o=!0,n(_ instanceof Error?_:new Error(String(_))))}});await new Promise((f,g)=>{a.once("error",g),a.listen(0,tpn,()=>{a.off("error",g),f()})});let l=a.address();if(!e$s(l))throw await YZr(a),new Error("Unable to resolve localhost callback server address.");let u=`http://${tpn}:${l.port}${e.callbackPath}`;return{callbackPath:e.callbackPath,callbackUrl:u,close:r(async()=>{await YZr(a)},"close"),waitForCallback:r(()=>s,"waitForCallback")}}function ige(e,t,n){e.writeHead(t,{"Content-Type":"text/plain; charset=utf-8"}),e.end(n)}function YZr(e){return e.listening?new Promise((t,n)=>{e.close(o=>{if(o){n(o);return}t()})}):Promise.resolve()}function e$s(e){return typeof e=="object"&&e!==null&&"port"in e}var XZr,tpn,Y7s,ZOe,X7s,Tct=Y(()=>{"use strict";XZr=require("node:http"),tpn="127.0.0.1",Y7s="Authorization successful! You may close this window and return to the CLI.",ZOe="Authorization failed. You may close this window and return to the CLI.",X7s="MCP_OAUTH_CALLBACK_DENIED";r(Q7s,"createCallbackDeniedError");r(YOe,"createLocalhostOAuthCallbackServer");r(ige,"writeText");r(YZr,"closeServer");r(e$s,"isAddressInfo")});function jM(e={}){let t=e.env??process.env,n=n$s(e),o=e.cipher??ZZr({env:t});return{filePath:n,async clearZaiLoginCredentials(){await e$(n,async s=>{let a=s[R1.activeProvider],l=a?o.decrypt(a):null;delete s[R1.zaiAccessToken],delete s[R1.zaiRefreshToken],delete s[R1.zaiUserInfo],delete s[R1.zcodeJwtToken],l===QZr&&delete s[R1.activeProvider]})},async delete(s){let a=VF(s);await e$(n,l=>{delete l[a]})},async deleteIfValue(s,a){let l=VF(s),u=bG(a),f=!1;return await e$(n,g=>{let _=g[l];_===void 0||o.decrypt(_)!==u||(delete g[l],f=!0)}),f},async deleteIfValues(s){let a=Object.entries(s).map(([u,f])=>[VF(u),bG(f)]);if(a.length===0)return{};let l={};return await e$(n,u=>{for(let[f,g]of a){let _=u[f],b=_!==void 0&&o.decrypt(_)===g;l[f]=b,b&&delete u[f]}}),l},async deleteManyIfValue(s,a,l){let u=VF(s),f=bG(a),g=l.map(VF),_=!1;return await e$(n,b=>{let w=b[u];if(!(w===void 0||o.decrypt(w)!==f)){for(let T of g)delete b[T];_=!0}}),_},async load(s){let l=(await npn(n))[VF(s)];return l===void 0?null:o.decrypt(l)},async loadMany(s){let a=s.map(VF),l=await npn(n);return Object.fromEntries(a.map(u=>{let f=l[u];return[u,f===void 0?null:o.decrypt(f)]}))},onDidChange(s){let a=Ict.get(n);return a||(a=new Set,Ict.set(n,a)),a.add(s),()=>{a?.delete(s),a?.size===0&&Ict.delete(n)}},async save(s,a){let l=VF(s),u=o.encrypt(bG(a));await e$(n,f=>{f[l]=u})},async saveMany(s){let a=Object.entries(s).map(([l,u])=>[VF(l),o.encrypt(bG(u))]);await e$(n,l=>{for(let[u,f]of a)l[u]=f})},async saveReplacing(s,a,l){let u=VF(s),f=o.encrypt(bG(a)),g=l.map(VF);await e$(n,_=>{_[u]=f;for(let b of g)b!==u&&delete _[b]})},async saveZaiLoginCredentials(s){let a={activeProvider:o.encrypt(QZr),accessToken:o.encrypt(bG(s.accessToken)),jwtToken:o.encrypt(bG(s.jwtToken)),userInfo:o.encrypt(JSON.stringify(s.user))};await e$(n,l=>{l[R1.activeProvider]=a.activeProvider,l[R1.zaiAccessToken]=a.accessToken,l[R1.zcodeJwtToken]=a.jwtToken,l[R1.zaiUserInfo]=a.userInfo})}}}function n$s(e={}){e={...e,filePath:e.filePath??(e.env??process.env).ZCODE_CLI_CREDENTIALS_FILE?.trim()};if(e.filePath)return eYr(e.filePath);let t=e.env??process.env,n=e.baseDir??t[t$s]??(0,Cct.homedir)();return(0,XOe.join)(eYr(n),".zcode","v2","credentials.json")}async function npn(e){let t;try{t=await(0,tYr.readFile)(e,"utf-8")}catch(n){if(o$s(n)==="ENOENT")return{};throw new Error(`Unable to read shared ZCode credentials: ${e}`,{cause:n})}try{return r$s(JSON.parse(t))}catch(n){let o=await Gqt(e).catch(()=>{}),s=o?` Backup: ${o}`:"";throw new Error(`Shared ZCode credentials are corrupt: ${e}.${s}`,{cause:n})}}async function e$(e,t){await lw(e,async()=>{let o=await npn(e);await t(o),await qL(e,`${JSON.stringify(o,null,2)}
|
|
2137
2137
|
`)});let n=[...Ict.get(e)??[]];await Promise.allSettled(n.map(o=>o()))}function r$s(e){if(!i$s(e))throw new Error("Credential record must be an object");let t={};for(let[n,o]of Object.entries(e)){if(typeof o!="string")throw new Error(`Credential record value must be a string: ${n}`);t[n]=o}return t}function o$s(e){if(typeof e!="object"||e===null||!("code"in e))return;let t=e.code;return typeof t=="string"?t:void 0}function VF(e){let t=e.trim();if(t.length===0)throw new Error("Credential key must not be empty");return t}function bG(e){if(e.length===0)throw new Error("Credential value must not be empty");return e}function eYr(e){return e==="~"?(0,Cct.homedir)():e.startsWith("~/")?(0,XOe.join)((0,Cct.homedir)(),e.slice(2)):(0,XOe.resolve)(e)}function i$s(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var tYr,Cct,XOe,t$s,QZr,Ict,R1,Ect=Y(()=>{"use strict";tYr=require("node:fs/promises"),Cct=require("node:os"),XOe=require("node:path");bz();epn();t$s="ZCODE_DATA_BASE_DIR",QZr="zai",Ict=new Map,R1={activeProvider:"oauth:active_provider",bigmodelAccessToken:"oauth:bigmodel:access_token",bigmodelRefreshToken:"oauth:bigmodel:refresh_token",bigmodelUserInfo:"oauth:bigmodel:user_info",zaiAccessToken:"oauth:zai:access_token",zaiRefreshToken:"oauth:zai:refresh_token",zaiUserInfo:"oauth:zai:user_info",zcodeJwtToken:"zcodejwttoken"};r(jM,"createSharedZCodeCredentialStore");r(n$s,"resolveSharedZCodeCredentialsPath");r(npn,"readRawCredentialRecord");r(e$,"mutateRawCredentialRecord");r(r$s,"parseCredentialRecord");r(o$s,"getErrorCode");r(VF,"validateCredentialKey");r(bG,"validateCredentialValue");r(eYr,"resolveUserPath");r(i$s,"isRecord")});var rpn=Y(()=>{"use strict";NZr();FZr();qZr();GZr();epn();Tct();Ect()});function nYr(e,t){return{id:e,generation:t,type:"cdp",name:"ZCode Headless Chromium",capabilities:{browser:[],tab:[]},apiSupportOverrides:{"BrowserUser.openTabs":!1,"BrowserUser.history":!1,"PlaywrightAPI.waitForEvent":!1,"PlaywrightDownload.path":!1,"PlaywrightFileChooser.setFiles":!1,"PlaywrightLocator.downloadMedia":!1,"PlaywrightLocator.evaluate":!1,"CUAAPI.downloadMedia":!1,"DomCUAAPI.downloadMedia":!1},metadata:{provider:"zcode-cli",launchMode:"managed",headless:"true"}}}var rYr=Y(()=>{"use strict";r(nYr,"createManagedCdpDescriptor")});function c$s(e){return[e.PROGRAMFILES,e["PROGRAMFILES(X86)"],e.LOCALAPPDATA].filter(t=>!!t?.trim()).flatMap(t=>[(0,sge.join)(t,"Google","Chrome","Application","chrome.exe"),(0,sge.join)(t,"Chromium","Application","chrome.exe"),(0,sge.join)(t,"Microsoft","Edge","Application","msedge.exe")])}function oYr(e,t){try{return!(0,SG.existsSync)(e)||!(0,SG.statSync)(e).isFile()?!1:(t!=="win32"&&(0,SG.accessSync)(e,SG.constants.X_OK),!0)}catch{return!1}}function Act(e,t=process.platform){if(e===void 0)return;if(!(0,sge.isAbsolute)(e))throw new Error(`Browser executable path must be absolute: ${e}`);let n=e;if(!oYr(n,t))throw new Error(`Browser executable is missing or not executable: ${n}`);return n}function opn(e,t={}){let n=t.platform??process.platform,o=Act(t.executablePath,n);if(o)return o;let s=e.chromium.executablePath(),l=[...s?[s]:[],...n==="darwin"?a$s:n==="win32"?c$s(t.env??process.env):s$s].find(u=>oYr(u,n));if(l)return l;throw new Error("No installed Chrome or Chromium executable was found. Install Chromium or pass --browser-executable <absolute-path>.")}async function iYr(){return await import("playwright-core")}var SG,sge,s$s,a$s,ipn=Y(()=>{"use strict";SG=require("node:fs"),sge=require("node:path"),s$s=["/usr/bin/google-chrome-stable","/usr/bin/google-chrome","/usr/bin/chromium","/usr/bin/chromium-browser","/snap/bin/chromium"],a$s=["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"];r(c$s,"windowsBrowserPaths");r(oYr,"isUsableExecutable");r(Act,"validateExplicitBrowserExecutable");r(opn,"resolveInstalledBrowserExecutable");r(iYr,"loadPlaywrightChromium")});function Pct(e){return e===void 0?3e3:Math.min(3e3,Math.max(1,Math.floor(e)))}function l$s(e,t){return e.locator(t)}function sYr(e){return(e??[]).map(t=>t==="ControlOrMeta"?process.platform==="darwin"?"Meta":"Control":t)}async function spn(e,t,n,o,s){let a=await e.context().newCDPSession(e);try{let l=n==="function"?`(${t})(${JSON.stringify(o)})`:t,u=await a.send("Runtime.evaluate",{expression:l,awaitPromise:!0,returnByValue:!0,timeout:s});if(u.exceptionDetails){let f=u.exceptionDetails.exception?.description??u.exceptionDetails.text??"Playwright evaluate failed";throw new Error(`playwright.evaluate failed: ${f}`)}return u.result?.value}finally{await a.detach().catch(()=>{})}}async function u$s(e,t){let n=l$s(e,t.selector),o=Pct(t.timeoutMs);switch(t.operation){case"allTextContents":return await n.allTextContents();case"count":return await n.count();case"getAttribute":return await n.getAttribute(t.attribute??"",{timeout:o});case"innerText":return await n.innerText({timeout:o});case"isEnabled":return await n.isEnabled({timeout:o});case"isVisible":return await n.isVisible();case"textContent":return await n.textContent({timeout:o});case"click":await n.click({button:t.button,force:t.force,modifiers:sYr(t.modifiers),timeout:o});return;case"dblclick":await n.dblclick({button:t.button,force:t.force,modifiers:sYr(t.modifiers),timeout:o});return;case"fill":t.replace===!1?await n.pressSequentially(String(t.value??""),{timeout:o}):await n.fill(String(t.value??""),{timeout:o});return;case"press":await n.press(String(t.value??""),{timeout:o});return;case"selectOption":{let s=(t.selections??[]).map(a=>a.index!==void 0?{index:a.index}:a.label!==void 0?{label:a.label}:{value:a.value??""});await n.selectOption(s,{timeout:o});return}case"setChecked":await n.setChecked(t.checked??!0,{force:t.force,timeout:o});return;case"waitFor":await n.waitFor({state:t.state??"visible",timeout:o});return;case"downloadMedia":case"evaluate":throw new Error(`Playwright locator operation '${t.operation}' is unavailable`)}}async function aYr(e,t){switch(t.name){case"domSnapshot":return{ok:!0,value:await e.locator("html").ariaSnapshot({timeout:3e3})};case"elementInfo":return{ok:!0,value:await e.evaluate(({x:n,y:o,includeNonInteractable:s})=>document.elementsFromPoint(n,o).filter(a=>s||a.matches("a,button,input,select,textarea,[role],[tabindex]")).map(a=>{let l=a.getBoundingClientRect(),u=(a.innerText||a.textContent||"").trim();return{tagName:a.tagName.toLowerCase(),role:a.getAttribute("role"),visibleText:u||null,ariaName:a.getAttribute("aria-label")||u||null,testId:a.getAttribute("data-testid"),boundingBox:{x:l.x,y:l.y,width:l.width,height:l.height},preview:a.outerHTML.slice(0,300),selector:{primary:a.id?`#${a.id}`:a.tagName.toLowerCase(),candidates:[]}}}),t)};case"elementScreenshot":{let n="data-zcode-element-screenshot";if(await e.evaluate(({x:s,y:a,includeNonInteractable:l,markerAttribute:u})=>{let f=document.elementsFromPoint(s,a).filter(_=>l||_.matches("a,button,input,select,textarea,[role],[tabindex]")),g=0;for(let _ of f){let b=_.getBoundingClientRect();if(b.width<=0||b.height<=0)continue;let w=document.createElement("div");w.setAttribute(u,""),Object.assign(w.style,{border:"2px solid #ff2d55",boxSizing:"border-box",height:`${b.height}px`,left:`${b.left}px`,pointerEvents:"none",position:"fixed",top:`${b.top}px`,width:`${b.width}px`,zIndex:"2147483647"}),document.documentElement.append(w),g+=1}return g},{...t,markerAttribute:n})===0)throw new Error("No matching element was found at the requested point");try{return{ok:!0,image:{base64:(await e.screenshot({type:"png"})).toString("base64"),mimeType:"image/png"}}}finally{await e.evaluate(s=>document.querySelectorAll(`[${s}]`).forEach(a=>a.remove()),n).catch(()=>{})}}case"evaluate":return{ok:!0,value:await spn(e,t.expression,t.expressionKind,t.arg,Pct(t.timeoutMs))};case"waitForLoadState":if((t.state??"load")==="networkidle")throw new Error("playwright_wait_for_load_state does not support networkidle");return await e.waitForLoadState(t.state??"load",{timeout:Pct(t.timeoutMs)}),{ok:!0};case"waitForURL":if(t.waitUntil==="networkidle")throw new Error("playwright_wait_for_url does not support networkidle");return await e.waitForURL(t.url,{timeout:Pct(t.timeoutMs),waitUntil:t.waitUntil??"load"}),{ok:!0};case"locator":{let n=await u$s(e,t);return n===void 0?{ok:!0}:{ok:!0,value:n}}case"waitForEvent":case"downloadPath":case"fileChooserSetFiles":throw new Error(`Playwright action '${t.name}' is unavailable`)}}var cYr=Y(()=>{"use strict";r(Pct,"timeoutMs");r(l$s,"locatorFor");r(sYr,"modifiers");r(spn,"evaluatePage");r(u$s,"runLocatorAction");r(aYr,"executeManagedPlaywrightAction")});function d$s(e){let t="a[href],button,input,textarea,select,[role],[onclick],[tabindex],summary,label,[contenteditable]",n="body,main,nav,header,footer,aside,section,article,h1,h2,h3,h4,h5,h6,p,ul,ol,li,dl,dt,dd,blockquote,pre,code,table,caption,thead,tbody,tfoot,tr,th,td,form,fieldset,legend,figure,figcaption,img,canvas,svg,a[href],button,input,textarea,select,option,summary,label,[role],[aria-label],[contenteditable]",o=[],s=new WeakMap,a=window.innerWidth||document.documentElement.clientWidth||0,l=window.innerHeight||document.documentElement.clientHeight||0,u=r(B=>{let z=window.getComputedStyle(B),$=B.getBoundingClientRect();return z.display==="none"||z.visibility==="hidden"||z.opacity==="0"||$.width<=0&&$.height<=0},"hidden"),f=r((B,z)=>String(B??"").trim().replace(/\s+/g," ").slice(0,z),"text"),g=r((B,z)=>{if(z==="a"&&B.hasAttribute("href"))return"link";if(z==="button")return"button";if(z==="select")return"combobox";if(z==="textarea")return"textbox";if(z!=="input")return"";let $=(B.getAttribute("type")||"text").toLowerCase();return $==="checkbox"?"checkbox":$==="radio"?"radio":["button","submit","reset"].includes($)?"button":$==="search"?"searchbox":"textbox"},"implicitRole"),_=r(B=>f(B.getAttribute("aria-label")||B.getAttribute("alt")||B.getAttribute("title")||B.getAttribute("placeholder")||B.innerText||B.textContent,120),"accessibleName"),b=r(B=>{let z={};for(let $ of["id","href","name","type","placeholder","title","alt","role","aria-label","data-testid","data-test","data-qa"]){let J=f(B.getAttribute($),240);J&&(z[$]=J)}return z},"attributes"),w=r(B=>{if(B.id&&/^[A-Za-z][A-Za-z0-9_-]*$/.test(B.id))return`#${B.id}`;let z=[],$=B;for(let J=0;$&&J<6;J+=1){let q=$.tagName.toLowerCase(),ie=$.parentElement?[...$.parentElement.children].filter(ae=>ae.tagName===$?.tagName):[];z.unshift(`${q}:nth-of-type(${ie.indexOf($)+1})`),$=$.parentElement}return z.join(" > ")},"selector"),T=r(B=>{let z=[],$=B;for(;$;){let J=$.tagName.toLowerCase(),q=$.parentElement?[...$.parentElement.children].filter(ie=>ie.tagName===$?.tagName):[];z.unshift(`${J}[${q.indexOf($)+1}]`),$=$.parentElement}return`/${z.join("/")}`},"xpath"),I=r(B=>B.top<l&&B.bottom>0&&B.left<a&&B.right>0,"inViewport"),E=[...document.querySelectorAll(t)].filter(B=>e.includeHidden||!u(B)),R=E.slice(0,e.maxElements).map((B,z)=>{let $=`e${z+1}`;o.push(B),s.set(B,$);let J=B.getBoundingClientRect(),q=B.tagName.toLowerCase(),ie=B.getAttribute("role")||g(B,q),ae=_(B),Ce=f(B.innerText,100),pe=b(B),ze="value"in B?f(String(B.value),240):"",rt=B.parentElement,Pe;for(;rt&&!Pe;)Pe=s.get(rt),rt=rt.parentElement;return{ref:$,tag:q,...ie?{role:ie}:{},...ae?{name:ae}:{},...Ce?{text:Ce}:{},...ze?{value:ze}:{},..."disabled"in B&&B.disabled?{disabled:!0}:{},..."checked"in B?{checked:!!B.checked}:{},selector:w(B),xpath:T(B),rect:{x:Math.round(J.x),y:Math.round(J.y),width:Math.round(J.width),height:Math.round(J.height)},inViewport:I(J),...Pe?{parentRef:Pe}:{},...Object.keys(pe).length>0?{attributes:pe}:{}}}),L=[...document.querySelectorAll(n)].filter(B=>e.includeHidden||!u(B)),U=L.slice(0,e.maxDomNodes).map(B=>{let z=B.getBoundingClientRect(),$=B.tagName.toLowerCase(),J=B.getAttribute("role")||g(B,$),q=_(B),ie=/^(h[1-6]|p|li|dt|dd|blockquote|pre|code|caption|th|td|label|summary|button|a|option|legend|figcaption)$/.test($)?f(B.innerText||B.textContent,300):"",ae=0;for(let ze=B.parentElement;ze&&ze!==document.body;ze=ze.parentElement)ae+=1;let Ce=s.get(B),pe=b(B);return{tag:$,depth:ae,inViewport:I(z),...Ce?{ref:Ce}:{},...J?{role:J}:{},...q?{name:q}:{},...ie?{text:ie}:{},...Object.keys(pe).length>0?{attributes:pe}:{}}});return{refElements:o,snapshot:{url:location.href,title:document.title,elements:R,truncated:E.length>e.maxElements,dom:U,domTruncated:L.length>e.maxDomNodes}}}async function cpn(e,t=200,n=!1){let o=await e.evaluateHandle(d$s,{includeHidden:n,maxDomNodes:300,maxElements:Math.max(1,Math.floor(t))}),s=await o.getProperty("snapshot"),a=await o.getProperty("refElements"),l=await s.jsonValue(),u=new Map;for(let[g,_]of await a.getProperties()){let b=_.asElement();if(!b||!/^\d+$/u.test(g)){await _.dispose();continue}u.set(`e${Number(g)+1}`,b)}let f=apn.get(e);return apn.set(e,u),await Promise.all([...f?.values()??[]].map(async g=>g.dispose())),await Promise.all([s.dispose(),a.dispose(),o.dispose()]),l}async function lpn(e,t){let n=apn.get(e)?.get(t);return n&&await n.evaluate(s=>s.isConnected).catch(()=>!1)?n:void 0}async function lYr(e,t){let n=await lpn(e,t);if(!n)return;await n.scrollIntoViewIfNeeded();let o=await n.boundingBox();return o?{x:Math.round(o.x+o.width/2),y:Math.round(o.y+o.height/2)}:void 0}var apn,uYr=Y(()=>{"use strict";apn=new WeakMap;r(d$s,"collectSnapshot");r(cpn,"captureManagedCdpSnapshot");r(lpn,"resolveSnapshotElement");r(lYr,"resolveSnapshotRef")});function pYr(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"||t.href==="about:blank"}catch{return!1}}function p$s(e){return e==="ControlOrMeta"?process.platform==="darwin"?"Meta":"Control":e}async function age(e,t,n){let o=(t??[]).map(p$s);for(let s of o)await e.keyboard.down(s);try{await n()}finally{for(let s of o.reverse())await e.keyboard.up(s)}}async function Ere(e,t){let n=await lpn(e,t);if(!n)throw new Error(`Browser ref '${t}' is stale or unavailable. Take a fresh snapshot before retrying.`);return n}async function QOe(e,t,n){if(t){let o=await lYr(e,t);if(!o)throw new Error(`Browser ref '${t}' is stale or unavailable`);return o}if(n)return n;throw new Error("Browser action requires a ref or x/y coordinates")}async function eMe(e){let t=await e.context().newCDPSession(e);try{let n=await t.send("Page.getNavigationHistory"),o=n.currentIndex??0,s=n.entries?.length??1,a=e.viewportSize(),l=await e.evaluate(()=>({scrollX:Math.round(window.scrollX),scrollY:Math.round(window.scrollY)})).catch(()=>({scrollX:0,scrollY:0}));return{url:e.url(),title:await e.title().catch(()=>""),canGoBack:o>0,canGoForward:o+1<s,...l,...a?{viewportWidth:a.width,viewportHeight:a.height}:{}}}finally{await t.detach().catch(()=>{})}}async function f$s(e,t){if(t.length===0)return;let n=t.map(s=>s==="ControlOrMeta"?process.platform==="darwin"?"Meta":"Control":s),o=n.slice(0,-1);for(let s of o)await e.keyboard.down(s);try{await e.keyboard.press(n.at(-1)??"")}finally{for(let s of o.reverse())await e.keyboard.up(s)}}async function dYr(e,t){if(t.length===0)throw new Error("Browser drag requires a non-empty path");let[n,...o]=t;await e.mouse.move(n.x,n.y),await e.mouse.down();try{for(let s of o)await e.mouse.move(s.x,s.y,{steps:4})}finally{await e.mouse.up()}}async function fYr(e,t){switch(t.method){case"navigate":return pYr(t.url)?(await e.goto(t.url,{timeout:Rct,waitUntil:"load"}),{ok:!0,state:await eMe(e)}):{ok:!1,error:{code:"navigation_blocked",message:`Navigation URL is not allowed: ${t.url}`}};case"back":return await e.goBack({timeout:Rct,waitUntil:"load"}),{ok:!0,state:await eMe(e)};case"forward":return await e.goForward({timeout:Rct,waitUntil:"load"}),{ok:!0,state:await eMe(e)};case"reload":return await e.reload({timeout:Rct,waitUntil:"load"}),{ok:!0,state:await eMe(e)};case"getState":return{ok:!0,state:await eMe(e)};case"snapshot":return{ok:!0,snapshot:await cpn(e,t.maxElements,t.includeHidden)};case"screenshot":return{ok:!0,image:{base64:(t.ref?await(await Ere(e,t.ref)).screenshot({type:"png"}):await e.screenshot({type:"png",fullPage:t.fullPage,clip:t.clip})).toString("base64"),mimeType:"image/png"}};case"click":{let n=await QOe(e,t.ref,t.x!==void 0&&t.y!==void 0?{x:t.x,y:t.y}:void 0);return await age(e,t.modifiers,async()=>{await e.mouse.click(n.x,n.y,{button:t.button,clickCount:t.doubleClick?2:1})}),{ok:!0}}case"fill":return await(await Ere(e,t.ref)).fill(t.value),{ok:!0};case"type":return t.ref&&await(await Ere(e,t.ref)).focus(),await e.keyboard.type(t.text),{ok:!0};case"press":return t.ref?await(await Ere(e,t.ref)).press(t.key):await age(e,t.modifiers,async()=>e.keyboard.press(t.key)),{ok:!0};case"cuaKeypress":return await f$s(e,t.keys),{ok:!0};case"scroll":return t.ref&&await(await Ere(e,t.ref)).evaluate(n=>n.scrollIntoView()),await e.evaluate(({x:n,y:o})=>window.scrollBy(n,o),{x:t.x??0,y:t.y??0}),{ok:!0};case"cuaScroll":return await age(e,t.modifiers,async()=>{await e.mouse.move(t.x,t.y),await e.mouse.wheel(t.scrollX,t.scrollY)}),{ok:!0};case"domCuaScroll":{let n=t.nodeId?await QOe(e,t.nodeId,void 0):await e.evaluate(()=>({x:window.innerWidth/2,y:window.innerHeight/2}));return await e.mouse.move(n.x,n.y),await e.mouse.wheel(t.scrollX,t.scrollY),{ok:!0}}case"hover":{let n=await QOe(e,t.ref,t.x!==void 0&&t.y!==void 0?{x:t.x,y:t.y}:void 0);return await age(e,t.modifiers,async()=>e.mouse.move(n.x,n.y)),{ok:!0}}case"select":return await(await Ere(e,t.ref)).selectOption(t.values),{ok:!0};case"check":return await(await Ere(e,t.ref)).setChecked(t.checked??!0),{ok:!0};case"drag":{let n=await QOe(e,t.fromRef,t.from),o=await QOe(e,t.toRef,t.to);return await age(e,t.modifiers,async()=>dYr(e,[n,o])),{ok:!0}}case"cuaDrag":return await age(e,t.modifiers,async()=>dYr(e,t.path)),{ok:!0};case"elementInfo":return{ok:!0,element:(await cpn(e)).elements.find(o=>t.x>=o.rect.x&&t.x<=o.rect.x+o.rect.width&&t.y>=o.rect.y&&t.y<=o.rect.y+o.rect.height)};case"evaluate":return{ok:!0,value:await spn(e,t.expression,"string",void 0,3e3)};case"waitFor":{let n=Math.min(3e3,Math.max(1,t.timeoutMs??3e3));if(t.selector)await e.locator(t.selector).waitFor({timeout:n,state:"visible"});else if(t.text)await e.getByText(t.text).waitFor({timeout:n,state:"visible"});else if(t.textGone)await e.getByText(t.textGone).waitFor({timeout:n,state:"hidden"});else throw new Error("waitFor requires selector, text, or textGone");return{ok:!0}}case"playwright":return await aYr(e,t.action);case"playwrightWaitForTimeout":return await new Promise(n=>setTimeout(n,t.timeoutMs)),{ok:!0};default:return{ok:!1,error:{code:"capability_unsupported",message:`Browser command '${t.method}' is unavailable in the managed CDP page runtime`}}}}var Rct,upn=Y(()=>{"use strict";cYr();uYr();Rct=3e4;r(pYr,"isAllowedManagedBrowserUrl");r(p$s,"normalizedModifier");r(age,"withModifiers");r(Ere,"elementForRef");r(QOe,"pointFor");r(eMe,"readManagedPageState");r(f$s,"pressKeys");r(dYr,"dragPath");r(fYr,"executeManagedPageCommand")});function HF(){return new DOMException("Browser command cancelled","AbortError")}async function dpn(e,t){if(t.aborted)throw HF();return await new Promise((n,o)=>{let s=r(()=>o(HF()),"onAbort");t.addEventListener("abort",s,{once:!0}),e.then(n,o).finally(()=>t.removeEventListener("abort",s))})}function mYr(e){return e.method==="playwright"&&e.action.name==="locator"?["click","dblclick","fill","press","selectOption","setChecked"].includes(e.action.operation):e.method==="playwright"&&e.action.name==="evaluate"?!0:["navigate","back","forward","reload","click","fill","type","press","cuaKeypress","scroll","cuaScroll","domCuaScroll","hover","select","check","drag","cuaDrag","handleDialog","close","newTab","evaluate"].includes(e.method)}function hYr(e){return e instanceof Error&&e.name==="AbortError"?"cancelled":e instanceof Error&&e.name==="TimeoutError"?"timeout":e instanceof Error&&/unavailable|closed|disconnected/iu.test(e.message)?"backend_unavailable":"execution_error"}var gYr=Y(()=>{"use strict";r(HF,"abortError");r(dpn,"raceWithAbort");r(mYr,"hasSideEffects");r(hYr,"classifyError")});var yYr,_Yr,Dct,vYr=Y(()=>{"use strict";yYr=require("node:crypto"),_Yr={width:1280,height:720},Dct=class{static{r(this,"ManagedCdpSession")}context;#e=new Map;#t=new Map;#n;constructor(t){this.context=t;for(let n of t.pages())this.registerPage(n);t.on("page",n=>this.registerPage(n))}get tabIds(){return[...this.#t.keys()]}get activeTabId(){return this.#n}async createTab(){let t=await this.context.newPage(),n=this.tabForPage(t)??this.registerPage(t);return this.#n=n.id,await t.bringToFront(),n}async ensureTab(t){if(t){let s=this.#t.get(t);if(!s||s.page.isClosed())throw new Error(`Browser tab '${t}' is unavailable`);return s}let n=this.#n?this.#t.get(this.#n):void 0;return n&&!n.page.isClosed()?n:[...this.#t.values()].find(s=>!s.page.isClosed())??await this.createTab()}async activateTab(t){let n=await this.ensureTab(t);return this.#n=n.id,await n.page.bringToFront(),n}async closeTab(t){let n=await this.ensureTab(t);this.#t.delete(n.id),this.#e.delete(n.id),n.page.isClosed()||await n.page.close({runBeforeUnload:!1}),this.#n===n.id&&(this.#n=[...this.#t.keys()].at(-1))}async listTabs(){let t=[];for(let n of this.#t.values())n.page.isClosed()||t.push({tabId:n.id,url:n.page.url(),title:await n.page.title().catch(()=>""),viewport:n.page.viewportSize()??_Yr,...n.id===this.#n?{active:!0}:{},lifecycle:"active"});return t}dialogFor(t){return this.#e.get(t)}clearDialog(t){this.#e.delete(t)}async setViewport(t,n){await(await this.ensureTab(t)).page.setViewportSize(n??_Yr)}async close(){this.#e.clear(),this.#t.clear(),this.context.browser()?.isConnected()&&await this.context.close().catch(()=>{})}registerPage(t){let n=this.tabForPage(t);if(n)return n;let o={id:`tab:${(0,yYr.randomUUID)()}`,page:t};return this.#t.set(o.id,o),this.#n??=o.id,t.on("dialog",s=>this.#e.set(o.id,s)),t.on("close",()=>{this.#t.delete(o.id),this.#e.delete(o.id),this.#n===o.id&&(this.#n=[...this.#t.keys()].at(-1))}),o}tabForPage(t){return[...this.#t.values()].find(n=>n.page===t)}}});function bYr(e={}){let t={...e,executablePath:Act(e.executablePath,e.platform)},n=new fpn(t);return{browserControlPort:n,close:r(async()=>n.close(),"close")}}function Are(e,t){return new Promise(n=>{let o=!1,s,a=r(l=>{o||(o=!0,s&&clearTimeout(s),n(l))},"finish");s=setTimeout(()=>a(!1),t),e.then(()=>a(!0),()=>a(!0))})}var ppn,m$s,fpn,mpn=Y(()=>{"use strict";ppn=require("node:crypto");rYr();ipn();upn();gYr();vYr();ipn();upn();m$s=1500,fpn=class{static{r(this,"ManagedCdpBrowserControlPort")}#e=`cdp:${(0,ppn.randomUUID)()}`;#t;#n;#r;#o=new Set;#i=new Map;#c=new Map;#s=new Map;#a;#l=!1;#d=1;#u;constructor(t){this.#n=t,this.#t=t.loadPlaywright??iYr,this.#r=Math.max(1,Math.trunc(t.closeTimeoutMs??m$s))}async list(t){return await this.ensureBrowser(t.signal),[this.descriptor()]}async execute(t){let n=Date.now();if(t.browserId!==this.#e||t.browserGeneration!==this.#d)return this.errorResult("backend_unavailable",`Browser backend '${t.browserId}' generation ${t.browserGeneration} is stale`,n);let o=(0,ppn.randomUUID)(),s=new AbortController,a=r(()=>s.abort(t.signal?.reason??HF()),"forwardAbort");t.signal?.addEventListener("abort",a,{once:!0}),t.signal?.aborted&&a(),this.#i.set(o,{controller:s,sessionId:t.sessionId,turnId:t.turnId});let l=!1;try{if(s.signal.aborted)throw HF();await this.ensureBrowser(s.signal);let u=await this.ensureSession(t.sessionId);if(s.signal.aborted)throw HF();l=!0;let f=await dpn(this.executeSessionCommand(u,t.command),s.signal);return await this.withMeta(u,t.command,f,n)}catch(u){let f=hYr(u);return this.errorResult(f,u instanceof Error?u.message:String(u),n,f==="cancelled"&&l&&mYr(t.command)?"uncertain":void 0)}finally{t.signal?.removeEventListener("abort",a),this.#i.delete(o)}}async turnEnded(t){for(let n of this.#i.values())n.sessionId===t.sessionId&&n.turnId===t.turnId&&n.controller.abort(HF())}async closeSession(t){this.#o.add(t.sessionId);for(let s of this.#i.values())s.sessionId===t.sessionId&&s.controller.abort(HF());let n=this.#c.get(t.sessionId);n&&(await Are(n,this.#r)||n.then(async()=>{this.#s.size===0&&await this.closeBrowser()},async()=>{this.#s.size===0&&await this.closeBrowser()}));let o=this.#s.get(t.sessionId);this.#s.delete(t.sessionId),o&&await Are(o.close(),this.#r),this.#s.size===0&&await this.closeBrowser()}async close(){if(this.#l)return;this.#l=!0;let t=this.#u;for(let n of this.#i.values())n.controller.abort(HF());this.#i.clear(),this.#o.clear(),await Promise.all([...this.#c.values()].map(async n=>{await Are(n,this.#r)})),await Promise.all([...this.#s.values()].map(async n=>{await Are(n.close(),this.#r)})),this.#s.clear(),await this.closeBrowser(),t&&await Are(t.then(async n=>this.closeBrowserInstance(n)),this.#r)}descriptor(){return nYr(this.#e,this.#d)}async ensureBrowser(t){if(this.#l)throw new Error("Managed CDP browser runtime is closed");if(t?.aborted)throw HF();if(this.#a?.isConnected())return this.#a;this.#u??=(async()=>{let o;try{o=await this.#t()}catch(l){throw new Error("Managed headless Chromium is unavailable: failed to load the pinned Playwright runtime.",{cause:l})}let s=opn(o,this.#n),a;try{a=await o.chromium.launch({executablePath:s,headless:!0,args:["--no-first-run","--no-default-browser-check"]})}catch(l){throw new Error("Managed headless Chromium is unavailable: launch failed. Verify the browser executable and OS sandbox/runtime dependencies.",{cause:l})}if(this.#l)throw await this.closeBrowserInstance(a),new Error("Managed CDP browser runtime is closed");return a.on("disconnected",()=>{this.#a===a&&(this.#a=void 0,this.#s.clear(),this.#d+=1)}),this.#a=a,a})().finally(()=>{this.#u=void 0});let n=t?await dpn(this.#u,t):await this.#u;if(t?.aborted)throw await this.closeBrowserInstance(n),HF();return n}async ensureSession(t){if(this.#o.has(t))throw new Error(`Browser session '${t}' is closing`);let n=this.#s.get(t);if(n)return n;let o=this.#c.get(t);if(o)return await o;let s=(async()=>{let a=await this.ensureBrowser(),l=this.#d,u=await a.newContext({acceptDownloads:!1,viewport:{width:1280,height:720}});if(this.#l||this.#o.has(t)||this.#a!==a||this.#d!==l||!a.isConnected())throw await Are(u.close(),this.#r),new Error("Managed CDP browser context became unavailable during creation");let f=new Dct(u);return this.#s.set(t,f),f})();this.#c.set(t,s);try{return await s}finally{this.#c.get(t)===s&&this.#c.delete(t)}}async executeSessionCommand(t,n){switch(n.method){case"list":return{ok:!0,tabs:await t.listTabs()};case"newTab":{let o=await t.createTab();return{ok:!0,tab:(await t.listTabs()).find(s=>s.tabId===o.id)}}case"activateTab":{let o=await t.activateTab(n.tabId);return{ok:!0,tab:(await t.listTabs()).find(s=>s.tabId===o.id)}}case"close":return await t.closeTab(n.tabId),{ok:!0};case"browserViewportSet":return await t.setViewport(n.tabId,{width:n.width,height:n.height}),{ok:!0};case"browserViewportReset":return await t.setViewport(n.tabId,null),{ok:!0};case"getDialog":{let o=await t.ensureTab(n.tabId),s=t.dialogFor(o.id),a=s?.type();return{ok:!0,dialog:s&&a&&["alert","confirm","prompt","beforeunload"].includes(a)?{type:a,message:s.message(),...s.defaultValue()?{defaultPrompt:s.defaultValue()}:{}}:null}}case"handleDialog":{let o=await t.ensureTab(n.tabId),s=t.dialogFor(o.id);if(!s)throw new Error("No JavaScript dialog is pending for this tab");return n.accept?await s.accept(n.promptText):await s.dismiss(),t.clearDialog(o.id),{ok:!0}}case"nameSession":return{ok:!0};case"listUserTabs":return{ok:!0,userTabs:[]};case"browserVisibilityGet":case"browserVisibilitySet":case"capabilities":case"claimTab":case"finalize":case"finalizeTabs":case"markDeliverable":case"markHandoff":case"turnEnded":case"closeSession":case"cancelRequest":return{ok:!1,error:{code:"capability_unsupported",message:`Browser command '${n.method}' is unavailable in managed headless CDP`}};default:{let o=await t.ensureTab("tabId"in n?n.tabId:void 0);return await fYr(o.page,n)}}}async withMeta(t,n,o,s){let a="tabId"in n?n.tabId:t.activeTabId,l=a?await t.ensureTab(a).catch(()=>{}):void 0;return{...o,elapsedMs:Date.now()-s,meta:{browserUse:!0,backendType:"cdp",browserId:this.#e,browserGeneration:this.#d,openTabIds:t.tabIds,...l?{tabId:l.id,currentUrl:l.page.url(),lifecycle:"active"}:{}}}}errorResult(t,n,o,s){return{ok:!1,error:{code:t,message:n,...s?{sideEffect:s}:{}},elapsedMs:Date.now()-o}}async closeBrowser(){let t=this.#a;this.#a=void 0,t&&await this.closeBrowserInstance(t)}async closeBrowserInstance(t){t.isConnected()&&await Are(t.close(),this.#r)}};r(bYr,"createManagedCdpBrowserRuntime");r(Are,"waitForPromise")});var h$s,Oct,g$s,_$s,y$s,v$s,qs,SYr,b$s,Mct,hpn=Y(()=>{h$s=Object.create,Oct=Object.defineProperty,g$s=Object.getOwnPropertyDescriptor,_$s=Object.getOwnPropertyNames,y$s=Object.getPrototypeOf,v$s=Object.prototype.hasOwnProperty,qs=r((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"__commonJSMin"),SYr=r((e,t)=>{let n={};for(var o in e)Oct(n,o,{get:e[o],enumerable:!0});return t&&Oct(n,Symbol.toStringTag,{value:"Module"}),n},"__exportAll"),b$s=r((e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(var s=_$s(t),a=0,l=s.length,u;a<l;a++)u=s[a],!v$s.call(e,u)&&u!==n&&Oct(e,u,{get:(f=>t[f]).bind(null,u),enumerable:!(o=g$s(t,u))||o.enumerable});return e},"__copyProps"),Mct=r((e,t,n)=>(n=e!=null?h$s(y$s(e)):{},b$s(t||!e||!e.__esModule?Oct(n,"default",{value:e,enumerable:!0}):n,e)),"__toESM")});function kYr(e){return typeof e=="string"&&wYr.has(e.replace(/#$/,""))}function xYr(e,t){if(!("$schema"in e)||typeof e.$schema!="string")return"2020-12";let n=e.$schema.replace(/#$/,"");if(S$s.has(n))return"2020-12";if(wYr.has(n))return"2019-09";if(w$s.has(n)||k$s.has(n))return"draft-7";throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}var S$s,wYr,w$s,k$s,gpn=Y(()=>{S$s=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),wYr=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),w$s=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),k$s=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);r(kYr,"declares2019Dialect");r(xYr,"declaredDialect")});var cge,Nct,Lct,n$,lge,r$,Rre,tMe,uge,Dre,wG,qv,ypn,nMe,rMe,Fct,jct,oMe,zk,Ore,Wv,D1,O1,iMe,Vv,kG,sMe,aMe,dge,pge,pB,vpn,cMe,Bct,lMe,Uct,xG,t$,fge,x$s,T$s,zct,$ct,qct,Wct,uMe,dMe,Vct,pMe,Hct,Mre,fMe,Gct,Jct,mMe,Kct,TG,IG,hMe,gMe,bpn,_Me,CG,o$,yMe,Zct,Yct,Xct,Qct,elt,mge,tlt,nlt,rlt,olt,ilt,slt,alt,clt,vMe,llt,ult,dlt,plt,flt,mlt,hlt,glt,_lt,ylt,vlt,blt,Slt,wlt,hge,gge,_ge,klt,xlt,Tlt,yge,Ilt,Clt,Elt,Alt,Plt,bMe,Rlt,Dlt,SMe,Spn,Olt,Mlt,Nlt,wMe,kMe,Llt,Flt,jlt,Blt,Ult,zlt,$lt,qlt,Wlt,Pre,Vlt,Hlt,Glt,Jlt,Klt,xMe,vge,bge,TMe,IMe,CMe,Zlt,EMe,AMe,Ylt,Xlt,PMe,Sge,Qlt,eut,tut,nut,rut,out,iut,sut,aut,cut,lut,uut,dut,put,fut,wpn,mut,EG,kpn,hut,xpn,Tpn,Ipn,Cpn,Epn,Apn,Ppn,Rpn,Dpn,Opn,Mpn,Npn,Lpn,Fpn,jpn,Uk,RMe,wge,gut,DMe,OMe,_ut,MMe,_pn,yut,vut,NMe,Bpn,Upn,TYr=Y(()=>{tc();cge="2025-11-25",Nct=[cge,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Lct="io.modelcontextprotocol/related-task",n$="io.modelcontextprotocol/protocolVersion",lge="io.modelcontextprotocol/clientInfo",r$="io.modelcontextprotocol/serverInfo",Rre="io.modelcontextprotocol/clientCapabilities",tMe="io.modelcontextprotocol/subscriptionId",uge="io.modelcontextprotocol/logLevel",Dre="2.0",wG=mV(()=>bc([$t(),Gs(),kc(),Bj(),cc($t(),wG),Go(wG)])),qv=cc($t(),wG),ypn=Go(wG),nMe=bc([$t(),Gs().int()]),rMe=$t(),Fct=Fr({ttl:Gs().optional()}),jct=Fr({taskId:$t()}),oMe=nu({progressToken:nMe.optional(),[Lct]:jct.optional()}),zk=Fr({_meta:oMe.optional()}),Ore=zk.extend({task:Fct.optional()}),Wv=Fr({method:$t(),params:zk.loose().optional()}),D1=Fr({_meta:oMe.optional()}),O1=Fr({method:$t(),params:D1.loose().optional()}),iMe=nu({get[r$](){return fge.optional().catch(void 0)}}),Vv=nu({_meta:iMe.optional()}),kG=bc([$t(),Gs().int()]),sMe=Fr({jsonrpc:si(Dre),id:kG,...Wv.shape}).strict(),aMe=Fr({jsonrpc:si(Dre),...O1.shape}).strict(),dge=Fr({jsonrpc:si(Dre),id:kG,result:Vv}).strict(),pge=Fr({jsonrpc:si(Dre),id:kG.optional(),error:Fr({code:Gs().int(),message:$t(),data:Dl().optional()})}).strict(),pB=bc([sMe,aMe,dge,pge]),vpn=bc([dge,pge]),cMe=Vv.strict(),Bct=D1.extend({requestId:kG.optional(),reason:$t().optional()}),lMe=O1.extend({method:si("notifications/cancelled"),params:Bct}),Uct=Fr({src:$t(),mimeType:$t().optional(),sizes:Go($t()).optional(),theme:Bu(["light","dark"]).optional()}),xG=Fr({icons:Go(Uct).optional()}),t$=Fr({name:$t(),title:$t().optional()}),fge=t$.extend({...t$.shape,...xG.shape,version:$t(),websiteUrl:$t().optional(),description:$t().optional()}),x$s=$L(Fr({applyDefaults:kc().optional()}),qv),T$s=hz(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,$L(Fr({form:x$s.optional(),url:qv.optional()}),qv.optional())),zct=nu({list:qv.optional(),cancel:qv.optional(),requests:nu({sampling:nu({createMessage:qv.optional()}).optional(),elicitation:nu({create:qv.optional()}).optional()}).optional()}),$ct=nu({list:qv.optional(),cancel:qv.optional(),requests:nu({tools:nu({call:qv.optional()}).optional()}).optional()}),qct=Fr({experimental:cc($t(),qv).optional(),sampling:Fr({context:qv.optional(),tools:qv.optional()}).optional(),elicitation:T$s.optional(),roots:Fr({listChanged:kc().optional()}).optional(),tasks:zct.optional(),extensions:cc($t(),qv).optional()}),Wct=zk.extend({protocolVersion:$t(),capabilities:qct,clientInfo:fge}),uMe=Wv.extend({method:si("initialize"),params:Wct}),dMe=Fr({experimental:cc($t(),qv).optional(),logging:qv.optional(),completions:qv.optional(),prompts:Fr({listChanged:kc().optional()}).optional(),resources:Fr({subscribe:kc().optional(),listChanged:kc().optional()}).optional(),tools:Fr({listChanged:kc().optional()}).optional(),tasks:$ct.optional(),extensions:cc($t(),qv).optional()}),Vct=Vv.extend({protocolVersion:$t(),capabilities:dMe,serverInfo:fge,instructions:$t().optional()}),pMe=O1.extend({method:si("notifications/initialized"),params:D1.optional()}),Hct=Wv.extend({method:si("server/discover"),params:zk.optional()}),Mre=Vv.extend({supportedVersions:Go($t()),capabilities:dMe,instructions:$t().optional()}),fMe=Wv.extend({method:si("ping"),params:zk.optional()}),Gct=Fr({progress:Gs(),total:xl(Gs()),message:xl($t())}),Jct=Fr({...D1.shape,...Gct.shape,progressToken:nMe}),mMe=O1.extend({method:si("notifications/progress"),params:Jct}),Kct=zk.extend({cursor:rMe.optional()}),TG=Wv.extend({params:Kct.optional()}),IG=Vv.extend({nextCursor:rMe.optional()}),hMe=Fr({uri:$t(),mimeType:xl($t()),_meta:cc($t(),Dl()).optional()}),gMe=hMe.extend({text:$t()}),bpn=$t().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),_Me=hMe.extend({blob:bpn}),CG=Bu(["user","assistant"]),o$=Fr({audience:Go(CG).optional(),priority:Gs().min(0).max(1).optional(),lastModified:jO.datetime({offset:!0}).optional()}),yMe=Fr({...t$.shape,...xG.shape,uri:$t(),description:xl($t()),mimeType:xl($t()),size:xl(Gs()),annotations:o$.optional(),_meta:xl(nu({}))}),Zct=Fr({...t$.shape,...xG.shape,uriTemplate:$t(),description:xl($t()),mimeType:xl($t()),annotations:o$.optional(),_meta:xl(nu({}))}),Yct=TG.extend({method:si("resources/list")}),Xct=IG.extend({resources:Go(yMe)}),Qct=TG.extend({method:si("resources/templates/list")}),elt=IG.extend({resourceTemplates:Go(Zct)}),mge=zk.extend({uri:$t()}),tlt=mge,nlt=Wv.extend({method:si("resources/read"),params:tlt}),rlt=Vv.extend({contents:Go(bc([gMe,_Me]))}),olt=O1.extend({method:si("notifications/resources/list_changed"),params:D1.optional()}),ilt=mge,slt=Wv.extend({method:si("resources/subscribe"),params:ilt}),alt=mge,clt=Wv.extend({method:si("resources/unsubscribe"),params:alt}),vMe=Fr({toolsListChanged:kc().optional(),promptsListChanged:kc().optional(),resourcesListChanged:kc().optional(),resourceSubscriptions:Go($t()).optional()}),llt=zk.extend({notifications:vMe}),ult=Wv.extend({method:si("subscriptions/listen"),params:llt}),dlt=D1.extend({notifications:vMe}),plt=O1.extend({method:si("notifications/subscriptions/acknowledged"),params:dlt}),flt=iMe.extend({[tMe]:kG}),mlt=Vv.extend({_meta:flt}),hlt=D1.extend({uri:$t()}),glt=O1.extend({method:si("notifications/resources/updated"),params:hlt}),_lt=Fr({name:$t(),description:xl($t()),required:xl(kc())}),ylt=Fr({...t$.shape,...xG.shape,description:xl($t()),arguments:xl(Go(_lt)),_meta:xl(nu({}))}),vlt=TG.extend({method:si("prompts/list")}),blt=IG.extend({prompts:Go(ylt)}),Slt=zk.extend({name:$t(),arguments:cc($t(),$t()).optional()}),wlt=Wv.extend({method:si("prompts/get"),params:Slt}),hge=Fr({type:si("text"),text:$t(),annotations:o$.optional(),_meta:cc($t(),Dl()).optional()}),gge=Fr({type:si("image"),data:bpn,mimeType:$t(),annotations:o$.optional(),_meta:cc($t(),Dl()).optional()}),_ge=Fr({type:si("audio"),data:bpn,mimeType:$t(),annotations:o$.optional(),_meta:cc($t(),Dl()).optional()}),klt=Fr({type:si("tool_use"),name:$t(),id:$t(),input:cc($t(),Dl()),_meta:cc($t(),Dl()).optional()}),xlt=Fr({type:si("resource"),resource:bc([gMe,_Me]),annotations:o$.optional(),_meta:cc($t(),Dl()).optional()}),Tlt=yMe.extend({type:si("resource_link")}),yge=bc([hge,gge,_ge,Tlt,xlt]),Ilt=Fr({role:CG,content:yge}),Clt=Vv.extend({description:$t().optional(),messages:Go(Ilt)}),Elt=O1.extend({method:si("notifications/prompts/list_changed"),params:D1.optional()}),Alt=Fr({title:$t().optional(),readOnlyHint:kc().optional(),destructiveHint:kc().optional(),idempotentHint:kc().optional(),openWorldHint:kc().optional()}),Plt=Fr({taskSupport:Bu(["required","optional","forbidden"]).optional()}),bMe=Fr({...t$.shape,...xG.shape,description:$t().optional(),inputSchema:Fr({type:si("object"),properties:cc($t(),wG).optional(),required:Go($t()).optional()}).catchall(Dl()),outputSchema:nu({$schema:$t().optional()}).optional(),annotations:Alt.optional(),execution:Plt.optional(),_meta:cc($t(),Dl()).optional()}),Rlt=TG.extend({method:si("tools/list")}),Dlt=IG.extend({tools:Go(bMe)}),SMe=Vv.extend({content:Go(yge).default([]),structuredContent:Dl().optional(),isError:kc().optional()}),Spn=SMe.or(Vv.extend({toolResult:Dl()})),Olt=Ore.extend({name:$t(),arguments:cc($t(),Dl()).optional()}),Mlt=Wv.extend({method:si("tools/call"),params:Olt}),Nlt=O1.extend({method:si("notifications/tools/list_changed"),params:D1.optional()}),wMe=Fr({autoRefresh:kc().default(!0),debounceMs:Gs().int().nonnegative().default(300)}),kMe=Bu(["debug","info","notice","warning","error","critical","alert","emergency"]),Llt=zk.extend({level:kMe}),Flt=Wv.extend({method:si("logging/setLevel"),params:Llt}),jlt=D1.extend({level:kMe,logger:$t().optional(),data:Dl()}),Blt=O1.extend({method:si("notifications/message"),params:jlt}),Ult=Fr({name:$t().optional()}),zlt=Fr({hints:Go(Ult).optional(),costPriority:Gs().min(0).max(1).optional(),speedPriority:Gs().min(0).max(1).optional(),intelligencePriority:Gs().min(0).max(1).optional()}),$lt=Fr({mode:Bu(["auto","required","none"]).optional()}),qlt=Fr({type:si("tool_result"),toolUseId:$t().describe("The unique identifier for the corresponding tool call."),content:Go(yge),structuredContent:Dl().optional(),isError:kc().optional(),_meta:cc($t(),Dl()).optional()}),Wlt=fV("type",[hge,gge,_ge]),Pre=fV("type",[hge,gge,_ge,klt,qlt]),Vlt=Fr({role:CG,content:bc([Pre,Go(Pre)]),_meta:cc($t(),Dl()).optional()}),Hlt=Ore.extend({messages:Go(Vlt),modelPreferences:zlt.optional(),systemPrompt:$t().optional(),includeContext:Bu(["none","thisServer","allServers"]).optional(),temperature:Gs().optional(),maxTokens:Gs().int(),stopSequences:Go($t()).optional(),metadata:qv.optional(),tools:Go(bMe).optional(),toolChoice:$lt.optional()}),Glt=Wv.extend({method:si("sampling/createMessage"),params:Hlt}),Jlt=Vv.extend({model:$t(),stopReason:xl(Bu(["endTurn","stopSequence","maxTokens"]).or($t())),role:CG,content:Wlt}),Klt=Vv.extend({model:$t(),stopReason:xl(Bu(["endTurn","stopSequence","maxTokens","toolUse"]).or($t())),role:CG,content:bc([Pre,Go(Pre)])}),xMe=Fr({type:si("boolean"),title:$t().optional(),description:$t().optional(),default:kc().optional()}),vge=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),minLength:Gs().optional(),maxLength:Gs().optional(),format:Bu(["email","uri","date","date-time"]).optional(),default:$t().optional()}),bge=Fr({type:Bu(["number","integer"]),title:$t().optional(),description:$t().optional(),minimum:Gs().optional(),maximum:Gs().optional(),default:Gs().optional()}),TMe=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),enum:Go($t()),default:$t().optional()}),IMe=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),oneOf:Go(Fr({const:$t(),title:$t()})),default:$t().optional()}),CMe=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),enum:Go($t()),enumNames:Go($t()).optional(),default:$t().optional()}),Zlt=bc([TMe,IMe]),EMe=Fr({type:si("array"),title:$t().optional(),description:$t().optional(),minItems:Gs().optional(),maxItems:Gs().optional(),items:Fr({type:si("string"),enum:Go($t())}),default:Go($t()).optional()}),AMe=Fr({type:si("array"),title:$t().optional(),description:$t().optional(),minItems:Gs().optional(),maxItems:Gs().optional(),items:Fr({anyOf:Go(Fr({const:$t(),title:$t()}))}),default:Go($t()).optional()}),Ylt=bc([EMe,AMe]),Xlt=bc([CMe,Zlt,Ylt]),PMe=bc([Xlt,xMe,vge,bge]),Sge=Ore.extend({mode:si("form").optional(),message:$t(),requestedSchema:Fr({type:si("object"),properties:cc($t(),PMe),required:Go($t()).optional()}).catchall(Dl())}),Qlt=Ore.extend({mode:si("url"),message:$t(),elicitationId:$t(),url:$t().url()}),eut=bc([Sge,Qlt]),tut=Wv.extend({method:si("elicitation/create"),params:eut}),nut=D1.extend({elicitationId:$t()}),rut=O1.extend({method:si("notifications/elicitation/complete"),params:nut}),out=Vv.extend({action:Bu(["accept","decline","cancel"]),content:hz(e=>e===null?void 0:e,cc($t(),bc([$t(),Gs(),kc(),Go($t())])).optional())}),iut=Fr({type:si("ref/resource"),uri:$t()}),sut=Fr({type:si("ref/prompt"),name:$t()}),aut=zk.extend({ref:bc([sut,iut]),argument:Fr({name:$t(),value:$t()}),context:Fr({arguments:cc($t(),$t()).optional()}).optional()}),cut=Wv.extend({method:si("completion/complete"),params:aut}),lut=Vv.extend({completion:nu({values:Go($t()).max(100),total:xl(Gs().int()),hasMore:xl(kc())})}),uut=Fr({uri:$t().startsWith("file://"),name:$t().optional(),_meta:cc($t(),Dl()).optional()}),dut=Wv.extend({method:si("roots/list"),params:zk.optional()}),put=Vv.extend({roots:Go(uut)}),fut=O1.extend({method:si("notifications/roots/list_changed"),params:D1.optional()}),wpn=nu({ttl:Gs().optional(),pollInterval:Gs().optional()}),mut=Bu(["working","input_required","completed","failed","cancelled"]),EG=Fr({taskId:$t(),status:mut,ttl:bc([Gs(),Bj()]),createdAt:$t(),lastUpdatedAt:$t(),pollInterval:xl(Gs()),statusMessage:xl($t())}),kpn=Vv.extend({task:EG}),hut=D1.merge(EG),xpn=O1.extend({method:si("notifications/tasks/status"),params:hut}),Tpn=Wv.extend({method:si("tasks/get"),params:zk.extend({taskId:$t()})}),Ipn=Vv.merge(EG),Cpn=Wv.extend({method:si("tasks/result"),params:zk.extend({taskId:$t()})}),Epn=Vv.loose(),Apn=TG.extend({method:si("tasks/list")}),Ppn=IG.extend({tasks:Go(EG)}),Rpn=Wv.extend({method:si("tasks/cancel"),params:zk.extend({taskId:$t()})}),Dpn=Vv.merge(EG),Opn=bc([fMe,uMe,Hct,cut,Flt,wlt,vlt,Yct,Qct,nlt,slt,clt,ult,Mlt,Rlt]),Mpn=bc([lMe,mMe,pMe,fut]),Npn=bc([cMe,Jlt,Klt,out,put]),Lpn=bc([fMe,Glt,tut,dut]),Fpn=bc([lMe,mMe,Blt,glt,olt,Nlt,Elt,plt,rut]),jpn=bc([cMe,Vct,Mre,lut,Clt,blt,Xct,elt,rlt,SMe,Dlt,mlt]),Uk=ape().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Eqt.custom,message:"URL must be parseable",fatal:!0}),KCe}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),RMe=nu({resource:$t().url(),authorization_servers:Go(Uk).optional(),jwks_uri:$t().url().optional(),scopes_supported:Go($t()).optional(),bearer_methods_supported:Go($t()).optional(),resource_signing_alg_values_supported:Go($t()).optional(),resource_name:$t().optional(),resource_documentation:$t().optional(),resource_policy_uri:$t().url().optional(),resource_tos_uri:$t().url().optional(),tls_client_certificate_bound_access_tokens:kc().optional(),authorization_details_types_supported:Go($t()).optional(),dpop_signing_alg_values_supported:Go($t()).optional(),dpop_bound_access_tokens_required:kc().optional()}),wge=nu({issuer:$t(),authorization_endpoint:Uk,token_endpoint:Uk,registration_endpoint:Uk.optional(),scopes_supported:Go($t()).optional(),response_types_supported:Go($t()),response_modes_supported:Go($t()).optional(),grant_types_supported:Go($t()).optional(),token_endpoint_auth_methods_supported:Go($t()).optional(),token_endpoint_auth_signing_alg_values_supported:Go($t()).optional(),service_documentation:Uk.optional(),revocation_endpoint:Uk.optional(),revocation_endpoint_auth_methods_supported:Go($t()).optional(),revocation_endpoint_auth_signing_alg_values_supported:Go($t()).optional(),introspection_endpoint:$t().optional(),introspection_endpoint_auth_methods_supported:Go($t()).optional(),introspection_endpoint_auth_signing_alg_values_supported:Go($t()).optional(),code_challenge_methods_supported:Go($t()).optional(),client_id_metadata_document_supported:kc().optional(),authorization_response_iss_parameter_supported:kc().optional().catch(void 0)}),gut=nu({issuer:$t(),authorization_endpoint:Uk,token_endpoint:Uk,userinfo_endpoint:Uk.optional(),jwks_uri:Uk,registration_endpoint:Uk.optional(),scopes_supported:Go($t()).optional(),response_types_supported:Go($t()),response_modes_supported:Go($t()).optional(),grant_types_supported:Go($t()).optional(),acr_values_supported:Go($t()).optional(),subject_types_supported:Go($t()),id_token_signing_alg_values_supported:Go($t()),id_token_encryption_alg_values_supported:Go($t()).optional(),id_token_encryption_enc_values_supported:Go($t()).optional(),userinfo_signing_alg_values_supported:Go($t()).optional(),userinfo_encryption_alg_values_supported:Go($t()).optional(),userinfo_encryption_enc_values_supported:Go($t()).optional(),request_object_signing_alg_values_supported:Go($t()).optional(),request_object_encryption_alg_values_supported:Go($t()).optional(),request_object_encryption_enc_values_supported:Go($t()).optional(),token_endpoint_auth_methods_supported:Go($t()).optional(),token_endpoint_auth_signing_alg_values_supported:Go($t()).optional(),display_values_supported:Go($t()).optional(),claim_types_supported:Go($t()).optional(),claims_supported:Go($t()).optional(),service_documentation:$t().optional(),claims_locales_supported:Go($t()).optional(),ui_locales_supported:Go($t()).optional(),claims_parameter_supported:kc().optional(),request_parameter_supported:kc().optional(),request_uri_parameter_supported:kc().optional(),require_request_uri_registration:kc().optional(),op_policy_uri:Uk.optional(),op_tos_uri:Uk.optional(),client_id_metadata_document_supported:kc().optional(),authorization_response_iss_parameter_supported:kc().optional().catch(void 0)}),DMe=Fr({...gut.shape,...wge.pick({code_challenge_methods_supported:!0}).shape}),OMe=Fr({access_token:$t(),id_token:$t().optional(),token_type:$t(),expires_in:qEe.number().optional(),scope:$t().optional(),refresh_token:$t().optional()}).strip(),_ut=Fr({issued_token_type:si("urn:ietf:params:oauth:token-type:id-jag"),access_token:$t(),token_type:$t().optional(),expires_in:Gs().optional(),scope:$t().optional()}).strip(),MMe=Fr({error:$t(),error_description:$t().optional(),error_uri:$t().optional()}),_pn=Uk.optional().or(si("").transform(()=>{})),yut=Fr({redirect_uris:Go(Uk),token_endpoint_auth_method:$t().optional(),grant_types:Go($t()).optional(),response_types:Go($t()).optional(),application_type:$t().optional(),client_name:$t().optional(),client_uri:Uk.optional(),logo_uri:_pn,scope:$t().optional(),contacts:Go($t()).optional(),tos_uri:_pn,policy_uri:$t().optional(),jwks_uri:Uk.optional(),jwks:sKe().optional(),software_id:$t().optional(),software_version:$t().optional(),software_statement:$t().optional()}).strip(),vut=Fr({client_id:$t(),client_secret:$t().optional(),client_id_issued_at:Gs().optional(),client_secret_expires_at:Gs().optional()}).strip(),NMe=yut.merge(vut),Bpn=Fr({error:$t(),error_description:$t().optional()}).strip(),Upn=Fr({token:$t(),token_type_hint:$t().optional()}).strip()});var NYr=Y(()=>{TYr()});function Lre(e,t){let n=new Set,o=t;for(;typeof o=="function";){let s=o.mcpBrand;Object.prototype.hasOwnProperty.call(o,"mcpBrand")&&typeof s=="string"&&n.add(s),o=Object.getPrototypeOf(o)}n.size!==0&&Object.defineProperty(e,Vpn,{value:n,enumerable:!1,configurable:!0})}function C2(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,Vpn)){let n=t[Vpn];if(n&&typeof n.has=="function"&&n.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}function GYr(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function JYr({requestedResource:e,configuredResource:t}){let n=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(n.origin!==o.origin||n.pathname.length<o.pathname.length)return!1;let s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",a=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return s.startsWith(a)}function a$(e){return e>=KYr}function Ypn(e){return e.filter(t=>!a$(t))}function $Me(e){return e.filter(t=>a$(t))}function ZYr(e){let t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(e.content?.some(n=>n.type==="text")??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}function I$s(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||YYr.some(t=>t in e)?e:{...e,content:[]}}function C$s(){let e=mV(()=>bc([$t(),Gs(),kc(),Bj(),cc($t(),e),Go(e)])),t=cc($t(),e),n=bc([$t(),Gs().int()]),o=$t(),s=Fr({ttl:Gs().optional()}),a=Fr({taskId:$t()}),l=nu({progressToken:n.optional(),"io.modelcontextprotocol/related-task":a.optional()}),u=Fr({_meta:l.optional()}),f=u.extend({task:s.optional()}),g=Fr({method:$t(),params:u.loose().optional()}),_=Fr({_meta:l.optional()}),b=Fr({method:$t(),params:_.loose().optional()}),w=nu({_meta:l.optional()}),T=bc([$t(),Gs().int()]),I=w.strict(),E=_.extend({requestId:T.optional(),reason:$t().optional()}),R=b.extend({method:si("notifications/cancelled"),params:E}),L=Fr({src:$t(),mimeType:$t().optional(),sizes:Go($t()).optional(),theme:Bu(["light","dark"]).optional()}),U=Fr({icons:Go(L).optional()}),B=Fr({name:$t(),title:$t().optional()}),z=B.extend({...B.shape,...U.shape,version:$t(),websiteUrl:$t().optional(),description:$t().optional()}),$=$L(Fr({applyDefaults:kc().optional()}),t),J=hz(Xv=>Xv&&typeof Xv=="object"&&!Array.isArray(Xv)&&Object.keys(Xv).length===0?{form:{}}:Xv,$L(Fr({form:$.optional(),url:t.optional()}),t.optional())),q=nu({list:t.optional(),cancel:t.optional(),requests:nu({sampling:nu({createMessage:t.optional()}).optional(),elicitation:nu({create:t.optional()}).optional()}).optional()}),ie=nu({list:t.optional(),cancel:t.optional(),requests:nu({tools:nu({call:t.optional()}).optional()}).optional()}),ae=Fr({experimental:cc($t(),t).optional(),sampling:Fr({context:t.optional(),tools:t.optional()}).optional(),elicitation:J.optional(),roots:Fr({listChanged:kc().optional()}).optional(),tasks:q.optional(),extensions:cc($t(),t).optional()}),Ce=u.extend({protocolVersion:$t(),capabilities:ae,clientInfo:z}),pe=g.extend({method:si("initialize"),params:Ce}),ze=Fr({experimental:cc($t(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:Fr({listChanged:kc().optional()}).optional(),resources:Fr({subscribe:kc().optional(),listChanged:kc().optional()}).optional(),tools:Fr({listChanged:kc().optional()}).optional(),tasks:ie.optional(),extensions:cc($t(),t).optional()}),rt=w.extend({protocolVersion:$t(),capabilities:ze,serverInfo:z,instructions:$t().optional()}),Pe=b.extend({method:si("notifications/initialized"),params:_.optional()}),Tt=g.extend({method:si("ping"),params:u.optional()}),Ye=Fr({progress:Gs(),total:xl(Gs()),message:xl($t())}),Fe=Fr({..._.shape,...Ye.shape,progressToken:n}),St=b.extend({method:si("notifications/progress"),params:Fe}),kt=u.extend({cursor:o.optional()}),st=g.extend({params:kt.optional()}),$e=w.extend({nextCursor:o.optional()}),jt=Fr({uri:$t(),mimeType:xl($t()),_meta:cc($t(),Dl()).optional()}),Je=jt.extend({text:$t()}),Xe=$t().refine(Xv=>{try{return atob(Xv),!0}catch{return!1}},{message:"Invalid Base64 string"}),_t=jt.extend({blob:Xe}),Dt=Bu(["user","assistant"]),gn=Fr({audience:Go(Dt).optional(),priority:Gs().min(0).max(1).optional(),lastModified:jO.datetime({offset:!0}).optional()}),cn=Fr({...B.shape,...U.shape,uri:$t(),description:xl($t()),mimeType:xl($t()),size:xl(Gs()),annotations:gn.optional(),_meta:xl(nu({}))}),Fn=Fr({...B.shape,...U.shape,uriTemplate:$t(),description:xl($t()),mimeType:xl($t()),annotations:gn.optional(),_meta:xl(nu({}))}),on=st.extend({method:si("resources/list")}),dt=$e.extend({resources:Go(cn)}),we=st.extend({method:si("resources/templates/list")}),_e=$e.extend({resourceTemplates:Go(Fn)}),Pt=u.extend({uri:$t()}),ut=Pt,Mn=g.extend({method:si("resources/read"),params:ut}),Dr=w.extend({contents:Go(bc([Je,_t]))}),gr=b.extend({method:si("notifications/resources/list_changed"),params:_.optional()}),eo=Pt,to=g.extend({method:si("resources/subscribe"),params:eo}),oo=Pt,ro=g.extend({method:si("resources/unsubscribe"),params:oo}),Ji=_.extend({uri:$t()}),pi=b.extend({method:si("notifications/resources/updated"),params:Ji}),Wi=Fr({name:$t(),description:xl($t()),required:xl(kc())}),Ii=Fr({...B.shape,...U.shape,description:xl($t()),arguments:xl(Go(Wi)),_meta:xl(nu({}))}),Rs=st.extend({method:si("prompts/list")}),ht=$e.extend({prompts:Go(Ii)}),mr=u.extend({name:$t(),arguments:cc($t(),$t()).optional()}),mi=g.extend({method:si("prompts/get"),params:mr}),Ar=Fr({type:si("text"),text:$t(),annotations:gn.optional(),_meta:cc($t(),Dl()).optional()}),hi=Fr({type:si("image"),data:Xe,mimeType:$t(),annotations:gn.optional(),_meta:cc($t(),Dl()).optional()}),Js=Fr({type:si("audio"),data:Xe,mimeType:$t(),annotations:gn.optional(),_meta:cc($t(),Dl()).optional()}),qa=Fr({type:si("tool_use"),name:$t(),id:$t(),input:cc($t(),Dl()),_meta:cc($t(),Dl()).optional()}),li=Fr({type:si("resource"),resource:bc([Je,_t]),annotations:gn.optional(),_meta:cc($t(),Dl()).optional()}),oa=cn.extend({type:si("resource_link")}),Fs=bc([Ar,hi,Js,oa,li]),Qo=Fr({role:Dt,content:Fs}),gi=w.extend({description:$t().optional(),messages:Go(Qo)}),kn=b.extend({method:si("notifications/prompts/list_changed"),params:_.optional()}),Nn=Fr({title:$t().optional(),readOnlyHint:kc().optional(),destructiveHint:kc().optional(),idempotentHint:kc().optional(),openWorldHint:kc().optional()}),Ur=Fr({taskSupport:Bu(["required","optional","forbidden"]).optional()}),Vo=Fr({...B.shape,...U.shape,description:$t().optional(),inputSchema:Fr({type:si("object"),properties:cc($t(),e).optional(),required:Go($t()).optional()}).catchall(Dl()),outputSchema:Fr({type:si("object"),properties:cc($t(),e).optional(),required:Go($t()).optional()}).catchall(Dl()).optional(),annotations:Nn.optional(),execution:Ur.optional(),_meta:cc($t(),Dl()).optional()}),qe=st.extend({method:si("tools/list")}),Kt=$e.extend({tools:Go(Vo)}),Jt=w.extend({content:Go(Fs),structuredContent:cc($t(),Dl()).optional(),isError:kc().optional()}),en=f.extend({name:$t(),arguments:cc($t(),Dl()).optional()}),qn=g.extend({method:si("tools/call"),params:en}),Yr=b.extend({method:si("notifications/tools/list_changed"),params:_.optional()}),ei=Bu(["debug","info","notice","warning","error","critical","alert","emergency"]),ki=u.extend({level:ei}),ca=g.extend({method:si("logging/setLevel"),params:ki}),ks=_.extend({level:ei,logger:$t().optional(),data:Dl()}),Ud=b.extend({method:si("notifications/message"),params:ks}),zd=Fr({name:$t().optional()}),Bm=Fr({hints:Go(zd).optional(),costPriority:Gs().min(0).max(1).optional(),speedPriority:Gs().min(0).max(1).optional(),intelligencePriority:Gs().min(0).max(1).optional()}),Xf=Fr({mode:Bu(["auto","required","none"]).optional()}),kf=Fr({type:si("tool_result"),toolUseId:$t().describe("The unique identifier for the corresponding tool call."),content:Go(Fs),structuredContent:Fr({}).loose().optional(),isError:kc().optional(),_meta:cc($t(),Dl()).optional()}),qi=fV("type",[Ar,hi,Js]),Tm=fV("type",[Ar,hi,Js,qa,kf]),ev=Fr({role:Dt,content:bc([Tm,Go(Tm)]),_meta:cc($t(),Dl()).optional()}),E0=f.extend({messages:Go(ev),modelPreferences:Bm.optional(),systemPrompt:$t().optional(),includeContext:Bu(["none","thisServer","allServers"]).optional(),temperature:Gs().optional(),maxTokens:Gs().int(),stopSequences:Go($t()).optional(),metadata:t.optional(),tools:Go(Vo).optional(),toolChoice:Xf.optional()}),tv=g.extend({method:si("sampling/createMessage"),params:E0}),z_=w.extend({model:$t(),stopReason:xl(Bu(["endTurn","stopSequence","maxTokens"]).or($t())),role:Dt,content:qi}),Yv=w.extend({model:$t(),stopReason:xl(Bu(["endTurn","stopSequence","maxTokens","toolUse"]).or($t())),role:Dt,content:bc([Tm,Go(Tm)])}),Lw=Fr({type:si("boolean"),title:$t().optional(),description:$t().optional(),default:kc().optional()}),Tu=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),minLength:Gs().optional(),maxLength:Gs().optional(),format:Bu(["email","uri","date","date-time"]).optional(),default:$t().optional()}),t0=Fr({type:Bu(["number","integer"]),title:$t().optional(),description:$t().optional(),minimum:Gs().optional(),maximum:Gs().optional(),default:Gs().optional()}),Ub=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),enum:Go($t()),default:$t().optional()}),ta=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),oneOf:Go(Fr({const:$t(),title:$t()})),default:$t().optional()}),af=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),enum:Go($t()),enumNames:Go($t()).optional(),default:$t().optional()}),lP=bc([Ub,ta]),tE=Fr({type:si("array"),title:$t().optional(),description:$t().optional(),minItems:Gs().optional(),maxItems:Gs().optional(),items:Fr({type:si("string"),enum:Go($t())}),default:Go($t()).optional()}),IS=Fr({type:si("array"),title:$t().optional(),description:$t().optional(),minItems:Gs().optional(),maxItems:Gs().optional(),items:Fr({anyOf:Go(Fr({const:$t(),title:$t()}))}),default:Go($t()).optional()}),Fw=bc([tE,IS]),Vs=bc([af,lP,Fw]),Iu=bc([Vs,Lw,Tu,t0]),bs=f.extend({mode:si("form").optional(),message:$t(),requestedSchema:Fr({type:si("object"),properties:cc($t(),Iu),required:Go($t()).optional()}).catchall(Dl())}),A0=f.extend({mode:si("url"),message:$t(),elicitationId:$t(),url:$t().url()}),ri=bc([bs,A0]),la=g.extend({method:si("elicitation/create"),params:ri}),ul=_.extend({elicitationId:$t()}),py=b.extend({method:si("notifications/elicitation/complete"),params:ul}),X0=w.extend({action:Bu(["accept","decline","cancel"]),content:hz(Xv=>Xv===null?void 0:Xv,cc($t(),bc([$t(),Gs(),kc(),Go($t())])).optional())}),jw=Fr({type:si("ref/resource"),uri:$t()}),Ds=Fr({type:si("ref/prompt"),name:$t()}),e_=u.extend({ref:bc([Ds,jw]),argument:Fr({name:$t(),value:$t()}),context:Fr({arguments:cc($t(),$t()).optional()}).optional()}),nE=g.extend({method:si("completion/complete"),params:e_}),$_=w.extend({completion:nu({values:Go($t()).max(100),total:xl(Gs().int()),hasMore:xl(kc())})}),Va=Fr({uri:$t().startsWith("file://"),name:$t().optional(),_meta:cc($t(),Dl()).optional()}),lp=g.extend({method:si("roots/list"),params:u.optional()}),Eh=w.extend({roots:Go(Va)}),rE=b.extend({method:si("notifications/roots/list_changed"),params:_.optional()}),cf=nu({ttl:Gs().optional(),pollInterval:Gs().optional()}),t_=Bu(["working","input_required","completed","failed","cancelled"]),q_=Fr({taskId:$t(),status:t_,ttl:bc([Gs(),Bj()]),createdAt:$t(),lastUpdatedAt:$t(),pollInterval:xl(Gs()),statusMessage:xl($t())}),zb=w.extend({task:q_}),Yl=_.merge(q_),dh=b.extend({method:si("notifications/tasks/status"),params:Yl}),X1=g.extend({method:si("tasks/get"),params:u.extend({taskId:$t()})}),nD=w.merge(q_),ox=g.extend({method:si("tasks/result"),params:u.extend({taskId:$t()})}),eZ=w.loose(),Sd=st.extend({method:si("tasks/list")}),Ah=$e.extend({tasks:Go(q_)}),U8=g.extend({method:si("tasks/cancel"),params:u.extend({taskId:$t()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:o,TaskMetadataSchema:s,RelatedTaskMetadataSchema:a,RequestMetaSchema:l,BaseRequestParamsSchema:u,TaskAugmentedRequestParamsSchema:f,RequestSchema:g,NotificationsParamsSchema:_,NotificationSchema:b,ResultSchema:w,RequestIdSchema:T,EmptyResultSchema:I,CancelledNotificationParamsSchema:E,CancelledNotificationSchema:R,IconSchema:L,IconsSchema:U,BaseMetadataSchema:B,ImplementationSchema:z,ClientTasksCapabilitySchema:q,ServerTasksCapabilitySchema:ie,ClientCapabilitiesSchema:ae,InitializeRequestParamsSchema:Ce,InitializeRequestSchema:pe,ServerCapabilitiesSchema:ze,InitializeResultSchema:rt,InitializedNotificationSchema:Pe,PingRequestSchema:Tt,ProgressSchema:Ye,ProgressNotificationParamsSchema:Fe,ProgressNotificationSchema:St,PaginatedRequestParamsSchema:kt,PaginatedRequestSchema:st,PaginatedResultSchema:$e,ResourceContentsSchema:jt,TextResourceContentsSchema:Je,BlobResourceContentsSchema:_t,RoleSchema:Dt,AnnotationsSchema:gn,ResourceSchema:cn,ResourceTemplateSchema:Fn,ListResourcesRequestSchema:on,ListResourcesResultSchema:dt,ListResourceTemplatesRequestSchema:we,ListResourceTemplatesResultSchema:_e,ResourceRequestParamsSchema:Pt,ReadResourceRequestParamsSchema:ut,ReadResourceRequestSchema:Mn,ReadResourceResultSchema:Dr,ResourceListChangedNotificationSchema:gr,SubscribeRequestParamsSchema:eo,SubscribeRequestSchema:to,UnsubscribeRequestParamsSchema:oo,UnsubscribeRequestSchema:ro,ResourceUpdatedNotificationParamsSchema:Ji,ResourceUpdatedNotificationSchema:pi,PromptArgumentSchema:Wi,PromptSchema:Ii,ListPromptsRequestSchema:Rs,ListPromptsResultSchema:ht,GetPromptRequestParamsSchema:mr,GetPromptRequestSchema:mi,TextContentSchema:Ar,ImageContentSchema:hi,AudioContentSchema:Js,ToolUseContentSchema:qa,EmbeddedResourceSchema:li,ResourceLinkSchema:oa,ContentBlockSchema:Fs,PromptMessageSchema:Qo,GetPromptResultSchema:gi,PromptListChangedNotificationSchema:kn,ToolAnnotationsSchema:Nn,ToolExecutionSchema:Ur,ToolSchema:Vo,ListToolsRequestSchema:qe,ListToolsResultSchema:Kt,CallToolResultSchema:Jt,CallToolRequestParamsSchema:en,CallToolRequestSchema:qn,ToolListChangedNotificationSchema:Yr,LoggingLevelSchema:ei,SetLevelRequestParamsSchema:ki,SetLevelRequestSchema:ca,LoggingMessageNotificationParamsSchema:ks,LoggingMessageNotificationSchema:Ud,ModelHintSchema:zd,ModelPreferencesSchema:Bm,ToolChoiceSchema:Xf,ToolResultContentSchema:kf,SamplingContentSchema:qi,SamplingMessageContentBlockSchema:Tm,SamplingMessageSchema:ev,CreateMessageRequestParamsSchema:E0,CreateMessageRequestSchema:tv,CreateMessageResultSchema:z_,CreateMessageResultWithToolsSchema:Yv,BooleanSchemaSchema:Lw,StringSchemaSchema:Tu,NumberSchemaSchema:t0,UntitledSingleSelectEnumSchemaSchema:Ub,TitledSingleSelectEnumSchemaSchema:ta,LegacyTitledEnumSchemaSchema:af,SingleSelectEnumSchemaSchema:lP,UntitledMultiSelectEnumSchemaSchema:tE,TitledMultiSelectEnumSchemaSchema:IS,MultiSelectEnumSchemaSchema:Fw,EnumSchemaSchema:Vs,PrimitiveSchemaDefinitionSchema:Iu,ElicitRequestFormParamsSchema:bs,ElicitRequestURLParamsSchema:A0,ElicitRequestParamsSchema:ri,ElicitRequestSchema:la,ElicitationCompleteNotificationParamsSchema:ul,ElicitationCompleteNotificationSchema:py,ElicitResultSchema:X0,ResourceTemplateReferenceSchema:jw,PromptReferenceSchema:Ds,CompleteRequestParamsSchema:e_,CompleteRequestSchema:nE,CompleteResultSchema:$_,RootSchema:Va,ListRootsRequestSchema:lp,ListRootsResultSchema:Eh,RootsListChangedNotificationSchema:rE,TaskCreationParamsSchema:cf,TaskStatusSchema:t_,TaskSchema:q_,CreateTaskResultSchema:zb,TaskStatusNotificationParamsSchema:Yl,TaskStatusNotificationSchema:dh,GetTaskRequestSchema:X1,GetTaskResultSchema:nD,GetTaskPayloadRequestSchema:ox,GetTaskPayloadResultSchema:eZ,ListTasksRequestSchema:Sd,ListTasksResultSchema:Ah,CancelTaskRequestSchema:U8,CancelTaskResultSchema:w.merge(q_),ClientRequestSchema:bc([Tt,pe,nE,ca,mi,Rs,on,we,Mn,to,ro,qn,qe,X1,ox,Sd,U8]),ClientNotificationSchema:bc([R,St,Pe,rE,dh]),ClientResultSchema:bc([I,z_,Yv,X0,Eh,nD,Ah,zb]),ServerRequestSchema:bc([Tt,tv,la,lp,X1,ox,Sd,U8]),ServerNotificationSchema:bc([R,St,Ud,pi,gr,Yr,kn,dh,py]),ServerResultSchema:bc([I,rt,$_,gi,ht,dt,_e,Dr,Jt,Kt,nD,Ah,zb]),CallToolResultWireSchema:Dl().superRefine((Xv,pse)=>{if(!(typeof Xv!="object"||Xv===null||Array.isArray(Xv)||Xv.content!==void 0)){for(let fse of YYr)if(fse in Xv){pse.addIssue({code:"custom",message:`content is required when the body carries '${fse}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(I$s).pipe(Jt)}}function XYr(){return E$s??=C$s()}function QYr(e){return e.type!=="object"}function LYr(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}function R$s(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(LYr(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let n=kYr(e.$schema)&&e.$recursiveAnchor!==!0,o=r((s,a)=>{if(Array.isArray(s))return s.map(f=>o(f,!1));if(s===null||typeof s!="object"||!a&&LYr(s.$id))return s;let l={},u=!1;for(let[f,g]of Object.entries(s))a?l[f]=o(g,!1):(f==="$ref"||f==="$dynamicRef")&&typeof g=="string"?l[f]=g==="#"?"#/properties/result":g.startsWith("#/")?`#/properties/result${g.slice(1)}`:g:f==="$recursiveRef"&&g==="#"&&n?u=!0:A$s.has(f)?l[f]=g:P$s.has(f)?l[f]=o(g,!0):l[f]=o(g,!1);return u&&("$ref"in l?l.allOf=[...Array.isArray(l.allOf)?l.allOf:[],{$ref:"#/properties/result"}]:l.$ref="#/properties/result"),l},"rewriteRefs");return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}function Xpn(){if(but)return but;let e=XYr();return but={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},but}function nXr(e){return Object.prototype.hasOwnProperty.call(eXr,e)}function rXr(e){return Object.prototype.hasOwnProperty.call(tXr,e)}function O$s(e){return Object.prototype.hasOwnProperty.call(D$s,e)}function M$s(e){return O$s(e)?Xpn().resultSchemas[e]:void 0}function N$s(e){return nXr(e)?Xpn().requestSchemas[e]:void 0}function L$s(e){return rXr(e)?Xpn().notificationSchemas[e]:void 0}function Hpn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Sut(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:"invalid",message:String(n.error)}}function jYr(e){return Hpn(e)&&Hpn(e.outputSchema)&&QYr(e.outputSchema)}function F$s(){let e=mV(()=>bc([$t(),Gs(),kc(),Bj(),cc($t(),e),Go(e)])),t=cc($t(),e),n=bc([$t(),Gs().int()]),o=$t(),s=bc([$t(),Gs().int()]),a=Bu(["user","assistant"]),l=Bu(["debug","info","notice","warning","error","critical","alert","emergency"]),u=$t().refine(Ah=>{try{return atob(Ah),!0}catch{return!1}},{message:"Invalid Base64 string"}),f=Fr({ttl:Gs().optional()}),g=Fr({taskId:$t()}),_=nu({progressToken:n.optional(),"io.modelcontextprotocol/related-task":g.optional()}),b=Fr({_meta:_.optional()}),w=b.extend({task:f.optional()}),T=Fr({_meta:_.optional()}),I=Fr({method:$t(),params:T.loose().optional()}),E=Fr({src:$t(),mimeType:$t().optional(),sizes:Go($t()).optional(),theme:Bu(["light","dark"]).optional()}),R=Fr({icons:Go(E).optional()}),L=Fr({name:$t(),title:$t().optional()}),U=L.extend({...L.shape,...R.shape,version:$t(),websiteUrl:$t().optional(),description:$t().optional()}),B=$L(Fr({applyDefaults:kc().optional()}),t),z=hz(Ah=>Ah&&typeof Ah=="object"&&!Array.isArray(Ah)&&Object.keys(Ah).length===0?{form:{}}:Ah,$L(Fr({form:B.optional(),url:t.optional()}),t.optional())),$=nu({list:t.optional(),cancel:t.optional(),requests:nu({sampling:nu({createMessage:t.optional()}).optional(),elicitation:nu({create:t.optional()}).optional()}).optional()}),J=nu({list:t.optional(),cancel:t.optional(),requests:nu({tools:nu({call:t.optional()}).optional()}).optional()}),q=Fr({experimental:cc($t(),t).optional(),sampling:Fr({context:t.optional(),tools:t.optional()}).optional(),elicitation:z.optional(),roots:Fr({listChanged:kc().optional()}).optional(),tasks:$.optional(),extensions:cc($t(),t).optional()}),ie=Fr({experimental:cc($t(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:Fr({listChanged:kc().optional()}).optional(),resources:Fr({subscribe:kc().optional(),listChanged:kc().optional()}).optional(),tools:Fr({listChanged:kc().optional()}).optional(),tasks:J.optional(),extensions:cc($t(),t).optional()}),ae=Fr({progress:Gs(),total:xl(Gs()),message:xl($t())}),Ce=Fr({...T.shape,...ae.shape,progressToken:n}),pe=I.extend({method:si("notifications/progress"),params:Ce}),ze=T.extend({level:l,logger:$t().optional(),data:Dl()}),rt=I.extend({method:si("notifications/message"),params:ze}),Pe=Fr({uri:$t(),mimeType:xl($t()),_meta:cc($t(),Dl()).optional()}),Tt=Pe.extend({text:$t()}),Ye=Pe.extend({blob:u}),Fe=Fr({audience:Go(a).optional(),priority:Gs().min(0).max(1).optional(),lastModified:jO.datetime({offset:!0}).optional()}),St=Fr({...L.shape,...R.shape,uri:$t(),description:xl($t()),mimeType:xl($t()),size:xl(Gs()),annotations:Fe.optional(),_meta:xl(nu({}))}),kt=Fr({...L.shape,...R.shape,uriTemplate:$t(),description:xl($t()),mimeType:xl($t()),annotations:Fe.optional(),_meta:xl(nu({}))}),st=I.extend({method:si("notifications/resources/list_changed"),params:T.optional()}),$e=T.extend({uri:$t()}),jt=I.extend({method:si("notifications/resources/updated"),params:$e}),Je=Fr({name:$t(),description:xl($t()),required:xl(kc())}),Xe=Fr({...L.shape,...R.shape,description:xl($t()),arguments:xl(Go(Je)),_meta:xl(nu({}))}),_t=I.extend({method:si("notifications/prompts/list_changed"),params:T.optional()}),Dt=Fr({type:si("text"),text:$t(),annotations:Fe.optional(),_meta:cc($t(),Dl()).optional()}),gn=Fr({type:si("image"),data:u,mimeType:$t(),annotations:Fe.optional(),_meta:cc($t(),Dl()).optional()}),cn=Fr({type:si("audio"),data:u,mimeType:$t(),annotations:Fe.optional(),_meta:cc($t(),Dl()).optional()}),Fn=Fr({type:si("tool_use"),name:$t(),id:$t(),input:cc($t(),Dl()),_meta:cc($t(),Dl()).optional()}),on=Fr({type:si("resource"),resource:bc([Tt,Ye]),annotations:Fe.optional(),_meta:cc($t(),Dl()).optional()}),dt=St.extend({type:si("resource_link")}),we=bc([Dt,gn,cn,dt,on]),_e=Fr({role:a,content:we}),Pt=Fr({title:$t().optional(),readOnlyHint:kc().optional(),destructiveHint:kc().optional(),idempotentHint:kc().optional(),openWorldHint:kc().optional()}),ut=I.extend({method:si("notifications/tools/list_changed"),params:T.optional()}),Mn=Fr({name:$t().optional()}),Dr=Fr({hints:Go(Mn).optional(),costPriority:Gs().min(0).max(1).optional(),speedPriority:Gs().min(0).max(1).optional(),intelligencePriority:Gs().min(0).max(1).optional()}),gr=Fr({mode:Bu(["auto","required","none"]).optional()}),eo=Fr({type:si("boolean"),title:$t().optional(),description:$t().optional(),default:kc().optional()}),to=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),minLength:Gs().optional(),maxLength:Gs().optional(),format:Bu(["email","uri","date","date-time"]).optional(),default:$t().optional()}),oo=Fr({type:Bu(["number","integer"]),title:$t().optional(),description:$t().optional(),minimum:Gs().optional(),maximum:Gs().optional(),default:Gs().optional()}),ro=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),enum:Go($t()),default:$t().optional()}),Ji=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),oneOf:Go(Fr({const:$t(),title:$t()})),default:$t().optional()}),pi=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),enum:Go($t()),enumNames:Go($t()).optional(),default:$t().optional()}),Wi=bc([ro,Ji]),Ii=Fr({type:si("array"),title:$t().optional(),description:$t().optional(),minItems:Gs().optional(),maxItems:Gs().optional(),items:Fr({type:si("string"),enum:Go($t())}),default:Go($t()).optional()}),Rs=Fr({type:si("array"),title:$t().optional(),description:$t().optional(),minItems:Gs().optional(),maxItems:Gs().optional(),items:Fr({anyOf:Go(Fr({const:$t(),title:$t()}))}),default:Go($t()).optional()}),ht=bc([Ii,Rs]),mr=bc([pi,Wi,ht]),mi=bc([mr,eo,to,oo]),Ar=w.extend({mode:si("form").optional(),message:$t(),requestedSchema:Fr({type:si("object"),properties:cc($t(),mi),required:Go($t()).optional()}).catchall(Dl())}),hi=Fr({type:si("ref/resource"),uri:$t()}),Js=Fr({type:si("ref/prompt"),name:$t()}),qa=Fr({uri:$t().startsWith("file://"),name:$t().optional(),_meta:cc($t(),Dl()).optional()}),li=q.shape,oa=Fr({experimental:li.experimental,sampling:li.sampling,elicitation:li.elicitation,roots:li.roots,extensions:li.extensions}),Fs=ie.shape,Qo=Fr({experimental:Fs.experimental,logging:Fs.logging,completions:Fs.completions,prompts:Fs.prompts,resources:Fs.resources,tools:Fs.tools,extensions:Fs.extensions}),gi=nu({progressToken:n.optional(),[n$]:$t(),[lge]:U.optional(),[Rre]:oa,[uge]:l.optional()}),kn=Fr({...L.shape,...R.shape,description:$t().optional(),inputSchema:nu({$schema:$t().optional(),type:si("object")}),outputSchema:nu({$schema:$t().optional()}).optional(),annotations:Pt.optional(),_meta:cc($t(),Dl()).optional()}),Nn=Fr({type:si("tool_result"),toolUseId:$t(),content:Go(we),structuredContent:Dl().optional(),isError:kc().optional(),_meta:cc($t(),Dl()).optional()}),Ur=bc([Dt,gn,cn,Fn,Nn]),Vo=Fr({role:a,content:bc([Ur,Go(Ur)]),_meta:cc($t(),Dl()).optional()}),qe=$t(),Kt=nu({[r$]:U.optional().catch(void 0)}),Jt=Kt.optional();function en(Ah){return nu({_meta:Jt,resultType:qe.default("complete"),...Ah})}r(en,"wireResult");let qn=en({}),Yr=en({nextCursor:o.optional()}),ei=en({content:Go(we),structuredContent:Dl().optional(),isError:kc().optional()}),ki=en({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),tools:Go(kn),nextCursor:o.optional()}),ca=en({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),prompts:Go(Xe),nextCursor:o.optional()}),ks=en({description:$t().optional(),messages:Go(_e)}),Ud=en({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),resources:Go(St),nextCursor:o.optional()}),zd=en({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),resourceTemplates:Go(kt),nextCursor:o.optional()}),Bm=en({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),contents:Go(bc([Tt,Ye]))}),Xf=en({completion:Fr({values:Go($t()).max(100),total:Gs().int().optional(),hasMore:kc().optional()}).loose()}),kf=en({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"])}),qi=en({ttlMs:Gs().int().min(0).catch(0),cacheScope:Bu(["public","private"]).catch("private"),supportedVersions:Go($t()),capabilities:Qo,instructions:$t().optional()}),Tm=Fr({messages:Go(Vo),modelPreferences:Dr.optional(),systemPrompt:$t().optional(),includeContext:Bu(["none","thisServer","allServers"]).optional(),temperature:Gs().optional(),maxTokens:Gs().int(),stopSequences:Go($t()).optional(),metadata:t.optional(),tools:Go(kn).optional(),toolChoice:gr.optional()}),ev=Fr({method:si("sampling/createMessage"),params:Tm}),E0=Fr({method:si("roots/list"),params:Fr({_meta:cc($t(),Dl()).optional()}).optional()}),tv=Fr({...Vo.shape,model:$t(),stopReason:$t().optional()}),z_=Fr({roots:Go(qa)}),Yv=Fr({action:Bu(["accept","decline","cancel"]),content:cc($t(),bc([$t(),Gs(),kc(),Go($t())])).optional()}),Lw=Fr({mode:si("url"),message:$t(),url:$t().url()}),Tu=bc([Ar,Lw]),t0=Fr({method:si("elicitation/create"),params:Tu}),Ub=bc([ev,E0,t0]),ta=bc([tv,z_,Yv]),af=cc($t(),Ub),lP=cc($t(),ta),tE=en({inputRequests:af.optional(),requestState:$t().optional()}),IS={inputResponses:lP.optional(),requestState:$t().optional()},Fw=Fr({_meta:gi,...IS}),Vs=nu({progressToken:n.optional()});function Iu(Ah,U8){return Fr({method:si(Ah),params:Fr({_meta:gi,...U8})})}r(Iu,"wireRequest");function bs(Ah,U8){return Fr({method:si(Ah),params:Fr({_meta:Vs.optional(),...U8}).optional()})}r(bs,"dispatchRequest");let A0={name:$t(),arguments:cc($t(),Dl()).optional(),...IS},ri={cursor:o.optional()},la=Iu("tools/call",A0),ul=Iu("tools/list",ri),py=Iu("prompts/list",ri),X0=Iu("prompts/get",{name:$t(),arguments:cc($t(),$t()).optional(),...IS}),jw=Iu("resources/list",ri),Ds=Iu("resources/templates/list",ri),e_=Iu("resources/read",{uri:$t(),...IS}),nE={ref:bc([Js,hi]),argument:Fr({name:$t(),value:$t()}),context:Fr({arguments:cc($t(),$t()).optional()}).optional()},$_=Iu("completion/complete",nE),Va=Iu("server/discover",{}),lp=Fr({toolsListChanged:kc().optional(),promptsListChanged:kc().optional(),resourcesListChanged:kc().optional(),resourceSubscriptions:Go($t()).optional()}),Eh={notifications:lp},rE=Iu("subscriptions/listen",Eh),cf=Kt.extend({"io.modelcontextprotocol/subscriptionId":s}),t_=nu({_meta:cf,resultType:qe.default("complete")}),q_={"tools/call":bs("tools/call",A0),"tools/list":bs("tools/list",ri),"prompts/get":bs("prompts/get",{name:$t(),arguments:cc($t(),$t()).optional()}),"prompts/list":bs("prompts/list",ri),"resources/list":bs("resources/list",ri),"resources/templates/list":bs("resources/templates/list",ri),"resources/read":bs("resources/read",{uri:$t()}),"completion/complete":bs("completion/complete",nE),"server/discover":bs("server/discover",{}),"subscriptions/listen":bs("subscriptions/listen",Eh)};function zb(Ah){return nu({_meta:Jt,...Ah})}r(zb,"liftedResult");let Yl={"tools/call":zb({content:Go(we),structuredContent:Dl().optional(),isError:kc().optional()}),"tools/list":zb({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),tools:Go(kn),nextCursor:o.optional()}),"prompts/get":zb({description:$t().optional(),messages:Go(_e)}),"prompts/list":zb({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),prompts:Go(Xe),nextCursor:o.optional()}),"resources/list":zb({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),resources:Go(St),nextCursor:o.optional()}),"resources/templates/list":zb({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),resourceTemplates:Go(kt),nextCursor:o.optional()}),"resources/read":zb({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),contents:Go(bc([Tt,Ye]))}),"completion/complete":zb({completion:Fr({values:Go($t()).max(100),total:Gs().int().optional(),hasMore:kc().optional()}).loose()}),"server/discover":zb({ttlMs:Gs().int().min(0).catch(0),cacheScope:Bu(["public","private"]).catch("private"),supportedVersions:Go($t()),capabilities:Qo,instructions:$t().optional()}),"subscriptions/listen":zb({})},dh=nu({"io.modelcontextprotocol/subscriptionId":s.optional()}),X1=Fr({method:si("notifications/subscriptions/acknowledged"),params:Fr({_meta:dh.optional(),notifications:lp})}),nD=Fr({_meta:dh.optional(),requestId:s,reason:$t().optional()}),ox=Fr({method:si("notifications/cancelled"),params:nD}),eZ={"notifications/cancelled":ox,"notifications/progress":pe,"notifications/message":rt,"notifications/resources/updated":jt,"notifications/resources/list_changed":st,"notifications/tools/list_changed":ut,"notifications/prompts/list_changed":_t,"notifications/subscriptions/acknowledged":X1},Sd=r(Ah=>Fr({jsonrpc:si("2.0"),id:bc([$t(),Gs().int()]),result:Ah}).strict(),"wireResultResponse");return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:o,RequestIdSchema:s,RoleSchema:a,LoggingLevelSchema:l,TaskMetadataSchema:f,RelatedTaskMetadataSchema:g,RequestMetaSchema:_,BaseRequestParamsSchema:b,TaskAugmentedRequestParamsSchema:w,NotificationsParamsSchema:T,NotificationSchema:I,IconSchema:E,IconsSchema:R,BaseMetadataSchema:L,ImplementationSchema:U,ClientTasksCapabilitySchema:$,ServerTasksCapabilitySchema:J,ClientCapabilitiesSchema:q,ServerCapabilitiesSchema:ie,ProgressSchema:ae,ProgressNotificationParamsSchema:Ce,ProgressNotificationSchema:pe,LoggingMessageNotificationParamsSchema:ze,LoggingMessageNotificationSchema:rt,ResourceContentsSchema:Pe,TextResourceContentsSchema:Tt,BlobResourceContentsSchema:Ye,AnnotationsSchema:Fe,ResourceSchema:St,ResourceTemplateSchema:kt,ResourceListChangedNotificationSchema:st,ResourceUpdatedNotificationParamsSchema:$e,ResourceUpdatedNotificationSchema:jt,PromptArgumentSchema:Je,PromptSchema:Xe,PromptListChangedNotificationSchema:_t,TextContentSchema:Dt,ImageContentSchema:gn,AudioContentSchema:cn,ToolUseContentSchema:Fn,EmbeddedResourceSchema:on,ResourceLinkSchema:dt,ContentBlockSchema:we,PromptMessageSchema:_e,ToolAnnotationsSchema:Pt,ToolListChangedNotificationSchema:ut,ModelHintSchema:Mn,ModelPreferencesSchema:Dr,ToolChoiceSchema:gr,BooleanSchemaSchema:eo,StringSchemaSchema:to,NumberSchemaSchema:oo,UntitledSingleSelectEnumSchemaSchema:ro,TitledSingleSelectEnumSchemaSchema:Ji,LegacyTitledEnumSchemaSchema:pi,SingleSelectEnumSchemaSchema:Wi,UntitledMultiSelectEnumSchemaSchema:Ii,TitledMultiSelectEnumSchemaSchema:Rs,MultiSelectEnumSchemaSchema:ht,EnumSchemaSchema:mr,PrimitiveSchemaDefinitionSchema:mi,ElicitRequestFormParamsSchema:Ar,ResourceTemplateReferenceSchema:hi,PromptReferenceSchema:Js,RootSchema:qa,ClientCapabilities2026Schema:oa,ServerCapabilities2026Schema:Qo,RequestMetaEnvelopeSchema:gi,ToolSchema:kn,ToolResultContentSchema:Nn,SamplingMessageContentBlockSchema:Ur,SamplingMessageSchema:Vo,ResultTypeSchema:qe,ResultMetaSchema:Kt,ResultSchema:qn,PaginatedResultSchema:Yr,CallToolResultSchema:ei,ListToolsResultSchema:ki,ListPromptsResultSchema:ca,GetPromptResultSchema:ks,ListResourcesResultSchema:Ud,ListResourceTemplatesResultSchema:zd,ReadResourceResultSchema:Bm,CompleteResultSchema:Xf,CacheableResultSchema:kf,DiscoverResultSchema:qi,CreateMessageRequestParamsSchema:Tm,CreateMessageRequestSchema:ev,ListRootsRequestSchema:E0,CreateMessageResultSchema:tv,ListRootsResultSchema:z_,ElicitResultSchema:Yv,ElicitRequestURLParamsSchema:Lw,ElicitRequestParamsSchema:Tu,ElicitRequestSchema:t0,InputRequestSchema:Ub,InputResponseSchema:ta,InputRequestsSchema:af,InputResponsesSchema:lP,InputRequiredResultSchema:tE,InputResponseRequestParamsSchema:Fw,CallToolRequestSchema:la,ListToolsRequestSchema:ul,ListPromptsRequestSchema:py,GetPromptRequestSchema:X0,ListResourcesRequestSchema:jw,ListResourceTemplatesRequestSchema:Ds,ReadResourceRequestSchema:e_,CompleteRequestSchema:$_,DiscoverRequestSchema:Va,SubscriptionFilterSchema:lp,SubscriptionsListenRequestSchema:rE,SubscriptionsListenResultMetaSchema:cf,SubscriptionsListenResultSchema:t_,dispatchRequestSchemas:q_,dispatchResultSchemas:Yl,NotificationMetaSchema:dh,SubscriptionsAcknowledgedNotificationSchema:X1,CancelledNotificationParamsSchema:nD,CancelledNotificationSchema:ox,notificationSchemas2026:eZ,JSONRPCResultResponseSchema:Sd(qn),CallToolResultResponseSchema:Sd(bc([ei,tE])),ListToolsResultResponseSchema:Sd(ki),ListPromptsResultResponseSchema:Sd(ca),GetPromptResultResponseSchema:Sd(bc([ks,tE])),ListResourcesResultResponseSchema:Sd(Ud),ListResourceTemplatesResultResponseSchema:Sd(zd),ReadResourceResultResponseSchema:Sd(bc([Bm,tE])),CompleteResultResponseSchema:Sd(Xf),DiscoverResultResponseSchema:Sd(qi)}}function Nre(){return j$s??=F$s()}function U$s(e){return B$s.includes(e)}function z$s(e){return e[efn]}function oXr(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function iXr(e){return e==="public"||e==="private"}function V$s(e,t){let n=t.resultType;if(n===void 0)return{...t,resultType:"complete"};if(n==="complete"||W$s.includes(e))return t;throw new oh(Du.InternalError,`Handler for ${e} returned resultType '${String(n)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function H$s(e,t){let n=z$s(t);if(t.resultType!=="complete"||!U$s(e))return n===void 0?t:Y$s(t);let o=t,s=oXr(o.ttlMs)?o.ttlMs:K$s(n),a=iXr(o.cacheScope)?o.cacheScope:Z$s(n),l={...o,ttlMs:s,cacheScope:a};return delete l[efn],l}function G$s(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function J$s(e,t){if(t===void 0)return e;let n=e._meta;return n===void 0?{...e,_meta:{[r$]:t}}:!G$s(n)||n[r$]!==void 0?e:{...e,_meta:{...n,[r$]:t}}}function K$s(e){return e!==void 0&&oXr(e.ttlMs)?e.ttlMs:$$s}function Z$s(e){return e!==void 0&&iXr(e.cacheScope)?e.cacheScope:q$s}function Y$s(e){let t={...e};return delete t[efn],t}function uXr(){if(wut)return wut;let e=Nre();return wut={request:{"elicitation/create":Fr({method:si("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":Fr({method:si("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":Fr({method:si("roots/list"),params:nu({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},wut}function dXr(e){return X$s.includes(e)}function zpn(e){return dXr(e)?uXr().request[e]:void 0}function Q$s(e){return dXr(e)?uXr().response[e]:void 0}function fXr(e){return Object.prototype.hasOwnProperty.call(tfn,e)}function mXr(e){return Object.prototype.hasOwnProperty.call(pXr,e)}function e9s(e){return Object.prototype.hasOwnProperty.call(tfn,e)}function t9s(e){return fXr(e)?Nre().dispatchRequestSchemas[e]:void 0}function n9s(e){return e9s(e)?Nre().dispatchResultSchemas[e]:void 0}function r9s(e){return mXr(e)?Nre().notificationSchemas2026[e]:void 0}function jMe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function LMe(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:"invalid",message:String(n.error)}}function s9s(e,t){let n=t,o=!1,s=r(()=>(o||(n={...n},o=!0),n),"copy"),a=t.tools;e==="tools/list"&&Array.isArray(a)&&a.some(u=>jMe(u)&&"execution"in u)&&(s().tools=a.map(u=>{if(!jMe(u)||!("execution"in u))return u;let f={...u};return delete f.execution,f}));let l=t.capabilities;if(jMe(l)&&"tasks"in l){let u={...l};delete u.tasks,s().capabilities=u}return n}function a9s(){if(kut)return kut;let e=Nre();return kut={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},kut}function i$(e){return e!==void 0&&a$(e)?nfn:Qpn}function BYr(e){return e.revision!==void 0?i$(e.revision).era:e.era==="modern"?nfn.era:Qpn.era}function $pn(e){return hXr.some(t=>t.hasRequestMethod(e))}function qpn(e){return hXr.some(t=>t.hasNotificationMethod(e))}function ofn(e){let t=[],n=new Map,o=r((a,l,u)=>{if(a===null||typeof a!="object")return;let f=a;if(UYr in f){if(!u||l.length===0)return`${xut(l)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let _=f[UYr];if(typeof _!="string"||_.length===0)return`${xut(l)}: x-mcp-header MUST be a non-empty string`;if(!u9s.test(_))return`${xut(l)}: x-mcp-header '${_}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let b=typeof f.type=="string"?f.type:void 0;if(b===void 0||!d9s.has(b))return`${xut(l)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${b??"<none>"}`;let w=_.toLowerCase(),T=n.get(w);if(T!==void 0)return`x-mcp-header '${_}' is not case-insensitively unique (also declared as '${T}')`;n.set(w,_),t.push({path:l,headerName:_,type:b})}let g=f.properties;if(g!==null&&typeof g=="object")for(let[_,b]of Object.entries(g)){let w=o(b,[...l,_],u);if(w!==void 0)return w}for(let _ of p9s){let b=f[_];if(b===void 0)continue;let w=Array.isArray(b)?b:b!==null&&typeof b=="object"&&f9s.has(_)?Object.values(b):[b];for(let T of w){let I=o(T,[...l,`<${_}>`],!1);if(I!==void 0)return I}}},"visit"),s=o(e,[],!0);return s===void 0?{valid:!0,declarations:t}:{valid:!1,reason:s}}function xut(e){return e.length===0?"<root>":e.join(".")}function m9s(e){if(typeof e=="string")return e;if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e)?void 0:String(e)}function h9s(e){if(e.length===0||e.startsWith(vXr)&&e.endsWith(bXr)||e!==e.trim())return!0;for(let t=0;t<e.length;t++){let n=e.codePointAt(t);if(!(n===9||n>=32&&n<=126))return!0}return!1}function g9s(e){let t=new TextEncoder().encode(e),n="";for(let o of t)n+=String.fromCodePoint(o);return btoa(n)}function ifn(e){return h9s(e)?`${vXr}${g9s(e)}${bXr}`:e}function _9s(e,t){let n=e;for(let o of t){if(n===null||typeof n!="object")return;n=n[o]}return n}function SXr(e,t){let n={};for(let o of e){let s=_9s(t,o.path);if(s==null)continue;let a=m9s(s);a!==void 0&&(n[`${l9s}${o.headerName}`]=ifn(a))}return n}function Cut(e,t){return REe(e,t)}function FMe(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}function Gpn(e){if(e==null)return!1;let t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}function y9s(e,t="input"){let n=e["~standard"],o;if(n.jsonSchema)o=n.jsonSchema[t]({target:Jpn});else if(n.vendor==="zod"){if(!("_zod"in e))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");zYr||(zYr=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),o=zL(e,{target:Jpn,io:t})}else throw new Error(`Schema library "${n.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output")return o.type!==void 0?o:wXr(o)?{type:"object",...o}:o;if(o.type!==void 0&&o.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(o.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...o}}function wXr(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let n=e[t];if(Array.isArray(n)&&n.length>0)return n.every(o=>o!==null&&typeof o=="object"&&(o.type==="object"||wXr(o)))}return!1}function v9s(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}async function Wpn(e,t){let n=await e["~standard"].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(o=>v9s(o)).join(", ")}:{success:!0,data:n.value}}function b9s(e){let t=zL(e,{target:Jpn,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}function w9s(e){let t=S9s.exec(e),n=[void 0,-1,0];return t&&n.push(Number(t[1])),[!1,!0].flatMap(o=>[!1,!0].flatMap(s=>n.map(a=>jO.datetime({local:o,offset:s,precision:a}))))}function k9s(e,t){let n;switch(e){case"email":n=[$Je()];break;case"uri":n=[ape()];break;case"date":n=[jO.date()];break;case"date-time":n=w9s(t);break}return new Set(n.map(o=>b9s(o)).filter(o=>o!==void 0))}function x9s(e,t,n){return n!=="zod"?!0:k9s(e,t).has(t)}function UMe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function T9s(e){try{return y9s(e,"input")}catch(t){let n=t instanceof Error?t.message:String(t);throw new oh(Du.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${n}`)}}function sfn(e){return I9s.has(e)||e.startsWith("x-")}function A9s(e,t,n,o){if(!UMe(e))return e;let s=typeof e.type=="string"&&Object.hasOwn($Yr,e.type)?$Yr[e.type]:void 0;if(s===void 0)return e;let a={};for(let[l,u]of Object.entries(e))s.has(l)||sfn(l)?a[l]=u:l==="pattern"&&e.type==="string"&&typeof e.format=="string"?E9s.has(e.format)?(typeof u!="string"||!x9s(e.format,u,n))&&o.push(`${t}.${l}`):a[l]=u:o.push(`${t}.${l}`);return a}function P9s(e,t){let n={},o=[];for(let[s,a]of Object.entries(e))s==="properties"&&UMe(a)?n[s]=Object.fromEntries(Object.entries(a).map(([l,u])=>[l,A9s(u,`properties.${l}`,t,o)])):C9s.has(s)?n[s]=a:sfn(s)||o.push(s);if(o.length>0)throw new oh(Du.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return n}function R9s(e,t){if(!UMe(e.properties))return t;let n=Object.entries(e.properties).filter(([,o])=>!Cut(PMe,o).success).map(([o])=>`properties.${o}`);return n.length>0?n.join(", "):t}function Kpn(e,t,n=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((o,s)=>Kpn(o,t[s],`${n}[${s}]`)):!UMe(e)||!UMe(t)?[]:Object.entries(e).flatMap(([o,s])=>{let a=n?`${n}.${o}`:o;return Object.prototype.hasOwnProperty.call(t,o)?Kpn(s,t[o],a):sfn(o)?[]:[a]})}function D9s(e){if(!Gpn(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,n=P9s(T9s(e.requestedSchema),t),o=Cut(Sge.shape.requestedSchema,n);if(!o.success)throw new oh(Du.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${R9s(n,o.error.message)}`);let s=Kpn(n,o.data);if(s.length>0)throw new oh(Du.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${s.join(", ")}`);let a=(o.data.required??[]).filter(l=>!Object.prototype.hasOwnProperty.call(o.data.properties,l));if(a.length>0)throw new oh(Du.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${a.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}function O9s(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,n=typeof e.requestState=="string";if(!t&&!n)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}function kXr(e){return{autoFulfill:e?.autoFulfill??M9s,maxRounds:e?.maxRounds??N9s}}function F9s(e,t,n){let o=t!==void 0&&Object.keys(t).length>0;return!o&&n===void 0?e:{...e,...o&&{inputResponses:t},...n!==void 0&&{requestState:n}}}function j9s(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function B9s(e,t){return new Promise((n,o)=>{if(t?.aborted){o(t.reason instanceof rl?t.reason:new rl(Pc.RequestTimeout,String(t.reason)));return}let s=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e),a=r(()=>{clearTimeout(s),o(t?.reason instanceof rl?t.reason:new rl(Pc.RequestTimeout,String(t?.reason)))},"onAbort");t?.addEventListener("abort",a,{once:!0})})}function U9s(e){let t=new AbortController,n=r(()=>t.abort(e?.reason),"onOuterAbort");return e?.addEventListener("abort",n,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:r(o=>t.abort(o),"abort"),dispose:r(()=>e?.removeEventListener("abort",n),"dispose")}}async function z9s(e){let{config:t,method:n,originalParams:o,requestOptions:s,hooks:a,signal:l}=e,u=e.flowStartedAt??Date.now(),f=e.firstPayload,g=0;for(;;){if(g+=1,g>t.maxRounds)throw new rl(Pc.InputRequiredRoundsExceeded,j9s(n,t.maxRounds),{rounds:t.maxRounds,lastResult:{inputRequests:f.inputRequests,...f.requestState!==void 0&&{requestState:f.requestState}}});s.onprogress?.({progress:g,message:`Fulfilling input required by '${n}' (round ${g})`});let _=Object.entries(f.inputRequests??{}),b;if(_.length>0){let I=U9s(l);try{let E=await Promise.all(_.map(async([R,L])=>{try{return[R,await a.dispatchInputRequest(R,L,I.signal)]}catch(U){throw I.abort(U),U}}));b=Object.fromEntries(E)}finally{I.dispose()}}else await B9s(L9s,l);let w={...s.timeout!==void 0&&{timeout:s.timeout}};if(s.maxTotalTimeout!==void 0){let I=Date.now()-u,E=s.maxTotalTimeout-I;if(E<=0)throw new rl(Pc.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:s.maxTotalTimeout,totalElapsed:I});w.maxTotalTimeout=E}let T=await a.retry(F9s(o,b,f.requestState),w);if(_Xr(T)){f={inputRequests:T.inputRequests??{},...T.requestState!==void 0&&{requestState:T.requestState}};continue}return T}}function IXr(e,t){let n=e.slice(0,-6);xXr[n]=t,TXr[n]=o=>t.safeParse(o).success}function V9s(e){switch(e){case"initialize":case"notifications/initialized":return i$(void 0);case"server/discover":return i$(Iut);default:return}}function qYr(e,t){let n=e.params;if(!BMe(n))return{message:e,lifted:{}};let o=n._meta,s=BMe(o)?H9s.filter(f=>f in o):[],a=t==="request"?G9s.filter(f=>f in n):[];if(s.length===0&&a.length===0)return{message:e,lifted:{}};let l={},u={...n};if(s.length>0&&BMe(o)){let f={},g={...o};for(let _ of s)f[_]=o[_],delete g[_];l.envelope=f,Object.keys(g).length>0?u._meta=g:delete u._meta}for(let f of a)f==="inputResponses"&&(l.inputResponses=u[f]),f==="requestState"&&(l.requestState=u[f]),delete u[f];return{message:{...e,params:u},lifted:l}}function WYr(e,t){let n=e.validateResult(t,void 0);if(!(!n.ok&&n.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(o){let s=e.validateResult(t,o);return s.ok?{value:s.value}:{issues:[{message:s.reason==="invalid"?s.message:`not-in-era: ${t}`}]}}}}}function afn(e){return()=>e}function BMe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function AXr(e,t){let n={...e};for(let o in t){let s=o,a=t[s];if(a===void 0)continue;let l=n[s];n[s]=BMe(l)&&BMe(a)?{...l,...a}:a}return n}function Tut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Z9s(e){let t={},n=[];if(!Tut(e))return{accepted:t,droppedKeys:n};for(let[o,s]of Object.entries(e)){if(!Tut(s)||"method"in s||"result"in s){n.push(o);continue}t[o]=s}return{accepted:t,droppedKeys:n}}function VYr(e){throw new rl(Pc.SendFailed,`ctx.mcpReq.${e} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`)}function Y9s(e,t,n,o,s){return{sessionId:s,mcpReq:{id:e,method:t,_meta:n?._meta,requestState:afn(void 0),signal:o,send:r((()=>VYr("send")),"send"),notify:r(()=>VYr("notify"),"notify")}}}async function X9s(e,t,n,o,s){if(!Tut(o)||typeof o.method!="string")throw new rl(Pc.InvalidResult,`Invalid input request '${n}': each inputRequests entry must be an embedded request object with a method`,{key:n});let a=o.method;if(!t.hasInputRequestMethod(a))throw new rl(Pc.InvalidResult,`Invalid input request '${n}': '${a}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:n,method:a});let l=e.getRequestHandler(a);if(l===void 0)throw new rl(Pc.CapabilityNotSupported,`Cannot fulfil input request '${n}': no handler is registered for '${a}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:n,method:a});let u=Tut(o.params)?o.params:void 0;return await l({jsonrpc:"2.0",id:n,method:a,...u!==void 0&&{params:u}},e.buildContext(Y9s(n,a,u,s,e.sessionId)))}function Q9s(e,t){return{...e?.signal!==void 0&&{signal:e.signal},...e?.onprogress!==void 0&&{onprogress:e.onprogress},...e?.resetTimeoutOnProgress!==void 0&&{resetTimeoutOnProgress:e.resetTimeoutOnProgress},...e?.headers!==void 0&&{headers:e.headers},...t.timeout!==void 0&&{timeout:t.timeout},...t.maxTotalTimeout!==void 0&&{maxTotalTimeout:t.maxTotalTimeout},allowInputRequired:!0}}function PXr(e,t,n,o){let{codec:s,request:a,options:l,flowStartedAt:u}=o,f={inputRequests:n.inputRequests,...n.requestState!==void 0&&{requestState:n.requestState}},g={dispatchInputRequest:r((_,b,w)=>X9s(e,s,_,b,w),"dispatchInputRequest"),retry:r((_,b)=>o.retry(_,Q9s(l,b)),"retry")};return z9s({config:t,method:a.method,originalParams:a.params,firstPayload:f,flowStartedAt:u,signal:l?.signal,requestOptions:{...l?.timeout!==void 0&&{timeout:l.timeout},...l?.maxTotalTimeout!==void 0&&{maxTotalTimeout:l.maxTotalTimeout},...l?.onprogress!==void 0&&{onprogress:l.onprogress}},hooks:g})}function eqs(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState}}}function RXr(e){if(e)try{return nqs.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();return t===""||e.slice(t.length).includes(",")?void 0:t}}function OXr(e){return pB.parse(JSON.parse(e))}function lfn(e){return JSON.stringify(e)+`
|
|
2138
2138
|
`}function zMe(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function ufn(e=fetch,t){return t?async(n,o)=>e(n,{...t,...o,headers:o?.headers?{...zMe(t.headers),...zMe(o.headers)}:t.headers}):e}var Vpn,GF,s$,Pc,rl,JF,KYr,Zpn,YYr,E$s,A$s,P$s,eXr,tXr,D$s,but,tbl,nbl,FYr,Qpn,j$s,B$s,efn,Du,oh,aXr,cXr,Tge,lXr,$$s,q$s,W$s,X$s,wut,tfn,pXr,rbl,obl,o9s,i9s,nfn,kut,Iut,hXr,c9s,Fre,gXr,xge,Ige,_Xr,rfn,yXr,l9s,UYr,u9s,d9s,p9s,f9s,vXr,bXr,kge,ibl,sbl,zYr,Jpn,S9s,I9s,C9s,$Yr,E9s,abl,M9s,N9s,L9s,$9s,q9s,xXr,TXr,W9s,CXr,Eut,H9s,G9s,J9s,K9s,EXr,tqs,nqs,DXr,cfn,dfn=Y(()=>{hpn();gpn();NYr();tc();Vpn=Symbol.for("mcp.sdk.errorBrands");r(Lre,"stampErrorBrands");r(C2,"brandedHasInstance");GF=(function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e})({}),s$=class HYr extends Error{static{r(this,"OAuthError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return C2(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return C2(this,t)}constructor(t,n,o){super(n),this.code=t,this.errorUri=o,this.name="OAuthError",Lre(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}static fromResponse(t){return new HYr(t.error,t.error_description??t.error,t.error_uri)}},Pc=(function(e){return e.NotConnected="NOT_CONNECTED",e.AlreadyConnected="ALREADY_CONNECTED",e.NotInitialized="NOT_INITIALIZED",e.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",e.RequestTimeout="REQUEST_TIMEOUT",e.ConnectionClosed="CONNECTION_CLOSED",e.SendFailed="SEND_FAILED",e.InvalidResult="INVALID_RESULT",e.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",e.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",e.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",e.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",e.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",e.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",e.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",e.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",e.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",e.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",e.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",e})({}),rl=class extends Error{static{r(this,"SdkError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return C2(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return C2(this,e)}constructor(e,t,n){super(t),this.code=e,this.data=n,this.name="SdkError",Lre(this,new.target)}},JF=class extends rl{static{r(this,"SdkHttpError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,n){super(e,t,n),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};r(GYr,"resourceUrlFromServerUrl");r(JYr,"checkResourceAllowed");KYr="2026-07-28",Zpn=[KYr];r(a$,"isModernProtocolVersion");r(Ypn,"legacyProtocolVersions");r($Me,"modernProtocolVersions");r(ZYr,"appendTextFallbackForNonObject");YYr=["task","inputRequests","requestState"];r(I$s,"normalizeContentlessToolResult");r(C$s,"build$1");r(XYr,"buildSchemas2025");r(QYr,"isNonObjectJsonSchemaRoot");A$s=new Set(["const","enum","default","examples"]),P$s=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);r(LYr,"establishesNewBase");r(R$s,"wrapOutputSchemaForLegacy");eXr={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},tXr={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},D$s={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};r(Xpn,"registryMaps");r(nXr,"hasRequestMethod2025");r(rXr,"hasNotificationMethod2025");r(O$s,"hasResultMethod");r(M$s,"getResultSchema");r(N$s,"getRequestSchema");r(L$s,"getNotificationSchema");tbl=Object.keys(eXr),nbl=Object.keys(tXr);r(Hpn,"isPlainObject$4");r(Sut,"triState$1");FYr={ok:!1,reason:"not-in-era"};r(jYr,"toolNeedsLegacyWrap");Qpn={era:"2025-11-25",hasRequestMethod:nXr,hasNotificationMethod:rXr,validateRequest:r((e,t)=>Sut(N$s(e),t),"validateRequest"),validateResult:r((e,t)=>Sut(M$s(e),t),"validateResult"),validateNotification:r((e,t)=>Sut(L$s(e),t),"validateNotification"),hasInputRequestMethod:r(()=>!1,"hasInputRequestMethod"),validateInputRequest:r(()=>FYr,"validateInputRequest"),validateInputResponse:r(()=>FYr,"validateInputResponse"),samplingResultVariant:r(((e,t)=>{let n=XYr();return Sut(e?n.CreateMessageResultWithToolsSchema:n.CreateMessageResultSchema,t)}),"samplingResultVariant"),outboundEnvelope:r(e=>{},"outboundEnvelope"),validateEnvelopeMeta:r(e=>[],"validateEnvelopeMeta"),projectCallToolResult(e,t){let n=ZYr(e),o=n.structuredContent;if(o===void 0)return n;let s=typeof o!="object"||o===null||Array.isArray(o),a=t!==void 0&&QYr(t);return!s&&!a?n:{...n,structuredContent:{result:o}}},decodeResult(e,t){if(Hpn(t)&&"resultType"in t){let n={...t};return delete n.resultType,{kind:"complete",result:n}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;let n=t.tools;return!Array.isArray(n)||!n.some(o=>jYr(o))?t:{...t,tools:n.map(o=>jYr(o)?{...o,outputSchema:R$s(o.outputSchema)}:o)}},encodeErrorCode:r(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope:r(e=>{},"checkInboundEnvelope")};r(F$s,"build");r(Nre,"buildSchemas2026");B$s=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];r(U$s,"isCacheableResultMethod");efn=Symbol("modelcontextprotocol.resultCacheHintFallback");r(z$s,"cacheHintFallbackOf");r(oXr,"isValidCacheTtlMs");r(iXr,"isValidCacheScope");Du=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({}),oh=class sXr extends Error{static{r(this,"ProtocolError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return C2(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return C2(this,t)}constructor(t,n,o){super(n),this.code=t,this.data=o,this.name="ProtocolError",Lre(this,new.target)}static fromError(t,n,o){if(t===Du.UrlElicitationRequired&&o){let s=o;if(s.elicitations)return new cXr(s.elicitations,n)}if(t===Du.UnsupportedProtocolVersion&&o){let s=o;if(Array.isArray(s.supported)&&typeof s.requested=="string")return new Tge({supported:s.supported,requested:s.requested},n)}if(t===Du.InvalidParams||t===Du.ResourceNotFound){let s=o;if(typeof s?.uri=="string"&&(t===Du.ResourceNotFound||Object.keys(s).length===1))return new aXr(s.uri,n)}if(t===Du.MissingRequiredClientCapability&&o){let s=o;if(s.requiredCapabilities!==null&&typeof s.requiredCapabilities=="object"&&!Array.isArray(s.requiredCapabilities))return new lXr({requiredCapabilities:s.requiredCapabilities},n)}return new sXr(t,n,o)}},aXr=class extends oh{static{r(this,"ResourceNotFoundError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(Du.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},cXr=class extends oh{static{r(this,"UrlElicitationRequiredError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Du.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Tge=class extends oh{static{r(this,"UnsupportedProtocolVersionError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(Du.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},lXr=class extends oh{static{r(this,"MissingRequiredClientCapabilityError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(Du.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},$$s=0,q$s="private",W$s=["tools/call","prompts/get","resources/read"];r(V$s,"stampResultType");r(H$s,"fillCacheFields");r(G$s,"isPlainObject$3");r(J$s,"stampServerInfoMeta");r(K$s,"resolveTtlMs");r(Z$s,"resolveCacheScope");r(Y$s,"stripCacheHintFallback");X$s=["elicitation/create","sampling/createMessage","roots/list"];r(uXr,"inputSchemaMaps");r(dXr,"isInputRequestMethod2026");r(zpn,"getInputRequestSchema2026");r(Q$s,"getInputResponseSchema2026");tfn={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},pXr={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};r(fXr,"hasRequestMethod2026");r(mXr,"hasNotificationMethod2026");r(e9s,"hasResultMethod2026");r(t9s,"getRequestSchema2026");r(n9s,"getResultSchema2026");r(r9s,"getNotificationSchema2026");rbl=Object.keys(tfn),obl=Object.keys(pXr);r(jMe,"isPlainObject$2");r(LMe,"triState");o9s={ok:!1,reason:"not-in-era"},i9s=[n$,Rre];r(s9s,"enforceDeletedFields");nfn={era:"2026-07-28",hasRequestMethod:fXr,hasNotificationMethod:mXr,hasInputRequestMethod:r(e=>zpn(e)!==void 0,"hasInputRequestMethod"),validateRequest:r((e,t)=>LMe(t9s(e),t),"validateRequest"),validateResult:r((e,t)=>LMe(n9s(e),t),"validateResult"),validateNotification:r((e,t)=>LMe(r9s(e),t),"validateNotification"),validateInputRequest:r((e,t)=>LMe(zpn(e),t),"validateInputRequest"),validateInputResponse:r((e,t)=>LMe(Q$s(e),t),"validateInputResponse"),samplingResultVariant:r(()=>o9s,"samplingResultVariant"),outboundEnvelope(e){return{[n$]:e.protocolVersion,[lge]:e.clientInfo,[Rre]:e.clientCapabilities,...e.logLevel!==void 0&&{[uge]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of i9s)o in e||t.push({key:o,problem:"missing"});let n=Nre().RequestMetaEnvelopeSchema.safeParse(e);if(!n.success)for(let o of n.error.issues){let s=o.path.map(String),a=s.length>0?s.join("."):"_meta";s.length===1&&t.some(l=>l.key===a&&l.problem==="missing")||t.push({key:a,problem:o.message})}return t},projectCallToolResult:r(e=>ZYr(e),"projectCallToolResult"),inputRequestSchema:zpn,decodeResult(e,t){if(!jMe(t))return{kind:"invalid",error:new rl(Pc.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let n=t.resultType;if(n===void 0)return{kind:"invalid",error:new rl(Pc.InvalidResult,`Invalid result for ${e}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:"missing-resultType"})};if(typeof n!="string")return{kind:"invalid",error:new rl(Pc.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:n})};if(n==="input_required"){let l=t.inputRequests,u=jMe(l)?l:{},f=t.requestState;return Object.keys(u).length===0&&typeof f!="string"?{kind:"invalid",error:new rl(Pc.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:u,...typeof f=="string"&&{requestState:f}}}if(n!=="complete")return{kind:"invalid",error:new rl(Pc.UnsupportedResultType,`Unsupported result type '${n}' for ${e}`,{resultType:n,method:e})};let o=a9s(),s=Object.hasOwn(o,e)?o[e]:void 0;if(s!==void 0){let l=s.safeParse(t);if(!l.success)return{kind:"invalid",error:new rl(Pc.InvalidResult,`Invalid result for ${e}: ${l.error}`,{method:e})}}let a={...t};return delete a.resultType,{kind:"complete",result:a}},encodeResult(e,t,n){return J$s(H$s(e,V$s(e,s9s(e,t))),n)},encodeErrorCode:r(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=Nre().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(n=>n.message).join("; ")}`}};r(a9s,"getWireResultSchemas");Iut="2026-07-28";r(i$,"codecForVersion");r(BYr,"classifiedWireEra");r($pn,"isSpecRequestMethod");r(qpn,"isSpecNotificationMethod");hXr=[Qpn,nfn],c9s=SYr({AnnotationsSchema:r(()=>o$,"AnnotationsSchema"),AudioContentSchema:r(()=>_ge,"AudioContentSchema"),BaseMetadataSchema:r(()=>t$,"BaseMetadataSchema"),BaseRequestParamsSchema:r(()=>zk,"BaseRequestParamsSchema"),BlobResourceContentsSchema:r(()=>_Me,"BlobResourceContentsSchema"),BooleanSchemaSchema:r(()=>xMe,"BooleanSchemaSchema"),CallToolRequestParamsSchema:r(()=>Olt,"CallToolRequestParamsSchema"),CallToolRequestSchema:r(()=>Mlt,"CallToolRequestSchema"),CallToolResultSchema:r(()=>SMe,"CallToolResultSchema"),CancelTaskRequestSchema:r(()=>Rpn,"CancelTaskRequestSchema"),CancelTaskResultSchema:r(()=>Dpn,"CancelTaskResultSchema"),CancelledNotificationParamsSchema:r(()=>Bct,"CancelledNotificationParamsSchema"),CancelledNotificationSchema:r(()=>lMe,"CancelledNotificationSchema"),ClientCapabilitiesSchema:r(()=>qct,"ClientCapabilitiesSchema"),ClientNotificationSchema:r(()=>Mpn,"ClientNotificationSchema"),ClientRequestSchema:r(()=>Opn,"ClientRequestSchema"),ClientResultSchema:r(()=>Npn,"ClientResultSchema"),ClientTasksCapabilitySchema:r(()=>zct,"ClientTasksCapabilitySchema"),CompatibilityCallToolResultSchema:r(()=>Spn,"CompatibilityCallToolResultSchema"),CompleteRequestParamsSchema:r(()=>aut,"CompleteRequestParamsSchema"),CompleteRequestSchema:r(()=>cut,"CompleteRequestSchema"),CompleteResultSchema:r(()=>lut,"CompleteResultSchema"),ContentBlockSchema:r(()=>yge,"ContentBlockSchema"),CreateMessageRequestParamsSchema:r(()=>Hlt,"CreateMessageRequestParamsSchema"),CreateMessageRequestSchema:r(()=>Glt,"CreateMessageRequestSchema"),CreateMessageResultSchema:r(()=>Jlt,"CreateMessageResultSchema"),CreateMessageResultWithToolsSchema:r(()=>Klt,"CreateMessageResultWithToolsSchema"),CreateTaskResultSchema:r(()=>kpn,"CreateTaskResultSchema"),CursorSchema:r(()=>rMe,"CursorSchema"),DiscoverRequestSchema:r(()=>Hct,"DiscoverRequestSchema"),DiscoverResultSchema:r(()=>Mre,"DiscoverResultSchema"),ElicitRequestFormParamsSchema:r(()=>Sge,"ElicitRequestFormParamsSchema"),ElicitRequestParamsSchema:r(()=>eut,"ElicitRequestParamsSchema"),ElicitRequestSchema:r(()=>tut,"ElicitRequestSchema"),ElicitRequestURLParamsSchema:r(()=>Qlt,"ElicitRequestURLParamsSchema"),ElicitResultSchema:r(()=>out,"ElicitResultSchema"),ElicitationCompleteNotificationParamsSchema:r(()=>nut,"ElicitationCompleteNotificationParamsSchema"),ElicitationCompleteNotificationSchema:r(()=>rut,"ElicitationCompleteNotificationSchema"),EmbeddedResourceSchema:r(()=>xlt,"EmbeddedResourceSchema"),EmptyResultSchema:r(()=>cMe,"EmptyResultSchema"),EnumSchemaSchema:r(()=>Xlt,"EnumSchemaSchema"),GetPromptRequestParamsSchema:r(()=>Slt,"GetPromptRequestParamsSchema"),GetPromptRequestSchema:r(()=>wlt,"GetPromptRequestSchema"),GetPromptResultSchema:r(()=>Clt,"GetPromptResultSchema"),GetTaskPayloadRequestSchema:r(()=>Cpn,"GetTaskPayloadRequestSchema"),GetTaskPayloadResultSchema:r(()=>Epn,"GetTaskPayloadResultSchema"),GetTaskRequestSchema:r(()=>Tpn,"GetTaskRequestSchema"),GetTaskResultSchema:r(()=>Ipn,"GetTaskResultSchema"),IconSchema:r(()=>Uct,"IconSchema"),IconsSchema:r(()=>xG,"IconsSchema"),ImageContentSchema:r(()=>gge,"ImageContentSchema"),ImplementationSchema:r(()=>fge,"ImplementationSchema"),InitializeRequestParamsSchema:r(()=>Wct,"InitializeRequestParamsSchema"),InitializeRequestSchema:r(()=>uMe,"InitializeRequestSchema"),InitializeResultSchema:r(()=>Vct,"InitializeResultSchema"),InitializedNotificationSchema:r(()=>pMe,"InitializedNotificationSchema"),JSONArraySchema:r(()=>ypn,"JSONArraySchema"),JSONObjectSchema:r(()=>qv,"JSONObjectSchema"),JSONRPCErrorResponseSchema:r(()=>pge,"JSONRPCErrorResponseSchema"),JSONRPCMessageSchema:r(()=>pB,"JSONRPCMessageSchema"),JSONRPCNotificationSchema:r(()=>aMe,"JSONRPCNotificationSchema"),JSONRPCRequestSchema:r(()=>sMe,"JSONRPCRequestSchema"),JSONRPCResponseSchema:r(()=>vpn,"JSONRPCResponseSchema"),JSONRPCResultResponseSchema:r(()=>dge,"JSONRPCResultResponseSchema"),JSONValueSchema:r(()=>wG,"JSONValueSchema"),LegacyTitledEnumSchemaSchema:r(()=>CMe,"LegacyTitledEnumSchemaSchema"),ListChangedOptionsBaseSchema:r(()=>wMe,"ListChangedOptionsBaseSchema"),ListPromptsRequestSchema:r(()=>vlt,"ListPromptsRequestSchema"),ListPromptsResultSchema:r(()=>blt,"ListPromptsResultSchema"),ListResourceTemplatesRequestSchema:r(()=>Qct,"ListResourceTemplatesRequestSchema"),ListResourceTemplatesResultSchema:r(()=>elt,"ListResourceTemplatesResultSchema"),ListResourcesRequestSchema:r(()=>Yct,"ListResourcesRequestSchema"),ListResourcesResultSchema:r(()=>Xct,"ListResourcesResultSchema"),ListRootsRequestSchema:r(()=>dut,"ListRootsRequestSchema"),ListRootsResultSchema:r(()=>put,"ListRootsResultSchema"),ListTasksRequestSchema:r(()=>Apn,"ListTasksRequestSchema"),ListTasksResultSchema:r(()=>Ppn,"ListTasksResultSchema"),ListToolsRequestSchema:r(()=>Rlt,"ListToolsRequestSchema"),ListToolsResultSchema:r(()=>Dlt,"ListToolsResultSchema"),LoggingLevelSchema:r(()=>kMe,"LoggingLevelSchema"),LoggingMessageNotificationParamsSchema:r(()=>jlt,"LoggingMessageNotificationParamsSchema"),LoggingMessageNotificationSchema:r(()=>Blt,"LoggingMessageNotificationSchema"),ModelHintSchema:r(()=>Ult,"ModelHintSchema"),ModelPreferencesSchema:r(()=>zlt,"ModelPreferencesSchema"),MultiSelectEnumSchemaSchema:r(()=>Ylt,"MultiSelectEnumSchemaSchema"),NotificationSchema:r(()=>O1,"NotificationSchema"),NotificationsParamsSchema:r(()=>D1,"NotificationsParamsSchema"),NumberSchemaSchema:r(()=>bge,"NumberSchemaSchema"),PaginatedRequestParamsSchema:r(()=>Kct,"PaginatedRequestParamsSchema"),PaginatedRequestSchema:r(()=>TG,"PaginatedRequestSchema"),PaginatedResultSchema:r(()=>IG,"PaginatedResultSchema"),PingRequestSchema:r(()=>fMe,"PingRequestSchema"),PrimitiveSchemaDefinitionSchema:r(()=>PMe,"PrimitiveSchemaDefinitionSchema"),ProgressNotificationParamsSchema:r(()=>Jct,"ProgressNotificationParamsSchema"),ProgressNotificationSchema:r(()=>mMe,"ProgressNotificationSchema"),ProgressSchema:r(()=>Gct,"ProgressSchema"),ProgressTokenSchema:r(()=>nMe,"ProgressTokenSchema"),PromptArgumentSchema:r(()=>_lt,"PromptArgumentSchema"),PromptListChangedNotificationSchema:r(()=>Elt,"PromptListChangedNotificationSchema"),PromptMessageSchema:r(()=>Ilt,"PromptMessageSchema"),PromptReferenceSchema:r(()=>sut,"PromptReferenceSchema"),PromptSchema:r(()=>ylt,"PromptSchema"),ReadResourceRequestParamsSchema:r(()=>tlt,"ReadResourceRequestParamsSchema"),ReadResourceRequestSchema:r(()=>nlt,"ReadResourceRequestSchema"),ReadResourceResultSchema:r(()=>rlt,"ReadResourceResultSchema"),RelatedTaskMetadataSchema:r(()=>jct,"RelatedTaskMetadataSchema"),RequestIdSchema:r(()=>kG,"RequestIdSchema"),RequestMetaSchema:r(()=>oMe,"RequestMetaSchema"),RequestSchema:r(()=>Wv,"RequestSchema"),ResourceContentsSchema:r(()=>hMe,"ResourceContentsSchema"),ResourceLinkSchema:r(()=>Tlt,"ResourceLinkSchema"),ResourceListChangedNotificationSchema:r(()=>olt,"ResourceListChangedNotificationSchema"),ResourceRequestParamsSchema:r(()=>mge,"ResourceRequestParamsSchema"),ResourceSchema:r(()=>yMe,"ResourceSchema"),ResourceTemplateReferenceSchema:r(()=>iut,"ResourceTemplateReferenceSchema"),ResourceTemplateSchema:r(()=>Zct,"ResourceTemplateSchema"),ResourceUpdatedNotificationParamsSchema:r(()=>hlt,"ResourceUpdatedNotificationParamsSchema"),ResourceUpdatedNotificationSchema:r(()=>glt,"ResourceUpdatedNotificationSchema"),ResultMetaObjectSchema:r(()=>iMe,"ResultMetaObjectSchema"),ResultSchema:r(()=>Vv,"ResultSchema"),RoleSchema:r(()=>CG,"RoleSchema"),RootSchema:r(()=>uut,"RootSchema"),RootsListChangedNotificationSchema:r(()=>fut,"RootsListChangedNotificationSchema"),SamplingContentSchema:r(()=>Wlt,"SamplingContentSchema"),SamplingMessageContentBlockSchema:r(()=>Pre,"SamplingMessageContentBlockSchema"),SamplingMessageSchema:r(()=>Vlt,"SamplingMessageSchema"),ServerCapabilitiesSchema:r(()=>dMe,"ServerCapabilitiesSchema"),ServerNotificationSchema:r(()=>Fpn,"ServerNotificationSchema"),ServerRequestSchema:r(()=>Lpn,"ServerRequestSchema"),ServerResultSchema:r(()=>jpn,"ServerResultSchema"),ServerTasksCapabilitySchema:r(()=>$ct,"ServerTasksCapabilitySchema"),SetLevelRequestParamsSchema:r(()=>Llt,"SetLevelRequestParamsSchema"),SetLevelRequestSchema:r(()=>Flt,"SetLevelRequestSchema"),SingleSelectEnumSchemaSchema:r(()=>Zlt,"SingleSelectEnumSchemaSchema"),StringSchemaSchema:r(()=>vge,"StringSchemaSchema"),SubscribeRequestParamsSchema:r(()=>ilt,"SubscribeRequestParamsSchema"),SubscribeRequestSchema:r(()=>slt,"SubscribeRequestSchema"),SubscriptionFilterSchema:r(()=>vMe,"SubscriptionFilterSchema"),SubscriptionsAcknowledgedNotificationParamsSchema:r(()=>dlt,"SubscriptionsAcknowledgedNotificationParamsSchema"),SubscriptionsAcknowledgedNotificationSchema:r(()=>plt,"SubscriptionsAcknowledgedNotificationSchema"),SubscriptionsListenRequestParamsSchema:r(()=>llt,"SubscriptionsListenRequestParamsSchema"),SubscriptionsListenRequestSchema:r(()=>ult,"SubscriptionsListenRequestSchema"),SubscriptionsListenResultMetaSchema:r(()=>flt,"SubscriptionsListenResultMetaSchema"),SubscriptionsListenResultSchema:r(()=>mlt,"SubscriptionsListenResultSchema"),TaskAugmentedRequestParamsSchema:r(()=>Ore,"TaskAugmentedRequestParamsSchema"),TaskCreationParamsSchema:r(()=>wpn,"TaskCreationParamsSchema"),TaskMetadataSchema:r(()=>Fct,"TaskMetadataSchema"),TaskSchema:r(()=>EG,"TaskSchema"),TaskStatusNotificationParamsSchema:r(()=>hut,"TaskStatusNotificationParamsSchema"),TaskStatusNotificationSchema:r(()=>xpn,"TaskStatusNotificationSchema"),TaskStatusSchema:r(()=>mut,"TaskStatusSchema"),TextContentSchema:r(()=>hge,"TextContentSchema"),TextResourceContentsSchema:r(()=>gMe,"TextResourceContentsSchema"),TitledMultiSelectEnumSchemaSchema:r(()=>AMe,"TitledMultiSelectEnumSchemaSchema"),TitledSingleSelectEnumSchemaSchema:r(()=>IMe,"TitledSingleSelectEnumSchemaSchema"),ToolAnnotationsSchema:r(()=>Alt,"ToolAnnotationsSchema"),ToolChoiceSchema:r(()=>$lt,"ToolChoiceSchema"),ToolExecutionSchema:r(()=>Plt,"ToolExecutionSchema"),ToolListChangedNotificationSchema:r(()=>Nlt,"ToolListChangedNotificationSchema"),ToolResultContentSchema:r(()=>qlt,"ToolResultContentSchema"),ToolSchema:r(()=>bMe,"ToolSchema"),ToolUseContentSchema:r(()=>klt,"ToolUseContentSchema"),UnsubscribeRequestParamsSchema:r(()=>alt,"UnsubscribeRequestParamsSchema"),UnsubscribeRequestSchema:r(()=>clt,"UnsubscribeRequestSchema"),UntitledMultiSelectEnumSchemaSchema:r(()=>EMe,"UntitledMultiSelectEnumSchemaSchema"),UntitledSingleSelectEnumSchemaSchema:r(()=>TMe,"UntitledSingleSelectEnumSchemaSchema")}),Fre=r(e=>sMe.safeParse(e).success,"isJSONRPCRequest"),gXr=r(e=>aMe.safeParse(e).success,"isJSONRPCNotification"),xge=r(e=>dge.safeParse(e).success,"isJSONRPCResultResponse"),Ige=r(e=>pge.safeParse(e).success,"isJSONRPCErrorResponse"),_Xr=r(e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required","isInputRequiredResult"),rfn=r(e=>uMe.safeParse(e).success,"isInitializeRequest"),yXr=r(e=>pMe.safeParse(e).success,"isInitializedNotification"),l9s="Mcp-Param-",UYr="x-mcp-header",u9s=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,d9s=new Set(["string","integer","boolean","number"]);r(ofn,"scanXMcpHeaderDeclarations");p9s=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],f9s=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);r(xut,"pathName");vXr="=?base64?",bXr="?=";r(m9s,"mcpParamPrimitiveToString");r(h9s,"needsBase64");r(g9s,"utf8ToBase64");r(ifn,"encodeMcpParamValue");r(_9s,"valueAtPath");r(SXr,"buildMcpParamHeaders");kge=-32020,ibl=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[Du.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[kge,Du.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[Du.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[Du.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[Du.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[kge],conformance:["http-header-validation"],rationale:"SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[Du.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[kge],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],sbl={[Du.ParseError]:400,[Du.InvalidRequest]:400,[Du.MethodNotFound]:404,[Du.UnsupportedProtocolVersion]:400,[Du.MissingRequiredClientCapability]:400,[kge]:400};r(Cut,"parseSchema");r(FMe,"shapeKeys");r(Gpn,"isStandardSchema");zYr=!1,Jpn="draft-2020-12";r(y9s,"standardSchemaToJsonSchema");r(wXr,"isProvablyObjectShapedRoot");r(v9s,"formatIssue");r(Wpn,"validateStandardSchema");r(b9s,"zodEmittedPattern");S9s=/\\\.\\d\{(\d+)\}/;r(w9s,"datetimeReferenceSchemas");r(k9s,"referencePatternsForFormat");r(x9s,"isLibraryFormatPattern");r(UMe,"isJsonObject");r(T9s,"convertStandardElicitationSchema");I9s=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);r(sfn,"isAnnotationOnlyJsonSchemaKeyword");C9s=new Set(["$schema",...Object.keys(Sge.shape.requestedSchema.shape)]),$Yr={string:FMe([vge,TMe,IMe,CMe]),number:FMe([bge]),integer:FMe([bge]),boolean:FMe([xMe]),array:FMe([EMe,AMe])},E9s=new Set(vge.shape.format.unwrap().options);r(A9s,"walkProperty");r(P9s,"walkRequestedSchema");r(R9s,"describeUnsupportedProperties");r(Kpn,"findDroppedConstraintPaths");r(D9s,"normalizeElicitInputParams");r(O9s,"buildInputRequired");abl=Object.assign(O9s,{elicit(e){try{return{method:"elicitation/create",params:D9s(e)}}catch(t){throw t instanceof oh?new TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}}),M9s=!0,N9s=10,L9s=250;r(kXr,"resolveInputRequiredDriverConfig");r(F9s,"buildInputRequiredRetryParams");r(j9s,"inputRequiredRoundsExceededMessage");r(B9s,"sleep");r(U9s,"linkedRoundAbort");r(z9s,"runInputRequiredDriver");$9s=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],q9s={IdJagTokenExchangeResponseSchema:_ut,OAuthClientInformationFullSchema:NMe,OAuthClientInformationSchema:vut,OAuthClientMetadataSchema:yut,OAuthClientRegistrationErrorSchema:Bpn,OAuthErrorResponseSchema:MMe,OAuthMetadataSchema:wge,OAuthProtectedResourceMetadataSchema:RMe,OAuthTokenRevocationRequestSchema:Upn,OAuthTokensSchema:OMe,OpenIdProviderDiscoveryMetadataSchema:DMe,OpenIdProviderMetadataSchema:gut},xXr={},TXr={};r(IXr,"register");for(let e of $9s)IXr(e,c9s[e]);for(let[e,t]of Object.entries(q9s))IXr(e,t);W9s=Object.freeze(xXr),CXr=Object.freeze(TXr);r(V9s,"bootstrapOutboundCodec");Eut=6e4,H9s=[n$,lge,Rre,uge],G9s=["inputResponses","requestState"];r(qYr,"liftWireOnlyMaterial");r(WYr,"codecResultValidator");r(afn,"requestStateAccessor");J9s=afn(void 0),EXr=class{static{r(this,"Protocol")}_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{K9s=r((e,t)=>{e._negotiatedProtocolVersion=t},"writeNegotiatedProtocolVersion")}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Nct,this.setNotificationHandler("notifications/cancelled",t=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",t=>{this._onprogress(t)}),this.setRequestHandler("ping",t=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let n=e.params??{};return{...e,params:{...n,_meta:{...t,...n._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new rl(Pc.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new rl(Pc.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,a)=>{o?.(s,a),xge(s)||Ige(s)?this._onresponse(s):Fre(s)?this._onrequest(s,a):gXr(s)?this._onnotification(s,a):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let n=new rl(Pc.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let o of e.values())o(n);for(let o of t.values())o.abort(n)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:n}=qYr(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let l=BYr(t.classification);if(l!==o.era){this._onerror(new Error(`Era mismatch on inbound notification '${n.method}': classified as ${l} but this instance serves ${o.era}`));return}}if(qpn(n.method)&&!o.hasNotificationMethod(n.method))return;let s=this._notificationHandlers.get(n.method),a=this.fallbackNotificationHandler;s===void 0&&a===void 0||Promise.resolve().then(()=>s===void 0?a(n):s(n,o)).catch(l=>this._onerror(new Error(`Uncaught error in notification handler: ${l}`)))}_onrequest(e,t){let{message:n,lifted:o}=qYr(e,"request"),s=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(new Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let a=this._transport,l=r((E,R,L)=>{let U={jsonrpc:"2.0",id:n.id,error:{code:E,message:R,...L!==void 0&&{data:L}}};a?.send(U).catch(B=>this._onerror(new Error(`Failed to send an error response: ${B}`)))},"sendErrorResponse");if(t?.classification!==void 0){let E=BYr(t.classification);if(E!==s.era){this._onerror(new Error(`Era mismatch on inbound request '${n.method}': classified as ${E} but this instance serves ${s.era}`));let R=t.classification.revision??E;l(Du.UnsupportedProtocolVersion,`Unsupported protocol version: ${R}`,{supported:this._supportedProtocolVersions,requested:R});return}}if($pn(n.method)&&!s.hasRequestMethod(n.method)){l(Du.MethodNotFound,"Method not found");return}let u=this._requestHandlers.get(n.method)??this.fallbackRequestHandler;if(u===void 0){l(Du.MethodNotFound,"Method not found");return}let f=s.checkInboundEnvelope(o);if(f!==void 0){l(Du.InvalidParams,f);return}let g=r((E,R)=>this._notificationViaCodec(this._resolveOutboundCodec(E.method),E,{...R,relatedRequestId:n.id}),"sendNotification"),_=r((E,R,L)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(E.method),E,R,{...L,relatedRequestId:n.id}),"sendRequest"),b=new AbortController;this._requestHandlerAbortControllers.set(n.id,b);let w=o.inputResponses===void 0?void 0:Z9s(o.inputResponses),T={sessionId:a?.sessionId,mcpReq:{id:n.id,method:n.method,_meta:n.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...w!==void 0&&{inputResponses:w.accepted},...w!==void 0&&w.droppedKeys.length>0&&{droppedInputResponseKeys:w.droppedKeys},requestState:o.requestState===void 0?J9s:afn(o.requestState),signal:b.signal,send:r(((E,R,L)=>{let U=this._resolveOutboundCodec(E.method);if(this._assertOutboundRequestInEra(U,E.method),Gpn(R))return _(E,R,L);let B=WYr(U,E.method);if(B===void 0)throw new TypeError(`'${E.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return _(E,B,R)}),"send"),notify:g},http:t?.authInfo?{authInfo:t.authInfo}:void 0},I=this.buildContext(T,t);Promise.resolve().then(()=>u(n,I)).then(async E=>{if(b.signal.aborted)return;let R;try{R=s.encodeResult(n.method,E,this._outboundServerInfo())}catch(U){this._onerror(new Error(`Failed to encode result for ${n.method}: ${U}`)),l(Du.InternalError,"Internal error");return}let L={result:R,jsonrpc:"2.0",id:n.id};await a?.send(L)},async E=>{if(b.signal.aborted)return;let R=Number.isSafeInteger(E.code)?E.code:Du.InternalError,L={jsonrpc:"2.0",id:n.id,error:{code:s.encodeErrorCode(R),message:E.message??"Internal error",...E.data!==void 0&&{data:E.data}}};await a?.send(L)}).catch(E=>this._onerror(new Error(`Failed to send response: ${E}`))).finally(()=>{this._requestHandlerAbortControllers.get(n.id)===b&&this._requestHandlerAbortControllers.delete(n.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,o=Number(t),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(o),l=this._timeoutInfo.get(o);if(l&&a&&l.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(u){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),a(u);return}s(n)}_onresponse(e){let t=Number(e.id),n=this._responseHandlers.get(t);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),xge(e)?n(e):n(oh.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,n){let o=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(o,e.method),Gpn(t))return this._requestWithSchemaViaCodec(o,e,t,n);let s=WYr(o,e.method);if(s===void 0)throw new TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(o,e,s,t)}_negotiatedWireCodec(){return i$(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=V9s(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if($pn(t)&&!e.hasRequestMethod(t))throw new rl(Pc.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,n){let o=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,n)}_requestWithSchemaViaCodec(e,t,n,o){let{relatedRequestId:s,resumptionToken:a,onresumptiontoken:l,headers:u}=o??{},f=Date.now(),g,_;return new Promise((b,w)=>{let T=r(J=>{w(J)},"earlyReject");if(!this._transport){T(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(J){T(J);return}if(o?.signal?.aborted){let J=o.signal.reason;throw J instanceof rl?J:new rl(Pc.RequestTimeout,String(J))}let I=e.era===Iut&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,E=this._requestMessageId++;_=E;let R={...t,jsonrpc:"2.0",id:E};o?.onprogress&&(this._progressHandlers.set(E,o.onprogress),R.params={...t.params,_meta:{...t.params?._meta,progressToken:E}});let L=this._envelopeOutbound(R),U=!1,B=r(J=>{U||(this._progressHandlers.delete(E),I===void 0?this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:E,reason:String(J)}}),{relatedRequestId:s,resumptionToken:a,onresumptiontoken:l}).catch(q=>this._onerror(new Error(`Failed to send cancellation: ${q}`))):I.abort(),w(J instanceof rl?J:new rl(Pc.RequestTimeout,String(J))))},"cancel");this._responseHandlers.set(E,J=>{if(o?.signal?.aborted)return;if(U=!0,J instanceof Error)return w(J);let q;try{q=e.decodeResult(t.method,J.result)}catch(ae){return w(ae instanceof Error?ae:new Error(String(ae)))}if(q.kind==="invalid")return w(q.error);if(q.kind==="input_required"){if(o?.allowInputRequired===!0)return b(eqs(q));let ae={codec:e,request:t,resultSchema:n,options:o,flowStartedAt:f,retry:r((Ce,pe)=>this._requestWithSchemaViaCodec(e,Ce===void 0?{method:t.method}:{method:t.method,params:Ce},n,pe),"retry")};return b(this._resolveNonCompleteResult(q,ae))}let ie=q.result;Wpn(n,ie).then(ae=>{ae.success?b(ae.data):w(new rl(Pc.InvalidResult,`Invalid result for ${t.method}: ${ae.error}`))},w)}),g=r(()=>B(o?.signal?.reason),"onAbort"),o?.signal?.addEventListener("abort",g,{once:!0});let z=o?.timeout??Eut,$=r(()=>B(new rl(Pc.RequestTimeout,"Request timed out",{timeout:z})),"timeoutHandler");this._setupTimeout(E,z,o?.maxTotalTimeout,$,o?.resetTimeoutOnProgress??!1),this._transport.send(L,{relatedRequestId:s,resumptionToken:a,onresumptiontoken:l,headers:u,requestSignal:I?.signal}).catch(J=>{this._progressHandlers.delete(E),w(J)})}).finally(()=>{g&&o?.signal?.removeEventListener("abort",g),_!==void 0&&(this._responseHandlers.delete(_),this._cleanupTimeout(_))})}async notification(e,t){return this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,n){if(!this._transport)throw new rl(Pc.NotConnected,"Not connected");if(qpn(t.method)&&!e.hasNotificationMethod(t.method))throw new rl(Pc.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let o=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!n?.relatedRequestId){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(o,n).catch(s=>this._onerror(s))});return}await this._transport.send(o,n)}setRequestHandler(e,t,n){this.assertRequestHandlerCapability(e);let o;if(typeof t=="function"){if(!$pn(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=r((s,a)=>{let l=this._negotiatedWireCodec(),u=l.validateRequest(e,s);if(!u.ok&&u.reason==="not-in-era"&&(u=l.validateInputRequest(e,s)),!u.ok)throw u.reason==="not-in-era"?new oh(Du.InternalError,`No wire schema for ${e} in the resolved era`):new Error(u.message);return Promise.resolve(t(u.value,a))},"stored")}else if(n)o=r(async(s,a)=>{let l=await Wpn(t.params,{...s.params});if(!l.success)throw new oh(Du.InvalidParams,`Invalid params for ${e}: ${l.error}`);return n(l.data,a)},"stored");else throw new TypeError("setRequestHandler: handler is required");this._requestHandlers.set(e,this._wrapHandler(e,o))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,n){if(typeof t=="function"){if(!qpn(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(o,s)=>{let a=s.validateNotification(e,o);if(!a.ok)throw a.reason==="not-in-era"?new oh(Du.InternalError,`No wire schema for ${e} in the resolved era`):new Error(a.message);return Promise.resolve(t(a.value))});return}if(!n)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async o=>{let s=await Wpn(t.params,{...o.params});if(!s.success)throw new oh(Du.InvalidParams,`Invalid params for notification ${e}: ${s.error}`);await n(s.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};r(BMe,"isPlainObject$1");r(AXr,"mergeCapabilities");r(Tut,"isPlainObject");r(Z9s,"partitionInputResponses");r(VYr,"relatedMessagingUnavailable");r(Y9s,"synthesizeInputRequestContext");r(X9s,"dispatchInputRequest");r(Q9s,"buildRetryLegRequestOptions");r(PXr,"runInputRequiredFlow");r(eqs,"manualInputRequiredValue");tqs=qs((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,n=/\\([\u000b\u0020-\u00ff])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=s;function s(u){if(!u)throw new TypeError("argument string is required");var f=typeof u=="object"?a(u):u;if(typeof f!="string")throw new TypeError("argument string is required to be a string");var g=f.indexOf(";"),_=g!==-1?f.slice(0,g).trim():f.trim();if(!o.test(_))throw new TypeError("invalid media type");var b=new l(_.toLowerCase());if(g!==-1){var w,T,I;for(t.lastIndex=g;T=t.exec(f);){if(T.index!==g)throw new TypeError("invalid parameter format");g+=T[0].length,w=T[1].toLowerCase(),I=T[2],I.charCodeAt(0)===34&&(I=I.slice(1,-1),I.indexOf("\\")!==-1&&(I=I.replace(n,"$1"))),b.parameters[w]=I}if(g!==f.length)throw new TypeError("invalid parameter format")}return b}r(s,"parse");function a(u){var f;if(typeof u.getHeader=="function"?f=u.getHeader("content-type"):typeof u.headers=="object"&&(f=u.headers&&u.headers["content-type"]),typeof f!="string")throw new TypeError("content-type header is missing from object");return f}r(a,"getcontenttype");function l(u){this.parameters=Object.create(null),this.type=u}r(l,"ContentType")})),nqs=Mct(tqs(),1);r(RXr,"mediaTypeEssence");DXr=10*1024*1024,cfn=class{static{r(this,"ReadBuffer")}_buffer;_maxBufferSize;constructor(e){this._maxBufferSize=e?.maxBufferSize??DXr}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){for(;this._buffer;){let e=this._buffer.indexOf(`
|
|
2139
2139
|
`);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");this._buffer=this._buffer.subarray(e+1);try{return OXr(t)}catch(n){if(n instanceof SyntaxError)continue;throw n}}return null}clear(){this._buffer=void 0}};r(OXr,"deserializeMessage");r(lfn,"serializeMessage");r(zMe,"normalizeHeaders");r(ufn,"createFetchWithInit")});function pfn(e){let t=new e({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return yWs(t),t}var Put,MXr,Ld,Nf,KF,Dut,rqs,NXr,LXr,Rut,oqs,ZF,iqs,sqs,FXr,aqs,Out,Cge,qMe,Ege,Mut,cqs,jXr,lqs,uqs,dqs,ffn,pqs,mfn,BXr,fqs,mqs,hqs,gqs,_qs,yqs,vqs,bqs,hfn,Sqs,wqs,kqs,UXr,zXr,$Xr,xqs,Tqs,Iqs,gfn,Cqs,qXr,Eqs,Aqs,Pqs,Rqs,Dqs,Oqs,Mqs,Nqs,WXr,Lqs,VXr,HXr,GXr,Fqs,_fn,jqs,JXr,KXr,ZXr,Bqs,Uqs,YXr,zqs,$qs,qqs,XXr,Wqs,Vqs,QXr,Hqs,Gqs,Jqs,Kqs,Zqs,Yqs,Xqs,Qqs,eWs,tWs,nWs,rWs,oWs,iWs,sWs,aWs,cWs,lWs,uWs,dWs,pWs,fWs,mWs,eQr,hWs,gWs,_Ws,yWs,yfn,bbl,tQr=Y(()=>{hpn();gpn();Put=qs((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{static{r(this,"_CodeOrName")}};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{static{r(this,"Name")}constructor(L){if(super(),!e.IDENTIFIER.test(L))throw new Error("CodeGen: name must be a valid identifier");this.str=L}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var o=class extends t{static{r(this,"_Code")}constructor(L){super(),this._items=typeof L=="string"?[L]:L}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let L=this._items[0];return L===""||L==='""'}get str(){var L;return(L=this._str)!==null&&L!==void 0?L:this._str=this._items.reduce((U,B)=>`${U}${B}`,"")}get names(){var L;return(L=this._names)!==null&&L!==void 0?L:this._names=this._items.reduce((U,B)=>(B instanceof n&&(U[B.str]=(U[B.str]||0)+1),U),{})}};e._Code=o,e.nil=new o("");function s(L,...U){let B=[L[0]],z=0;for(;z<U.length;)u(B,U[z]),B.push(L[++z]);return new o(B)}r(s,"_"),e._=s;let a=new o("+");function l(L,...U){let B=[T(L[0])],z=0;for(;z<U.length;)B.push(a),u(B,U[z]),B.push(a,T(L[++z]));return f(B),new o(B)}r(l,"str"),e.str=l;function u(L,U){U instanceof o?L.push(...U._items):U instanceof n?L.push(U):L.push(b(U))}r(u,"addCodeArg"),e.addCodeArg=u;function f(L){let U=1;for(;U<L.length-1;){if(L[U]===a){let B=g(L[U-1],L[U+1]);if(B!==void 0){L.splice(U-1,3,B);continue}L[U++]="+"}U++}}r(f,"optimize");function g(L,U){if(U==='""')return L;if(L==='""')return U;if(typeof L=="string")return U instanceof n||L[L.length-1]!=='"'?void 0:typeof U!="string"?`${L.slice(0,-1)}${U}"`:U[0]==='"'?L.slice(0,-1)+U.slice(1):void 0;if(typeof U=="string"&&U[0]==='"'&&!(L instanceof n))return`"${L}${U.slice(1)}`}r(g,"mergeExprItems");function _(L,U){return U.emptyStr()?L:L.emptyStr()?U:l`${L}${U}`}r(_,"strConcat"),e.strConcat=_;function b(L){return typeof L=="number"||typeof L=="boolean"||L===null?L:T(Array.isArray(L)?L.join(","):L)}r(b,"interpolate");function w(L){return new o(T(L))}r(w,"stringify"),e.stringify=w;function T(L){return JSON.stringify(L).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}r(T,"safeStringify"),e.safeStringify=T;function I(L){return typeof L=="string"&&e.IDENTIFIER.test(L)?new o(`.${L}`):s`[${L}]`}r(I,"getProperty"),e.getProperty=I;function E(L){if(typeof L=="string"&&e.IDENTIFIER.test(L))return new o(`${L}`);throw new Error(`CodeGen: invalid export name: ${L}, use explicit $id name mapping`)}r(E,"getEsmExportName"),e.getEsmExportName=E;function R(L){return new o(L.toString())}r(R,"regexpCode"),e.regexpCode=R})),MXr=qs((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Put();var n=class extends Error{static{r(this,"ValueError")}constructor(f){super(`CodeGen: "code" for ${f} not defined`),this.value=f.value}},o;(function(f){f[f.Started=0]="Started",f[f.Completed=1]="Completed"})(o||(e.UsedValueState=o={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};var s=class{static{r(this,"Scope")}constructor({prefixes:f,parent:g}={}){this._names={},this._prefixes=f,this._parent=g}toName(f){return f instanceof t.Name?f:this.name(f)}name(f){return new t.Name(this._newName(f))}_newName(f){let g=this._names[f]||this._nameGroup(f);return`${f}${g.index++}`}_nameGroup(f){var g,_;if(!((_=(g=this._parent)===null||g===void 0?void 0:g._prefixes)===null||_===void 0)&&_.has(f)||this._prefixes&&!this._prefixes.has(f))throw new Error(`CodeGen: prefix "${f}" is not allowed in this scope`);return this._names[f]={prefix:f,index:0}}};e.Scope=s;var a=class extends t.Name{static{r(this,"ValueScopeName")}constructor(f,g){super(g),this.prefix=f}setValue(f,{property:g,itemIndex:_}){this.value=f,this.scopePath=(0,t._)`.${new t.Name(g)}[${_}]`}};e.ValueScopeName=a;let l=(0,t._)`\n`;var u=class extends s{static{r(this,"ValueScope")}constructor(f){super(f),this._values={},this._scope=f.scope,this.opts={...f,_n:f.lines?l:t.nil}}get(){return this._scope}name(f){return new a(f,this._newName(f))}value(f,g){var _;if(g.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let b=this.toName(f),{prefix:w}=b,T=(_=g.key)!==null&&_!==void 0?_:g.ref,I=this._values[w];if(I){let L=I.get(T);if(L)return L}else I=this._values[w]=new Map;I.set(T,b);let E=this._scope[w]||(this._scope[w]=[]),R=E.length;return E[R]=g.ref,b.setValue(g,{property:w,itemIndex:R}),b}getValue(f,g){let _=this._values[f];if(_)return _.get(g)}scopeRefs(f,g=this._values){return this._reduceValues(g,_=>{if(_.scopePath===void 0)throw new Error(`CodeGen: name "${_}" has no value`);return(0,t._)`${f}${_.scopePath}`})}scopeCode(f=this._values,g,_){return this._reduceValues(f,b=>{if(b.value===void 0)throw new Error(`CodeGen: name "${b}" has no value`);return b.value.code},g,_)}_reduceValues(f,g,_={},b){let w=t.nil;for(let T in f){let I=f[T];if(!I)continue;let E=_[T]=_[T]||new Map;I.forEach(R=>{if(E.has(R))return;E.set(R,o.Started);let L=g(R);if(L){let U=this.opts.es5?e.varKinds.var:e.varKinds.const;w=(0,t._)`${w}${U} ${R} = ${L};${this.opts._n}`}else if(L=b?.(R))w=(0,t._)`${w}${L}${this.opts._n}`;else throw new n(R);E.set(R,o.Completed)})}return w}};e.ValueScope=u})),Ld=qs((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=Put(),n=MXr();var o=Put();Object.defineProperty(e,"_",{enumerable:!0,get:r(function(){return o._},"get")}),Object.defineProperty(e,"str",{enumerable:!0,get:r(function(){return o.str},"get")}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:r(function(){return o.strConcat},"get")}),Object.defineProperty(e,"nil",{enumerable:!0,get:r(function(){return o.nil},"get")}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:r(function(){return o.getProperty},"get")}),Object.defineProperty(e,"stringify",{enumerable:!0,get:r(function(){return o.stringify},"get")}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:r(function(){return o.regexpCode},"get")}),Object.defineProperty(e,"Name",{enumerable:!0,get:r(function(){return o.Name},"get")});var s=MXr();Object.defineProperty(e,"Scope",{enumerable:!0,get:r(function(){return s.Scope},"get")}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:r(function(){return s.ValueScope},"get")}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:r(function(){return s.ValueScopeName},"get")}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:r(function(){return s.varKinds},"get")}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};var a=class{static{r(this,"Node")}optimizeNodes(){return this}optimizeNames(Je,Xe){return this}},l=class extends a{static{r(this,"Def")}constructor(Je,Xe,_t){super(),this.varKind=Je,this.name=Xe,this.rhs=_t}render({es5:Je,_n:Xe}){let _t=Je?n.varKinds.var:this.varKind,Dt=this.rhs===void 0?"":` = ${this.rhs}`;return`${_t} ${this.name}${Dt};`+Xe}optimizeNames(Je,Xe){if(Je[this.name.str])return this.rhs&&(this.rhs=Pe(this.rhs,Je,Xe)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},u=class extends a{static{r(this,"Assign")}constructor(Je,Xe,_t){super(),this.lhs=Je,this.rhs=Xe,this.sideEffects=_t}render({_n:Je}){return`${this.lhs} = ${this.rhs};`+Je}optimizeNames(Je,Xe){if(!(this.lhs instanceof t.Name&&!Je[this.lhs.str]&&!this.sideEffects))return this.rhs=Pe(this.rhs,Je,Xe),this}get names(){return rt(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},f=class extends u{static{r(this,"AssignOp")}constructor(Je,Xe,_t,Dt){super(Je,_t,Dt),this.op=Xe}render({_n:Je}){return`${this.lhs} ${this.op}= ${this.rhs};`+Je}},g=class extends a{static{r(this,"Label")}constructor(Je){super(),this.label=Je,this.names={}}render({_n:Je}){return`${this.label}:`+Je}},_=class extends a{static{r(this,"Break")}constructor(Je){super(),this.label=Je,this.names={}}render({_n:Je}){return`break${this.label?` ${this.label}`:""};`+Je}},b=class extends a{static{r(this,"Throw")}constructor(Je){super(),this.error=Je}render({_n:Je}){return`throw ${this.error};`+Je}get names(){return this.error.names}},w=class extends a{static{r(this,"AnyCode")}constructor(Je){super(),this.code=Je}render({_n:Je}){return`${this.code};`+Je}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(Je,Xe){return this.code=Pe(this.code,Je,Xe),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},T=class extends a{static{r(this,"ParentNode")}constructor(Je=[]){super(),this.nodes=Je}render(Je){return this.nodes.reduce((Xe,_t)=>Xe+_t.render(Je),"")}optimizeNodes(){let{nodes:Je}=this,Xe=Je.length;for(;Xe--;){let _t=Je[Xe].optimizeNodes();Array.isArray(_t)?Je.splice(Xe,1,..._t):_t?Je[Xe]=_t:Je.splice(Xe,1)}return Je.length>0?this:void 0}optimizeNames(Je,Xe){let{nodes:_t}=this,Dt=_t.length;for(;Dt--;){let gn=_t[Dt];gn.optimizeNames(Je,Xe)||(Tt(Je,gn.names),_t.splice(Dt,1))}return _t.length>0?this:void 0}get names(){return this.nodes.reduce((Je,Xe)=>ze(Je,Xe.names),{})}},I=class extends T{static{r(this,"BlockNode")}render(Je){return"{"+Je._n+super.render(Je)+"}"+Je._n}},E=class extends T{static{r(this,"Root")}},R=class extends I{static{r(this,"Else")}};R.kind="else";var L=class Aut extends I{static{r(this,"If")}constructor(Xe,_t){super(_t),this.condition=Xe}render(Xe){let _t=`if(${this.condition})`+super.render(Xe);return this.else&&(_t+="else "+this.else.render(Xe)),_t}optimizeNodes(){super.optimizeNodes();let Xe=this.condition;if(Xe===!0)return this.nodes;let _t=this.else;if(_t){let Dt=_t.optimizeNodes();_t=this.else=Array.isArray(Dt)?new R(Dt):Dt}if(_t)return Xe===!1?_t instanceof Aut?_t:_t.nodes:this.nodes.length?this:new Aut(Ye(Xe),_t instanceof Aut?[_t]:_t.nodes);if(!(Xe===!1||!this.nodes.length))return this}optimizeNames(Xe,_t){var Dt;if(this.else=(Dt=this.else)===null||Dt===void 0?void 0:Dt.optimizeNames(Xe,_t),!!(super.optimizeNames(Xe,_t)||this.else))return this.condition=Pe(this.condition,Xe,_t),this}get names(){let Xe=super.names;return rt(Xe,this.condition),this.else&&ze(Xe,this.else.names),Xe}};L.kind="if";var U=class extends I{static{r(this,"For")}};U.kind="for";var B=class extends U{static{r(this,"ForLoop")}constructor(Je){super(),this.iteration=Je}render(Je){return`for(${this.iteration})`+super.render(Je)}optimizeNames(Je,Xe){if(super.optimizeNames(Je,Xe))return this.iteration=Pe(this.iteration,Je,Xe),this}get names(){return ze(super.names,this.iteration.names)}},z=class extends U{static{r(this,"ForRange")}constructor(Je,Xe,_t,Dt){super(),this.varKind=Je,this.name=Xe,this.from=_t,this.to=Dt}render(Je){let Xe=Je.es5?n.varKinds.var:this.varKind,{name:_t,from:Dt,to:gn}=this;return`for(${Xe} ${_t}=${Dt}; ${_t}<${gn}; ${_t}++)`+super.render(Je)}get names(){return rt(rt(super.names,this.from),this.to)}},$=class extends U{static{r(this,"ForIter")}constructor(Je,Xe,_t,Dt){super(),this.loop=Je,this.varKind=Xe,this.name=_t,this.iterable=Dt}render(Je){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(Je)}optimizeNames(Je,Xe){if(super.optimizeNames(Je,Xe))return this.iterable=Pe(this.iterable,Je,Xe),this}get names(){return ze(super.names,this.iterable.names)}},J=class extends I{static{r(this,"Func")}constructor(Je,Xe,_t){super(),this.name=Je,this.args=Xe,this.async=_t}render(Je){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(Je)}};J.kind="func";var q=class extends T{static{r(this,"Return")}render(Je){return"return "+super.render(Je)}};q.kind="return";var ie=class extends I{static{r(this,"Try")}render(Je){let Xe="try"+super.render(Je);return this.catch&&(Xe+=this.catch.render(Je)),this.finally&&(Xe+=this.finally.render(Je)),Xe}optimizeNodes(){var Je,Xe;return super.optimizeNodes(),(Je=this.catch)===null||Je===void 0||Je.optimizeNodes(),(Xe=this.finally)===null||Xe===void 0||Xe.optimizeNodes(),this}optimizeNames(Je,Xe){var _t,Dt;return super.optimizeNames(Je,Xe),(_t=this.catch)===null||_t===void 0||_t.optimizeNames(Je,Xe),(Dt=this.finally)===null||Dt===void 0||Dt.optimizeNames(Je,Xe),this}get names(){let Je=super.names;return this.catch&&ze(Je,this.catch.names),this.finally&&ze(Je,this.finally.names),Je}},ae=class extends I{static{r(this,"Catch")}constructor(Je){super(),this.error=Je}render(Je){return`catch(${this.error})`+super.render(Je)}};ae.kind="catch";var Ce=class extends I{static{r(this,"Finally")}render(Je){return"finally"+super.render(Je)}};Ce.kind="finally";var pe=class{static{r(this,"CodeGen")}constructor(Je,Xe={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...Xe,_n:Xe.lines?`
|
|
@@ -15417,7 +15417,7 @@ Commands:
|
|
|
15417
15417
|
Scopes: user (default), project. \`zcode plugin\` is an alias of \`zcode plugins\`.`;r(Zei,"runPluginsCommand");r(nrc,"runPluginsListCommand");r(rrc,"runPluginsInstallCommand");r(orc,"runPluginsUpdateCommand");r(irc,"reportInstallOutcome");r(Yei,"runPluginsSetCommand");r(src,"runPluginsDisableCommand");r(arc,"runPluginsUninstallCommand");r(crc,"runPluginsValidateCommand")});function urc(e=process.env){let t=e.ZCODE_STORAGE_DIR?.trim()||(0,dse.join)((0,eti.homedir)(),".zcode");return(0,dse.join)(t,"clipboard")}function tti(e={}){let t=e.platform??process.platform,n=e.maxBytes??lrc,o=e.runCommand??mrc,s=e.tempDirectory??urc(e.processEnv);return async(a={})=>t==="darwin"?await drc({maxBytes:n,runCommand:o,signal:a.abortSignal,tempDirectory:s}):t==="linux"?await prc({maxBytes:n,runCommand:o,signal:a.abortSignal}):t==="win32"?await frc({maxBytes:n,runCommand:o,signal:a.abortSignal,tempDirectory:s}):null}async function drc(e){await(0,M4.mkdir)(e.tempDirectory,{recursive:!0});let t=await(0,M4.mkdtemp)((0,dse.join)(e.tempDirectory,"zcode-clipboard-")),n=(0,dse.join)(t,"clipboard.png");try{return(await e.runCommand("osascript",["-e","set png_data to (the clipboard as \xABclass PNGf\xBB)","-e",`set fp to open for access POSIX file ${hrc(n)} with write permission`,"-e","write png_data to fp","-e","close access fp"],{maxBytes:e.maxBytes,signal:e.signal})).exitCode!==0?null:await nti(n,"image/png",e.maxBytes)}finally{await(0,M4.rm)(t,{force:!0,recursive:!0})}}async function prc(e){let t=[{args:["--type","image/png"],file:"wl-paste",mediaType:"image/png"},{args:["--type","image/jpeg"],file:"wl-paste",mediaType:"image/jpeg"},{args:["--type","image/gif"],file:"wl-paste",mediaType:"image/gif"},{args:["--type","image/webp"],file:"wl-paste",mediaType:"image/webp"},{args:["-selection","clipboard","-t","image/png","-o"],file:"xclip",mediaType:"image/png"},{args:["-selection","clipboard","-t","image/jpeg","-o"],file:"xclip",mediaType:"image/jpeg"},{args:["-selection","clipboard","-t","image/gif","-o"],file:"xclip",mediaType:"image/gif"},{args:["-selection","clipboard","-t","image/webp","-o"],file:"xclip",mediaType:"image/webp"}];for(let n of t){let o=await e.runCommand(n.file,n.args,{maxBytes:e.maxBytes,signal:e.signal}),s=rti(o.stdout,n.mediaType,e.maxBytes);if(o.exitCode===0&&s)return s}return null}async function frc(e){await(0,M4.mkdir)(e.tempDirectory,{recursive:!0});let t=await(0,M4.mkdtemp)((0,dse.join)(e.tempDirectory,"zcode-clipboard-")),n=(0,dse.join)(t,"clipboard.png"),o=["Add-Type -AssemblyName System.Windows.Forms;","$img = Get-Clipboard -Format Image;","if ($null -eq $img) { exit 2 }",`$img.Save(${grc(n)}, [System.Drawing.Imaging.ImageFormat]::Png);`].join(" ");try{return(await e.runCommand("powershell.exe",["-NoProfile","-NonInteractive","-Command",o],{maxBytes:e.maxBytes,signal:e.signal})).exitCode!==0?null:await nti(n,"image/png",e.maxBytes)}finally{await(0,M4.rm)(t,{force:!0,recursive:!0})}}async function nti(e,t,n){let o=await(0,M4.readFile)(e);return rti(o,t,n)}function rti(e,t,n){return e.byteLength===0||e.byteLength>n?null:{dataUrl:`data:${t};base64,${e.toString("base64")}`,mediaType:t,sizeBytes:e.byteLength}}async function mrc(e,t,n){return await new Promise(o=>{let s;try{s=(0,Qei.spawn)(e,t,{signal:n.signal,stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{o({exitCode:-1,stdout:Buffer.alloc(0)});return}let a=[],l=0,u=!1,f=r(g=>{u||(u=!0,o(g))},"finish");s.stdout?.on("data",g=>{if(l+=g.byteLength,l>n.maxBytes){s.kill();return}a.push(g)}),s.on("error",()=>f({exitCode:-1,stdout:Buffer.alloc(0)})),s.on("close",(g,_)=>{f({exitCode:g,signal:_,stdout:Buffer.concat(a)})})})}function hrc(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function grc(e){return`'${e.replace(/'/g,"''")}'`}var Qei,M4,eti,dse,lrc,oti=Y(()=>{"use strict";Qei=require("node:child_process"),M4=require("node:fs/promises"),eti=require("node:os"),dse=require("node:path"),lrc=20*1024*1024;r(urc,"resolveDefaultClipboardDirectory");r(tti,"createNodeClipboardImageReader");r(drc,"readMacClipboardImage");r(prc,"readLinuxClipboardImage");r(frc,"readWindowsClipboardImage");r(nti,"readImageFile");r(rti,"bufferToClipboardImage");r(mrc,"runCommandBuffer");r(hrc,"appleScriptString");r(grc,"powershellString")});function sti(e={}){let t=e.maxBytes??_rc,n=e.platform??process.platform,o=e.runCommand??Irc;return async s=>{let a=Trc(s,t);if(a.byteLength===0)return;let l=wrc(e.stdout,a),u=await krc({input:s,platform:n,runCommand:o});if(!l&&!u)throw new Error("No text clipboard target accepted the selected text.")}}function wrc(e,t){if(!e)return!1;try{return e.write(`${vrc}${yrc};${t.toString("base64")}${brc}`),!0}catch{return!1}}async function krc(e){for(let t of xrc(e.platform))if((await e.runCommand(t.file,t.args,{input:e.input})).exitCode===0)return!0;return!1}function xrc(e){return e==="darwin"?[{args:[],file:"pbcopy"}]:e==="linux"?[{args:[],file:"wl-copy"},{args:["-selection","clipboard"],file:"xclip"},{args:["--clipboard","--input"],file:"xsel"}]:e==="win32"?[{args:["-NoProfile","-NonInteractive","-Command",Src],file:"powershell.exe"}]:[]}function Trc(e,t){let n=Buffer.from(e,"utf8");if(n.byteLength>t)throw new Error(`Clipboard text exceeds ${t} bytes.`);return n}async function Irc(e,t,n){return await new Promise(o=>{let s;try{s=(0,iti.spawn)(e,t,{stdio:["pipe","ignore","ignore"],windowsHide:!0})}catch{o({exitCode:-1});return}let a=!1,l=r(u=>{a||(a=!0,o(u))},"finish");s.stdin?.on("error",()=>{}),s.stdin?.end(n.input),s.on("error",()=>l({exitCode:-1})),s.on("close",(u,f)=>l({exitCode:u,signal:f}))})}var iti,_rc,yrc,vrc,brc,Src,ati=Y(()=>{"use strict";iti=require("node:child_process"),_rc=1024*1024,yrc="c",vrc="\x1B]52;",brc="\x07",Src="Set-Clipboard -Value ([Console]::In.ReadToEnd())";r(sti,"createNodeClipboardTextWriter");r(wrc,"writeOsc52");r(krc,"writeNativeClipboardText");r(xrc,"nativeClipboardCommands");r(Trc,"assertClipboardTextSize");r(Irc,"runCommandText")});async function BTt(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return e.listCustomCommands?await e.listCustomCommands({env:t,logger:e.logger,workingDirectory:n}):await(await Qg()).listZCodeCustomCommands({env:t,logger:e.logger,workingDirectory:n})}async function cti(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)();return e.loadCustomCommand?await e.loadCustomCommand({env:n,logger:e.logger,name:t,workingDirectory:o}):await(await Qg()).loadZCodeCustomCommand({env:n,logger:e.logger,name:t,workingDirectory:o})}async function lti(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return await(e.listSkills??(await Qg()).listZCodeSkills)({env:t,logger:e.logger,workingDirectory:n})}async function uti(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return(await(e.listSessions??(await Qg()).listZCodeSessions)({directory:n,env:t,limit:50})).map(a=>({directory:a.directory,id:a.id,parentId:a.parentID,title:a.title,updatedAt:a.time.updated}))}async function dti(e){try{return await e.getSessionMetadata?.()??{}}catch(t){if(Crc(t))throw t;return{}}}function Crc(e){return e instanceof Error?e.name==="SqliteSessionMigrationError":!1}var j2n=Y(()=>{"use strict";b9();r(BTt,"listCustomCommandsForTui");r(cti,"loadCustomCommandForTui");r(lti,"listSkillsForTui");r(uti,"listSessionsForTui");r(dti,"loadInitialTuiSessionMetadata");r(Crc,"isStartupGateError")});function pti(e){let t=new Set,n,o=r(()=>{n?.(),n=void 0},"detach"),s=r(()=>{if(o(),t.size===0)return;n=e.readSubscriber(e.currentRuntime())?.({onSessionEvent:r(l=>{for(let u of t)u(l)},"onSessionEvent")})},"reattach");return{addSink:r(a=>(t.add(a),t.size===1&&s(),()=>{t.delete(a),t.size===0&&o()}),"addSink"),reattach:s,detach:o,isAttached:r(()=>n!==void 0,"isAttached")}}var fti=Y(()=>{"use strict";r(pti,"createTuiSessionEventRelay")});var mti,hti=Y(()=>{"use strict";TTt();mti=r((e,t)=>{const $zTuiBridge=e,$zTuiGetApp=t;$zTuiBridge.loadSessionTranscript=async()=>await(await $zTuiGetApp()).loadSessionTranscript?.()??[],$zTuiBridge.loadSessionContextMessages=async()=>await(await $zTuiGetApp()).loadSessionContextMessages?.()??[],$zTuiBridge.readGoal=async()=>await(await $zTuiGetApp()).readTarget?.()??null,$zTuiBridge.readTodos=async()=>await(await $zTuiGetApp()).readTodos?.()??[],$zTuiBridge.readRuntimeProjection=async()=>{let $zRuntimeProjectionBridge=await $zTuiGetApp();return await require(require("node:path").join(__dirname,"cli-config.cjs")).readTuiRuntimeProjection($zRuntimeProjectionBridge,$zTuiBridge)},$zTuiBridge.$zRestorePersistedBackgroundTasks=async $zApp=>await require(require("node:path").join(__dirname,"cli-config.cjs")).restoreTuiBackgroundTasks($zApp,(kKo(),H_r(),{collectChildSessionIds:bKo,projectSubagents:SKo,projectChildEvents:e=>new Ate().reduce(e)})),$zTuiBridge.readSessionUsage=async()=>await(await $zTuiGetApp()).readSessionUsage?.()??null,$zTuiBridge.cancelBackgroundTask=async e=>await(await $zTuiGetApp()).cancelBackgroundTask?.(e)??null,$zTuiBridge.previewFileRewind=async e=>{let t=await $zTuiGetApp();return await t.runtime?.previewWorkspaceFileRewind?.({targetMessageIds:e})??null},$zTuiBridge.applyFileRewind=async e=>{let t=await $zTuiGetApp();return await t.runtime?.applyWorkspaceFileRewind?.({targetMessageIds:e})??null},$zTuiBridge.setCustomSessionTitle=async e=>{let t=await $zTuiGetApp();let r=t.runtime?.setCustomSessionTitle?.bind(t.runtime)??t.setCustomSessionTitle?.bind(t);if(!r)throw new Error("Session renaming is unavailable in this runtime.");return await r({title:e.title,traceContext:e.traceContext??t.runtime?.rootTraceContext})},$zTuiBridge.readCustomSessionTitle=async()=>{let t=await $zTuiGetApp(),o=t.sessionStore??t.runtime?.sessionStore,r=await o?.getSession?.(t.sessionId);return r?.titleSource==="custom"&&typeof r.title==="string"?r.title:void 0},$zTuiBridge.setMode=async e=>{return await(await $zTuiGetApp()).setMode(e)},$zTuiBridge.readExecutionState=async()=>await(await $zTuiGetApp()).readExecutionState(),$zTuiBridge.setPlanEnabled=async e=>await(await $zTuiGetApp()).setPlanEnabled(e),$zTuiBridge.setTransientModel=async e=>{if(e==="main"){e=await $zTuiBridge.readDefaultModel();if(!e)throw new Error("No default model is configured.")}let t=await $zTuiGetApp(),r=await t.setModel(e);return{...r,thoughtLevel:t.getThoughtLevel(),effortOptions:t.listThoughtLevels()}},$zTuiBridge.readSessionModel=async()=>{let $zSessionModelApp=await $zTuiGetApp(),s=await $zSessionModelApp.readSessionModelState();if(s?.selection&&!s.issue)await $zSessionModelApp.setModel(s.selection,{transient:!0});return s},$zTuiBridge.sendBackgroundTaskMessage=async e=>await require(require("node:path").join(__dirname,"cli-config.cjs")).sendTuiBackgroundTaskMessage(await $zTuiGetApp(),$zTuiBridge,e),$zTuiBridge.interruptTurn=async e=>{let t=await $zTuiGetApp(),r=e?.reservationId??"tui-steer-interrupt",o=(Array.isArray(e?.pendingInputIds)?e.pendingInputIds:[]).filter(Boolean),n=[],i=async()=>{for(let a of n)await t.releaseQueueItemReservation?.(a,r);n=[]};try{if(t.reserveQueueItem&&t.releaseQueueItemReservation)for(let a of o)if(await t.reserveQueueItem(a,r))n.push(a);else{await i();break}let a=t.runtime?.stopActiveForegroundExecution?.({preserveQueueAutoDrainOnCancel:o.length>0&&n.length===o.length,reason:e?.reason??"TUI steer interrupt"})??{kind:"unsupported"};if(a.kind==="stopped"&&e?.waitForIdle===!0&&t.runtime?.getActiveForegroundExecutionId){let u=Date.now()+5e3;for(;t.runtime.getActiveForegroundExecutionId()!==void 0;){if(Date.now()>=u)throw new Error("Timed out waiting for background result processing to stop.");await new Promise(l=>setTimeout(l,25))}}return a.kind!=="stopped"&&await i(),a}catch(a){await i();throw a}},$zTuiBridge.promoteQueuedInput=async(e,t,r)=>{let o=await $zTuiGetApp(),n=r?.pendingInputReservationId??r?.queryId??r?.inputId??"tui-promotion",i=(Array.isArray(t)?t:[t]).filter(Boolean);if(i.length===0||!o.reserveQueueItem||!o.markQueueItemPromoting||!o.releaseQueueItemReservation||!o.removeQueueItem)return $zTuiBridge.sendInput(e,{...r,delivery:"start_turn"});let a=[],u=!1;try{for(let l of i){if(await o.markQueueItemPromoting(l,n)){a.push(l);continue}if(!await o.reserveQueueItem(l,n))throw new Error("TUI queued input is already reserved: "+l);a.push(l);if(!await o.markQueueItemPromoting(l,n))throw new Error("TUI queued input promotion failed: "+l)}let c=await $zTuiBridge.sendInput(e,{...r,delivery:"start_turn"});if(c?.kind==="rejected")return c;u=!0;for(let l of a)if(!await o.removeQueueItem(l,{reason:"promoted",reservationId:n}))throw new Error("TUI queued input promotion commit failed: "+l);return c}finally{if(!u)for(let l of a)await o.releaseQueueItemReservation(l,n)}},$zTuiBridge.$zSendInputWithoutBackgroundRestore=$zTuiBridge.sendInput,$zTuiBridge.sendInput=async(...$zArgs)=>{let $zApp=await $zTuiGetApp();await $zTuiBridge.$zRestorePersistedBackgroundTasks?.($zApp);return await $zTuiBridge.$zSendInputWithoutBackgroundRestore.apply($zTuiBridge,$zArgs)},e.recallPreviousInput=async n=>await(await t()).recallPreviousInputHistory?.(n)??null,e.getSessionMetadata=async()=>{let n=await t();return{locale:n.getLocale?.(),model:n.getModel?.(),theme:n.getTheme?.(),thoughtLevel:n.getThoughtLevel?.()}},e.reloadModelOptions=async()=>await(await t()).reloadModels(),e.readDefaultModel=async()=>{await t();let $zSelection=await(await e.$zReadProviderRegistryRuntime()).modelSelectionConfigRepository.read();return $zSelection?$zSelection.providerId+"/"+$zSelection.modelId:void 0},e.setDefaultModel=async $zModel=>{let $zApp=await t(),$zIndex=$zModel.indexOf("/"),$zSelection={providerId:$zModel.slice(0,$zIndex),modelId:$zModel.slice($zIndex+1)};if($zIndex<=0||!$zApp.getModelOption($zSelection))throw new Error("Unknown default model: "+$zModel);await(await e.$zReadProviderRegistryRuntime()).modelSelectionConfigRepository.saveConfiguredDefault($zSelection);return await e.setTransientModel($zModel)},e.listModelOptions=async()=>(await t()).listModels?.()??[],e.listEffortOptions=async()=>{let n=await t();return await j3e(n)??[]},e.listMcpServers=async()=>(await t()).listMcpServers?.()??{},e.listWorkflowRuns=async()=>await(await t()).listDynamicWorkflowRuns?.({})??[],e.replayWorkflowRuns=async n=>await(await t()).replayDynamicWorkflowRuns?.(n)??[]},"attachTuiAppQueries")});async function _ti(e,t,n,o){let s=e.env??process.env,a=(e.cwd??process.cwd)(),l=(e.loadDotenv??rA)({cwd:a,env:s});if(l.error)throw new Error(`Failed to load environment file: ${l.path}`,{cause:l.error});let u=await OTt(n,a,s,e),f=e.createZCodeApp?void 0:await Qg(),g=e.createZCodeApp??f?.createZCodeApp;if(!g)throw new Error("ZCode app factory is unavailable.");let _=e.prepareZCodeTelemetryEnv??f?.prepareZCodeTelemetryEnv;_&&(o.shutdownTelemetry=e.shutdownZCodeTelemetry??f?.shutdownZCodeTelemetry);let b=_?await _(s,{cliVersion:t,productVersion:s.ZCODE_APP_VERSION}):s,w=e.startProcessProviderRegistryRuntime??f?.startProcessProviderRegistryRuntime;if(!w)throw new Error("Provider Registry runtime is unavailable.");o.providerRegistryRuntimePromise??=w(b,e.skipUserConfig?{}:{standalone:{...gPe(),...e.userConfigPath?{legacyCliUserConfigFilePath:e.userConfigPath}:{}}});let T=await o.providerRegistryRuntimePromise,I=T?.modelSelectionConfigRepository?await T.modelSelectionConfigRepository.read():T?.configuredDefaultModelSelection,E=e.createProviderEndpointRoutingPort??f?.createDefaultProviderEndpointRoutingPort;return o.providerEndpointRoutingPort??=E?.({appVersion:t,env:s,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:a}),{appEnv:b,configuredDefaultModelSelection:I,createAppFactory:g,providerRegistryRuntime:T,sessionId:u,workingDirectory:a}}var gti,yti=Y(()=>{"use strict";b9();jQ();NXe();A2n();gti=r(()=>({providerEndpointRoutingPort:void 0,providerRegistryRuntimePromise:void 0,shutdownTelemetry:void 0}),"createTuiProcessRuntimeState");r(_ti,"prepareTuiAppRuntime")});async function vti(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)(),s=(e.loadDotenv??rA)({cwd:o,env:n});if(s.error)throw new Error(`Failed to load environment file: ${s.path}`,{cause:s.error});return await(e.loginZCodeCli??(await Qg()).loginZCodeCli)({abortSignal:t?.abortSignal,env:n,onAuthorizeUrl:t?.onAuthorizeUrl})}async function bti(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)(),s=(e.loadDotenv??rA)({cwd:o,env:n});if(s.error)throw new Error(`Failed to load environment file: ${s.path}`,{cause:s.error});return await(e.loginBigmodelCodingPlan??(await Qg()).loginBigmodelCodingPlan)({abortSignal:t?.abortSignal,env:n,onAuthorizeUrl:t?.onAuthorizeUrl})}async function Sti(e,t){return await(e.configureCodingPlanApiKey??(await Qg()).configureCodingPlanApiKey)({apiKey:t.apiKey,env:e.env??process.env,providerId:t.providerId})}async function wti(e){let t=e.env??process.env,n=(e.cwd??process.cwd)(),o=(e.loadDotenv??rA)({cwd:n,env:t});if(o.error)throw new Error(`Failed to load environment file: ${o.path}`,{cause:o.error});return await(e.logoutZCodeCli??(await Qg()).logoutZCodeCli)({env:t})}var kti=Y(()=>{"use strict";b9();jQ();r(vti,"loginForTui");r(bti,"loginBigmodelForTui");r(Sti,"configureApiKeyForTui");r(wti,"logoutForTui")});var xti,Tti,XK,B2n=Y(()=>{"use strict";xti={},Tti=r(e=>({current:e,override:e}),"createCliModeState"),XK=r(e=>e.current??e.override??"build","currentCliMode")});function U2n(e,t,n){return{kind:"started_turn",result:{...e,locale:e.locale??t.getLocale?.(),mode:n,model:e.model??t.getModel?.(),theme:e.theme??t.getTheme?.(),thoughtLevel:e.thoughtLevel??t.getThoughtLevel?.()}}}var Iti=Y(()=>{"use strict";r(U2n,"withTuiMetadata")});function Cti(e,t,n,o={continueSession:!1},s,a,l=Myt,u,f=!1,g,_){let b,w=s,T=gti(),I,E=new WeakMap,R=new WeakMap,L,U=Math.max(1,Math.trunc(e.shutdownCleanupTimeoutMs??nGe)),B={requestPermission:r(async(Pe,Tt)=>{let Ye=L;return Ye?await Ye(Pe,Tt):{decision:"deny",reason:`No interactive approval handler configured for ${Pe.toolName}`,resolvedAt:new Date}},"requestPermission")},z=r(async(Pe=b)=>{if(!Pe)return;let Tt=Pe,Ye=E.get(Tt);Ye||(Ye=(async()=>{await FL(async()=>Pe.close?.(),U),await FL(async()=>R.get(Tt)?.close(),U)})(),E.set(Tt,Ye)),await Ye},"closeApp"),$=pti({currentRuntime:r(()=>b?.runtime,"currentRuntime"),readSubscriber:RTt}),J=r(async Pe=>{let Tt=b,Ye=await Pe();return b=Ye,Tt&&Tt!==Ye&&await z(Tt),$.reattach(),t.current=b.getMode?.()??XK(t),b},"replaceApp"),q=r(async Pe=>{if(I)throw new Error("TUI prompt handler is closed");let{appEnv:Tt,configuredDefaultModelSelection:Ye,createAppFactory:Fe,providerRegistryRuntime:St,sessionId:kt,workingDirectory:st}=await _ti(e,n,Pe,T),$e=T.providerEndpointRoutingPort,jt=ATt({browserExecutable:_,browserUse:g},e),Je;try{Je=await Fe({browserControlPort:jt?.browserControlPort,env:Tt,projectConfigPath:e.projectConfigPath,...$e?{providerEndpointRoutingPort:$e}:{},providerRegistry:St.runtime.registryService,configuredDefaultModelSelection:Ye,...St.providerRuntimeHeadersPort?{providerRuntimeHeadersPort:St.providerRuntimeHeadersPort}:{},resume:kt!==void 0,runtimeConfig:{...t.override?{mode:t.override}:{},...u?{toolDisallowlist:u}:{},...f?{midConversationSystem:{mode:"force"}}:{},modelStreaming:"on",titleGeneration:xti,workingDirectory:st},permissionBroker:B,sessionId:kt,skipUserConfig:e.skipUserConfig,uiDetectedLocale:a,uiLocale:w,userConfigPath:e.userConfigPath,version:n})}catch(Xe){throw await FL(async()=>jt?.close(),U),Xe}if(jt&&R.set(Je,jt),I)throw await z(Je),new Error("TUI prompt handler is closed");return t.current=Je.getMode?.()??t.override??t.current??"build",Je},"createApp"),ie=r(async()=>(b??=await q(o),t.current=b.getMode?.()??XK(t),b),"getApp"),ae=r(async Pe=>await J(async()=>await q(Pe?{continueSession:!1,resumeSessionId:Pe}:{continueSession:!0})),"resumeApp"),Ce=r(async()=>await J(async()=>await q({continueSession:!1})),"newApp"),pe=r(async Pe=>{if(t.override=Pe,b){let Tt=b;if(Tt.setMode){let Ye=await Tt.setMode(Pe);return t.current=Ye.mode,Ye.mode}Tt.runtime.updateConfig({mode:Pe})}return t.current=Pe,Pe},"setCliMode"),ze=$3e({forkApp:r(async Pe=>{let Ye=await(await ie()).forkFromCheckpoint?.({targetCheckpointId:Pe});if(!Ye)throw new Error("Forking is not available in this client.");return await J(async()=>await q({continueSession:!1,resumeSessionId:Ye.forkedSessionId})),{copiedMessageCount:Ye.copiedMessageCount,forkedSessionId:Ye.forkedSessionId,response:`${Ye.response}
|
|
15418
15418
|
Switched to forked session ${Ye.forkedSessionId}.`,restoredFileCount:Ye.restoredFileCount??Ye.restoredFiles?.length??0}},"forkApp"),getApp:ie,getMode:r(()=>XK(t),"getMode"),getLocale:r(()=>b?.getLocale?.()??YRn(w,a)??l,"getLocale"),hasConfiguredCodingPlanAccess:k2n(e),listCustomCommands:r(()=>BTt(e),"listCustomCommands"),listSessions:r(()=>uti(e),"listSessions"),listSkills:r(()=>lti(e),"listSkills"),configureApiKey:r(Pe=>Sti(e,Pe),"configureApiKey"),login:r(Pe=>vti(e,Pe),"login"),loginBigmodel:r(Pe=>bti(e,Pe),"loginBigmodel"),loadCustomCommand:r(Pe=>cti(e,Pe),"loadCustomCommand"),newApp:Ce,recordInputHistory:r(async(Pe,Tt)=>{await b?.recordInputHistory?.(Pe,Tt)},"recordInputHistory"),resumeApp:ae,logout:r(()=>wti(e),"logout"),setLocale:r(async Pe=>{if(b?.setLocale){let Ye=await b.setLocale(Pe);return w=Pe,Ye}return w=Pe,{configPath:(await yOe(e.userConfigPath??U7(),Pe)).path,locale:YRn(Pe,a)??"en-US",requestedLocale:Pe}},"setLocale"),setMode:pe}),rt=r(async(Pe,Tt)=>{let Ye=L;L=Tt.requestPermission;try{return await ze(Pe,Tt)}finally{L=Ye}},"submitPrompt");return rt.setMode=async Pe=>({mode:await pe(Pe)}),rt.sendInput=async(Pe,Tt)=>{let Ye=L;L=Tt?.requestPermission;try{let Fe=await ie();if(Fe.sendInput){let St=await Fe.sendInput(Pe,Tt);return St.kind!=="started_turn"?St:U2n(await(St.result??St.completion),Fe,XK(t))}return U2n(await Fe.submitPrompt(Pe,Tt),Fe,XK(t))}finally{L=Ye}},rt.listSkills=async()=>await lti(e),rt.$zReadProviderRegistryRuntime=()=>T.providerRegistryRuntimePromise,mti(rt,ie),rt.subscribeSessionEvents=Pe=>{let Tt=$.addSink(Pe);return ie().then(()=>$.reattach(),()=>{}),Tt},rt.getMainSessionId=()=>{let Tt=b?.runtime?.getSessionId?.();return typeof Tt=="string"&&Tt.length>0?Tt:void 0},rt.close=async()=>{I??=(async()=>{await z(),await FL(async()=>T.shutdownTelemetry?.(),U),(await T.providerRegistryRuntimePromise)?.dispose()})(),await I},rt}var Eti=Y(()=>{"use strict";vw();eN();ETt();XRn();I2n();DTt();fti();hti();yti();Tde();kti();j2n();B2n();CTt();Iti();r(Cti,"createTuiSubmitPrompt")});var Ati,Pti,Y1,QK,cP,Rti,Dti,Erc,Arc,Oti,Mti,Prc,Rrc,Drc,Orc,Mrc,Nrc,Nti=Y(()=>{"use strict";Ati=require("node:crypto"),Pti=require("node:fs"),Y1=require("node:fs/promises"),QK=require("node:os"),cP=require("node:path"),Rti=require("node:url"),Dti="zcode-tui-runtime/",Erc=`${Dti}manifest.json`,Arc="node_modules/@zcode/tui/dist/index.js",Oti="manifest.json",Mti=r(async()=>{let e=await import("node:sea");if(!e.isSea())return await import("@zcode/tui");let t=await Prc(e);return await import((0,Rti.pathToFileURL)((0,cP.join)(t,Arc)).href)},"loadTuiRuntime"),Prc=r(async e=>{let t=Rrc(e),n=(0,cP.join)(Orc(),"0.16.9",t.target,t.hash),o=(0,cP.join)(n,Oti);if(await Drc(o,t))return n;let s=`${n}.tmp-${process.pid}-${Date.now()}`;await(0,Y1.rm)(s,{force:!0,recursive:!0}),await(0,Y1.mkdir)(s,{recursive:!0});for(let a of t.files){let l=e.getRawAsset(`${Dti}${a.path}`),u=Buffer.from(l);if((0,Ati.createHash)("sha256").update(u).digest("hex")!==a.sha256)throw new Error(`SEA TUI asset hash mismatch for ${a.path}`);let g=(0,cP.join)(s,a.path);await(0,Y1.mkdir)((0,cP.dirname)(g),{recursive:!0}),await(0,Y1.writeFile)(g,u),await(0,Y1.chmod)(g,a.mode??Nrc(a.path))}return await(0,Y1.writeFile)(Mrc(s),JSON.stringify(t,null,2)),await(0,Y1.rm)(n,{force:!0,recursive:!0}),await(0,Y1.mkdir)((0,cP.dirname)(n),{recursive:!0}),await(0,Y1.rename)(s,n),n},"ensureSeaTuiRuntime"),Rrc=r(e=>{let t=e.getAsset(Erc,"utf8"),n=JSON.parse(t);if(n.version!==1||!n.hash||!Array.isArray(n.files))throw new Error("Invalid SEA TUI runtime manifest.");return n},"readManifest"),Drc=r(async(e,t)=>{if(!(0,Pti.existsSync)(e))return!1;try{let n=JSON.parse(await(0,Y1.readFile)(e,"utf8"));return n.hash===t.hash&&n.target===t.target}catch{return!1}},"isCacheCurrent"),Orc=r(()=>{let e=(0,QK.homedir)();return(0,QK.platform)()==="darwin"&&e?(0,cP.join)(e,"Library","Caches","zcode","sea-assets"):(0,QK.platform)()==="win32"?(0,cP.join)(process.env.LOCALAPPDATA??(0,cP.join)(e||(0,QK.tmpdir)(),"AppData","Local"),"zcode","Cache","sea-assets"):(0,cP.join)(process.env.XDG_CACHE_HOME??(0,cP.join)(e||(0,QK.tmpdir)(),".cache"),"zcode","sea-assets")},"cacheBaseDirectory"),Mrc=r(e=>(0,cP.join)(e,Oti),"markerPathForDirectory"),Nrc=r(e=>/\.(?:dll|dylib|node|so)$/i.test(e)?493:420,"modeForPath")});function Lti({deps:e,options:t,workingDirectory:n}){let o=K0({cliOverrides:Lrc(t.locale),env:e.env??process.env,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:n});return e8(o.config.ui.locale,t.detectedLocale)}var Lrc,Fti=Y(()=>{"use strict";vw();eN();Lrc=r(e=>e?{ui:{locale:e}}:void 0,"localeCliOverrides");r(Lti,"resolveTuiStartupLocale")});function Bti(e){let t=e.fileSystemPort??hH(),n=(0,pN.resolve)(e.workspaceDirectory);return async o=>{let s=zrc(o.token);if(!s)return{items:[],truncated:!1};let a=(0,pN.resolve)(n,s.directoryToken);if(!Vrc(n,a))return{items:[],truncated:!1};try{let u=(await t.listDirectory({path:a},{signal:o.abortSignal})).entries.flatMap(g=>{if(g.kind!=="directory"&&g.kind!=="file")return[];if(g.kind==="directory"&&Urc.has(g.name))return[];if(!s.query.startsWith(".")&&g.name.startsWith("."))return[];if(!$rc(g.name,s.query))return[];let _=Wrc(n,g.path);return _?[{kind:g.kind,path:g.kind==="directory"?`${_}/`:_}]:[]}).sort((g,_)=>qrc(g,_,s.query)),f=Math.max(1,Math.floor(o.limit??Frc));return{items:u.slice(0,f),truncated:u.length>f}}catch{return{items:[],truncated:!1}}}}function zrc(e){let t=e.replace(/^@/u,"");if(t.startsWith("/")||t.startsWith("\\")||(0,pN.isAbsolute)(t)||Brc.test(t))return;let n=t.replace(jrc,"/");if(n.split("/").some(s=>s===".."))return;let o=n.lastIndexOf("/");return o<0?{directoryToken:"",query:n}:{directoryToken:n.slice(0,o+1),query:n.slice(o+1)}}function $rc(e,t){return t.length===0?!0:e.toLowerCase().includes(t.toLowerCase())}function qrc(e,t,n){if(e.kind!==t.kind)return e.kind==="directory"?-1:1;let o=jti(e.path),s=jti(t.path),a=n.toLowerCase(),l=o.toLowerCase().startsWith(a),u=s.toLowerCase().startsWith(a);return l!==u?l?-1:1:e.path.localeCompare(t.path)}function jti(e){let t=e.endsWith("/")?e.slice(0,-1):e,n=t.lastIndexOf("/");return n<0?t:t.slice(n+1)}function Wrc(e,t){let n=(0,pN.relative)(e,t);if(!(!n||n.startsWith("..")||(0,pN.isAbsolute)(n)))return n.split(pN.sep).join("/")}function Vrc(e,t){let n=(0,pN.relative)(e,t);return n===""||!n.startsWith("..")&&!(0,pN.isAbsolute)(n)}var pN,Frc,jrc,Brc,Urc,Uti=Y(()=>{"use strict";yme();pN=require("node:path"),Frc=50,jrc=/[\\/]+/gu,Brc=/^[a-zA-Z]:[\\/]/u,Urc=new Set([".bzr",".git",".hg",".jj",".sl",".svn","node_modules"]);r(Bti,"createWorkspacePathSuggestionProvider");r(zrc,"parseWorkspacePathToken");r($rc,"matchesPathQuery");r(qrc,"compareWorkspacePathSuggestion");r(jti,"basenameFromSuggestion");r(Wrc,"toWorkspaceRelativePath");r(Vrc,"isPathInside")});async function $ti(e){let t=e.maxOutputBytes??Krc,n=e.timeoutMs??Jrc,s=await(e.runCommand??Yrc)(Hrc,["-C",e.workspaceDirectory,...Grc],{maxOutputBytes:t,timeoutMs:n}).catch(()=>({exitCode:-1,stdout:""}));if(s.exitCode!==0)return;let a=s.stdout.trim().split(/\r?\n/,1)[0]?.trim();if(!(!a||a===Zrc))return a}async function Yrc(e,t,n){return await new Promise(o=>{let s;try{s=(0,zti.spawn)(e,t,{stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{o({exitCode:-1,stdout:""});return}let a="",l=!1,u=setTimeout(()=>{s.kill(),f({exitCode:-1,stdout:a})},n.timeoutMs),f=r(g=>{l||(l=!0,clearTimeout(u),o(g))},"finish");s.stdout?.on("data",g=>{a+=g.toString("utf8"),Buffer.byteLength(a,"utf8")>n.maxOutputBytes&&(s.kill(),f({exitCode:-1,stdout:a}))}),s.on("error",()=>f({exitCode:-1,stdout:a})),s.on("close",g=>f({exitCode:g,stdout:a}))})}var zti,Hrc,Grc,Jrc,Krc,Zrc,qti=Y(()=>{"use strict";zti=require("node:child_process"),Hrc="git",Grc=["symbolic-ref","--quiet","--short","HEAD"],Jrc=750,Krc=512,Zrc="HEAD";r($ti,"resolveWorkspaceGitBranch");r(Yrc,"runGitCommand")});var Wti,Vti=Y(()=>{"use strict";ms();oti();ati();ETt();Tde();j2n();CTt();Eti();Nti();Fti();Uti();qti();B2n();Wti=r(async(e,t,n,o,s,a,l,u=!1)=>{try{let f=Tti(s),g=n.runTui??(await Mti()).runTui,_=(n.cwd??process.cwd)(),b=n.env??process.env,w=OCe(b)==="development",T=await(n.resolveWorkspaceGitBranch??$ti)({workspaceDirectory:_}).catch(()=>{}),I=Lti({deps:n,options:t,workingDirectory:_}),E=Cti(n,f,o,a,t.locale,t.detectedLocale,I,l,u,t.browserUse,t.browserExecutable),R=rGe({cleanup:r(async()=>{await E.close?.()},"cleanup"),cleanupTimeoutMs:n.shutdownCleanupTimeoutMs,exitProcess:n.exitProcess,process:n.shutdownProcess});try{let L=await fei(n),U=L?{locale:I}:await dti(E),B=L||!U.model?[]:await E.listModelOptions?.().catch(()=>[]),z=L||!U.model?[]:await E.listEffortOptions?.().catch(()=>[]),$=await BTt(n).catch(()=>{});return await g({initialMode:XK(f),initialModel:U.model,initialThoughtLevel:U.thoughtLevel,loginRequired:L,locale:U.locale??I,theme:U.theme??"auto",developerMode:w,version:o,workspaceDirectory:_,workspaceGitBranch:T,noColor:t.noColor,readClipboardImage:n.readClipboardImage??tti(),effortOptions:z,modelOptions:B,listWorkspacePathSuggestions:Bti({workspaceDirectory:_}),listMcpServers:E.listMcpServers,listWorkflowRuns:E.listWorkflowRuns,replayWorkflowRuns:E.replayWorkflowRuns,reduceWorkflowRuns:($zState,$zEvent)=>{zhr();return oQe($zState,$zEvent)},getMainSessionId:E.getMainSessionId,writeClipboardText:n.writeClipboardText??sti({stdout:e.stdout}),stderr:e.stderr,stdin:e.stdin,stdout:e.stdout,loadSessionTranscript:E.loadSessionTranscript,loadSessionContextMessages:E.loadSessionContextMessages,readGoal:E.readGoal,readTodos:E.readTodos,readRuntimeProjection:E.readRuntimeProjection,readSessionUsage:E.readSessionUsage,cancelBackgroundTask:E.cancelBackgroundTask,previewFileRewind:E.previewFileRewind,applyFileRewind:E.applyFileRewind,setCustomSessionTitle:E.setCustomSessionTitle,readCustomSessionTitle:E.readCustomSessionTitle,interruptTurn:E.interruptTurn,promoteQueuedInput:E.promoteQueuedInput,listSkills:E.listSkills,readDefaultModel:E.readDefaultModel,setDefaultModel:E.setDefaultModel,reloadModelOptions:E.reloadModelOptions,listModelOptions:E.listModelOptions,readExecutionState:E.readExecutionState,setPlanEnabled:E.setPlanEnabled,setTransientModel:E.setTransientModel,readSessionModel:E.readSessionModel,sendBackgroundTaskMessage:E.sendBackgroundTaskMessage,recallPreviousInput:E.recallPreviousInput,sendInput:E.sendInput,setMode:E.setMode,slashCommands:v2n($),submitPrompt:E,subscribeSessionEvents:E.subscribeSessionEvents})}finally{R(),await E.close?.()}}catch(f){let g=f instanceof Error?f.message:String(f);return e.stderr.write(`Error: ${g}
|
|
15419
15419
|
`),t.verbose&&f instanceof Error&&f.stack&&e.stderr.write(`${f.stack}
|
|
15420
|
-
`),1}},"runTuiCommand")});var Jti={};Ng(Jti,{run:()=>Toc});var S9,Xrc,Qrc,eoc,toc,noc,roc,ooc,ioc,soc,aoc,coc,zTt,Hti,loc,uoc,Gti,doc,poc,foc,moc,hoc,goc,_oc,yoc,voc,boc,Soc,woc,UTt,koc,xoc,Toc,Kti=Y(()=>{"use strict";Dqt();adt();Y0();Y0();eN();jQ();L2o();WXo();XRn();b9();ZXo();oQo();cQo();n2n();F8t();X8t();mQo();jei();Xei();P2n();Vti();S9="0.16.9",Xrc="--target requires non-empty text.",Qrc="yolo",eoc="--force-mcs can only be used with --prompt, --target, or tui.",toc="--target-replace requires --target.",noc='--target cannot be used with --prompt. Use either --target <objective> or --prompt "/goal <objective>".',roc=new Set(["--disallowedTools","--disallowed-tools"]),ooc="--browser-executable requires --browser-use=headless.",ioc="--browser-use=headless can only be used with --prompt, --target, or tui.",soc="--surface can only be used with --prompt, --target, app-server, or agent-server.",aoc="--memory-bench can only be used with -p/--prompt.",coc=r(e=>({...e.all===!0?{all:!0}:{},...e.available===!0?{available:!0}:{},...e["keep-data"]===!0?{keepData:!0}:{},...typeof e.scope=="string"?{scope:e.scope}:{},...Array.isArray(e.sparse)?{sparse:e.sparse}:{}}),"pluginsCommandFlags"),zTt=r(e=>e[0]??"tui","commandName"),Hti=r(e=>typeof e.prompt=="string"||e.targetRequest!==void 0||zTt(e.positionals)==="tui","isForceMcsSupportedInvocation"),loc=r(e=>{let t=zTt(e.positionals);return typeof e.prompt=="string"||e.targetRequest!==void 0||t==="app-server"||t==="agent-server"},"isPresentationSurfaceSupportedInvocation"),uoc=r((e,t,n,o,s,a)=>({browserExecutable:s,browserUse:o,detectedLocale:n,force:e.force===!0,json:e.json===!0,locale:t,...e["memory-bench"]===!0?{memoryBench:!0}:{},noColor:e["no-color"]===!0,...a?{outputFormat:a}:{},verbose:e.verbose===!0}),"globalOptions"),Gti=["text","json","stream-json"],doc=r(e=>{if(e!==void 0){if(Gti.includes(e))return e;throw new Error(`--output-format must be one of ${Gti.join(", ")} (received: ${e}).`)}},"normalizeOutputFormat"),poc=r(e=>{if(e!==void 0){if(L6e(e))return e;throw new Error(S4().cli.errors.localeUnsupported(e))}},"normalizeLocaleOption"),foc=r(e=>{if(e===void 0)return;let t=e.toLowerCase();if(t==="build"||t==="edit"||t==="yolo")return t;throw new Error(`Unsupported --mode value: ${e}. Supported modes: build, edit, yolo. Use /plan in the TUI to toggle planning.`)},"normalizePromptMode"),moc=r(e=>{if(e!==void 0){if(e.toLowerCase()==="headless")return"headless";throw new Error(`Unsupported --browser-use value: ${e}. Supported value: headless.`)}},"normalizeBrowserUse"),hoc=r(e=>{if(e===void 0||e.toLowerCase()==="terminal")return"terminal";if(e.toLowerCase()==="desktop")return"zcode_desktop";throw new Error(`Unsupported --surface value: ${e}. Supported surfaces: terminal, desktop.`)},"normalizePresentationSurface"),goc=r(e=>{let t=[],n=[];for(let o=0;o<e.length;o+=1){let s=e[o],a=s.match(/^(--disallowedTools|--disallowed-tools)=(.*)$/);if(a){n.push(a[2]??"");continue}if(!roc.has(s)){t.push(s);continue}let l=!1;for(;o+1<e.length&&!_oc(e[o+1]);)n.push(e[o+1]),o+=1,l=!0;if(!l)throw new Error(`${s} requires at least one tool.`)}return{args:t,toolDisallowlist:yoc(n)}},"extractDisallowedToolsArgs"),_oc=r(e=>e==="--"||/^-[^-]?|^--/.test(e),"isCliOptionToken"),yoc=r(e=>{let t=[],n=new Set;for(let o of e)for(let s of voc(o)){let a=boc(s);!a||n.has(a)||(n.add(a),t.push(a))}return t.length>0?t:void 0},"normalizeCliToolRuleList"),voc=r(e=>{let t=[],n="",o=!1,s=r(()=>{let a=n.trim();a&&t.push(a),n=""},"flush");for(let a of e)switch(a){case"(":o=!0,n+=a;break;case")":o=!1,n+=a;break;case",":o?n+=a:s();break;case" ":o?n+=a:s();break;default:n+=a;break}return s(),t},"splitCliToolRules"),boc=r(e=>e?e==="web_search"?"WebSearch":e.startsWith("web_search(")?`WebSearch${e.slice(10)}`:e:"","normalizeCliToolRule"),Soc=r(e=>{let t=e.target,n=e["target-replace"]===!0;if(t===void 0){if(n)throw new Error(toc);return}let o=t.trim();if(o.length===0)throw new Error(Xrc);return{objective:o,replaceExisting:n}},"normalizeTargetRequest"),woc=r(e=>e.replaceExisting?`/goal replace ${e.objective}`:`/goal ${e.objective}`,"buildHeadlessTargetCommand"),UTt=r((e,t,n)=>{e.write(N2o(S9,t,n))},"writeHelp"),koc=r((e,t,n)=>{let o=wTn(),s={cli:{name:aZn,processName:L8t,version:S9},runtime:{arch:o.arch,cwd:n,execPath:o.execPath,node:o.node,platform:o.platform,processTitle:process.title,sea:o.sea},packaging:{default:"node-bundle",sea:"optional"}};if(t.json)return e.stdout.write(e0(s)),0;let a=bTn(e.stdout,t.noColor);return e.stdout.write(`${STn.bold("zcode doctor",a)}
|
|
15420
|
+
`),1}},"runTuiCommand")});var Jti={};Ng(Jti,{run:()=>Toc});var S9,Xrc,Qrc,eoc,toc,noc,roc,ooc,ioc,soc,aoc,coc,zTt,Hti,loc,uoc,Gti,doc,poc,foc,moc,hoc,goc,_oc,yoc,voc,boc,Soc,woc,UTt,koc,xoc,Toc,Kti=Y(()=>{"use strict";Dqt();adt();Y0();Y0();eN();jQ();L2o();WXo();XRn();b9();ZXo();oQo();cQo();n2n();F8t();X8t();mQo();jei();Xei();P2n();Vti();S9="0.16.9",Xrc="--target requires non-empty text.",Qrc="yolo",eoc="--force-mcs can only be used with --prompt, --target, or tui.",toc="--target-replace requires --target.",noc='--target cannot be used with --prompt. Use either --target <objective> or --prompt "/goal <objective>".',roc=new Set(["--disallowedTools","--disallowed-tools"]),ooc="--browser-executable requires --browser-use=headless.",ioc="--browser-use=headless can only be used with --prompt, --target, or tui.",soc="--surface can only be used with --prompt, --target, app-server, or agent-server.",aoc="--memory-bench can only be used with -p/--prompt.",coc=r(e=>({...e.all===!0?{all:!0}:{},...e.available===!0?{available:!0}:{},...e["keep-data"]===!0?{keepData:!0}:{},...typeof e.scope=="string"?{scope:e.scope}:{},...Array.isArray(e.sparse)?{sparse:e.sparse}:{}}),"pluginsCommandFlags"),zTt=r(e=>e[0]??"tui","commandName"),Hti=r(e=>typeof e.prompt=="string"||e.targetRequest!==void 0||zTt(e.positionals)==="tui","isForceMcsSupportedInvocation"),loc=r(e=>{let t=zTt(e.positionals);return typeof e.prompt=="string"||e.targetRequest!==void 0||t==="app-server"||t==="agent-server"},"isPresentationSurfaceSupportedInvocation"),uoc=r((e,t,n,o,s,a)=>({browserExecutable:s,browserUse:o,detectedLocale:n,force:e.force===!0,json:e.json===!0,locale:t,...e["memory-bench"]===!0?{memoryBench:!0}:{},noColor:e["no-color"]===!0,...a?{outputFormat:a}:{},verbose:e.verbose===!0}),"globalOptions"),Gti=["text","json","stream-json"],doc=r(e=>{if(e!==void 0){if(Gti.includes(e))return e;throw new Error(`--output-format must be one of ${Gti.join(", ")} (received: ${e}).`)}},"normalizeOutputFormat"),poc=r(e=>{if(e!==void 0){if(L6e(e))return e;throw new Error(S4().cli.errors.localeUnsupported(e))}},"normalizeLocaleOption"),foc=r(e=>{if(e===void 0)return;let t=e.toLowerCase();if(t==="build"||t==="edit"||t==="yolo")return t;throw new Error(`Unsupported --mode value: ${e}. Supported modes: build, edit, yolo. Use /plan in the TUI to toggle planning.`)},"normalizePromptMode"),moc=r(e=>{if(e!==void 0){if(e.toLowerCase()==="headless")return"headless";throw new Error(`Unsupported --browser-use value: ${e}. Supported value: headless.`)}},"normalizeBrowserUse"),hoc=r(e=>{if(e===void 0||e.toLowerCase()==="terminal")return"terminal";if(e.toLowerCase()==="desktop")return"zcode_desktop";throw new Error(`Unsupported --surface value: ${e}. Supported surfaces: terminal, desktop.`)},"normalizePresentationSurface"),goc=r(e=>{let t=[],n=[];for(let o=0;o<e.length;o+=1){let s=e[o],a=s.match(/^(--disallowedTools|--disallowed-tools)=(.*)$/);if(a){n.push(a[2]??"");continue}if(!roc.has(s)){t.push(s);continue}let l=!1;for(;o+1<e.length&&!_oc(e[o+1]);)n.push(e[o+1]),o+=1,l=!0;if(!l)throw new Error(`${s} requires at least one tool.`)}return{args:t,toolDisallowlist:yoc(n)}},"extractDisallowedToolsArgs"),_oc=r(e=>e==="--"||/^-[^-]?|^--/.test(e),"isCliOptionToken"),yoc=r(e=>{let t=[],n=new Set;for(let o of e)for(let s of voc(o)){let a=boc(s);!a||n.has(a)||(n.add(a),t.push(a))}return t.length>0?t:void 0},"normalizeCliToolRuleList"),voc=r(e=>{let t=[],n="",o=!1,s=r(()=>{let a=n.trim();a&&t.push(a),n=""},"flush");for(let a of e)switch(a){case"(":o=!0,n+=a;break;case")":o=!1,n+=a;break;case",":o?n+=a:s();break;case" ":o?n+=a:s();break;default:n+=a;break}return s(),t},"splitCliToolRules"),boc=r(e=>e?e==="web_search"?"WebSearch":e.startsWith("web_search(")?`WebSearch${e.slice(10)}`:e:"","normalizeCliToolRule"),Soc=r(e=>{let t=e.target,n=e["target-replace"]===!0;if(t===void 0){if(n)throw new Error(toc);return}let o=t.trim();if(o.length===0)throw new Error(Xrc);return{objective:o,replaceExisting:n}},"normalizeTargetRequest"),woc=r(e=>e.replaceExisting?`/goal replace ${e.objective}`:`/goal ${e.objective}`,"buildHeadlessTargetCommand"),UTt=r((e,t,n)=>{e.write(N2o(S9,t,n))},"writeHelp"),koc=r((e,t,n)=>{let o=wTn(),s={cli:{name:aZn,processName:L8t,version:S9},runtime:{arch:o.arch,cwd:n,execPath:o.execPath,node:o.node,platform:o.platform,processTitle:process.title,sea:o.sea},packaging:{default:"node-bundle",sea:"optional"},configuration:require(require("node:path").join(__dirname,"cli-config.cjs")).inspectRuntimeConfiguration(n,$zOptions=>{_Hr();return K0($zOptions)})};if(t.json)return e.stdout.write(e0(s)),s.configuration.ok?0:1;let a=bTn(e.stdout,t.noColor);return e.stdout.write(`${STn.bold("zcode doctor",a)}
|
|
15421
15421
|
`),e.stdout.write(`version: ${s.cli.version}
|
|
15422
15422
|
`),e.stdout.write(`process: ${s.runtime.processTitle}
|
|
15423
15423
|
`),e.stdout.write(`node: ${s.runtime.node}
|
|
@@ -15426,7 +15426,7 @@ Switched to forked session ${Ye.forkedSessionId}.`,restoredFileCount:Ye.restored
|
|
|
15426
15426
|
`),e.stdout.write(`default artifact: ${s.packaging.default}
|
|
15427
15427
|
`),t.verbose&&(e.stdout.write(`execPath: ${s.runtime.execPath}
|
|
15428
15428
|
`),e.stdout.write(`cwd: ${s.runtime.cwd}
|
|
15429
|
-
`)),
|
|
15429
|
+
`)),require(require("node:path").join(__dirname,"cli-config.cjs")).writeConfigurationDoctor(e.stdout,s.configuration)},"runDoctor"),xoc=r(async(e,t,n,o,s=!1)=>{try{let a=W8t(n.env??process.env),l=(n.cwd??process.cwd)(),u=TZn(a)?(n.loadDotenv??rA)({cwd:l,env:a}):{keys:[],loaded:!1};if(NCe(a),u.error)throw new Error(`Failed to load environment file: ${u.path}`,{cause:u.error});return await(n.runZCodeProtocolAgent??(await Qg()).runZCodeProtocolAgent)({lifecycle:n.protocolLifecycle,cwd:l,env:a,input:n.protocolInput??e.stdin,output:e.stdout,presentationSurface:o,prepareStorageOnly:s,version:S9}),0}catch(a){let l=a instanceof Error?a.message:String(a);return e.stderr.write(`Error: ${l}
|
|
15430
15430
|
`),t.verbose&&a instanceof Error&&a.stack&&e.stderr.write(`${a.stack}
|
|
15431
15431
|
`),1}},"runZCodeProtocolCommand"),Toc=r(async(e,t={})=>{if(e.argv[0]==="__internal-search")return KXo(e.argv.slice(1),{cwd:(t.cwd??process.cwd)(),stderr:e.stderr,stdin:e.stdin,stdout:e.stdout});if(BCe(e.argv))return await tGe(e,e.argv.slice(1));if(pQo(e.argv))return await fQo(e,e.argv.slice(1));if(e.argv[0]==="hooks")return await qXo(e,t,S9);let n,o;try{let U=goc(e.argv);n=Rqt(U.args),o=U.toolDisallowlist}catch(U){let B=U instanceof Error?U.message:String(U);return e.stderr.write(`${B}
|
|
15432
15432
|
|