zcode-app-cli 3.14.4-33 → 3.14.5-34
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 +5 -2
- package/docs/CONFIGURATION.md +32 -1
- package/docs/CONFIGURATION.zh-CN.md +23 -1
- package/package.json +1 -1
- package/vendor/cli-config.cjs +71 -0
- package/vendor/extraction.json +19 -4
- package/vendor/node_modules/@zcode/tui/dist/index.js +17 -0
- package/vendor/packages/node-repl-host/dist/mcp/server.js +1 -1
- package/vendor/zcode.cjs +2 -2
- package/zcode-runtime.lock.json +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={}){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)}
|
|
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:n!=="win32",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 require(require("node:path").join(__dirname,"cli-config.cjs")).browserOpenCommand(e,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?`
|
|
@@ -15246,7 +15246,7 @@ if (isProcessEntry) {
|
|
|
15246
15246
|
`)}function zVo(e){return e.trim().slice(0,2e3)}var Fbe,VVa,BVo,WAn,VAn,UVo,qVo=Y(()=>{"use strict";Fbe=require("node:path"),VVa=3e4,BVo=128*1024,WAn=/!`([^`]*)`/gu,VAn=/```!\s*\r?\n?([\s\S]*?)```/gu,UVo=/\$\{(CLAUDE_CODE_SESSION_ID|CLAUDE_PLUGIN_DATA|CLAUDE_PLUGIN_ROOT|CLAUDE_PROJECT_DIR|CLAUDE_SESSION_ID|CLAUDE_SKILL_DIR|ZCODE_PLUGIN_DATA|ZCODE_PLUGIN_ROOT|ZCODE_PROJECT_DIR|ZCODE_SESSION_ID|ZCODE_SKILL_DIR)\}/gu;r($Vo,"expandCustomCommandShellSyntax");r(HVa,"collectShellExpansionMatches");r(GVa,"pickNextMatch");r(JVa,"normalizeFencedShellCommand");r(KVa,"runShellExpansion");r(ZVa,"createShellExpansionEnv");r(YVa,"assertShellExpansionContextAvailable");r(XVa,"inferPluginContext");r(QVa,"formatShellExpansionError");r(zVo,"trimPreview")});function nHa(e){return e.trim().replace(/^\/+/,"").toLowerCase()}function jbe(e){return tHa.has(nHa(e))}var WVo,VVo,eHa,tHa,Bkt=Y(()=>{"use strict";ms();WVo=["goal","workflow","compact","init"],VVo=[{description:"Switch to Plan mode and optionally send a task.",inputHint:"/plan [task]",name:"plan",source:"builtin"}],eHa=["compress","plan"],tHa=new Set($R.flatMap(e=>[e.name,...e.aliases??[]]).concat([...eHa]));r(nHa,"normalizeZCodeSlashCommandName");r(jbe,"isReservedZCodeSlashCommandName")});async function HVo(e,t={}){let n=iHa(e);if(!(!n||jbe(n.name)))try{let o=await Fkt({...t,name:n.name});if(t.executionPort){let s=_Xt({args:n.args,command:o}),a=await $Vo({command:o,content:s.body,executionPort:t.executionPort,sessionId:t.sessionId,signal:t.signal,traceContext:t.traceContext,workingDirectory:t.workingDirectory??process.cwd()});return yXt({argumentCount:s.argumentCount,body:a,command:o,usedArgumentsPlaceholder:s.usedArgumentsPlaceholder}).prompt}return qQe({args:n.args,command:o}).prompt}catch(o){if(o instanceof Error&&rHa.test(o.message))return;throw o}}function iHa(e){let t=oHa.exec(e.trim());return t?.[1]?{args:t[2]?.trim()??"",name:t[1].toLowerCase()}:null}var rHa,oHa,GVo=Y(()=>{"use strict";nr();jkt();qVo();Bkt();rHa=/not found/i,oHa=/^\/([^\s]+)(?:\s+([\s\S]*))?$/;r(HVo,"resolveZCodeCustomCommandPrompt");r(iHa,"parsePromptCustomCommandInvocation")});function KVo(e){return qQe({args:e,command:cHa}).prompt}var f9,Ukt,JVo,sHa,aHa,HAn,cHa,GAn=Y(()=>{"use strict";nr();ms();Mje();f9="workflow",Ukt=$R.find(e=>e.name===f9);if(!Ukt)throw new Error(`Missing builtin slash command help entry: ${f9}`);JVo=`/${f9} `,sHa=Ukt.summary,aHa=Ukt.usage.startsWith(JVo)?Ukt.usage.slice(JVo.length):"",HAn=[`Use the \`${Cb}\` skill to design and launch a dynamic workflow for this request:`,"","$ARGUMENTS","","Decide the subagent topology before writing any code: how many subagents, which of them","share a context, what result each one returns. Then write the script and call the","`CreateWorkflow` tool. (`CreateWorkflow` is the dynamic-workflow tool. Do not use the","legacy `Workflow` tool, and do not substitute the `Agent` tool.)",""].join(`
|
|
15247
15247
|
`),cHa={bytesRead:Buffer.byteLength(HAn),content:HAn,metadata:{allowedTools:[],argumentHint:aHa,description:sHa,disableNonInteractive:!1,frontmatterKeys:["description","argument-hint","skills"],name:f9,path:`builtin:${f9}`,rootPath:"builtin:",scope:"system",skills:[Cb],source:"zcode"},sizeBytes:Buffer.byteLength(HAn),truncated:!1};r(KVo,"expandBuiltinWorkflowCommandPrompt")});function ZVo(e,t={}){let n=dHa(e);if(n){if(n.name===uHa){let o=t.workingDirectory??process.cwd();return pHa({args:n.args,targetPath:(0,zkt.join)(o,"AGENTS.md"),workingDirectory:o})}if(n.name===f9)return t.dynamicWorkflowEnabled===!1?void 0:KVo(n.args)}}function dHa(e){let t=lHa.exec(e.trim());return t?.[1]?{args:t[2]?.trim()??"",name:t[1].toLowerCase()}:null}function pHa(e){let t=e.args?["","Additional user instructions supplied with /init:","```text",e.args,"```"].join(`
|
|
15248
15248
|
`):"";return["You are running ZCode's built-in /init command.","","Your task is to create or update a concise workspace instruction file for future ZCode agents.","","Target:",`- Workspace directory: ${e.workingDirectory}`,`- Instruction file: ${e.targetPath}`,`- Existing hidden instruction candidates: ${(0,zkt.join)(e.workingDirectory,".zcode","AGENTS.md")} and ${(0,zkt.join)(e.workingDirectory,".agents","AGENTS.md")}`,"- File name must be exactly AGENTS.md.","- This command targets the current workspace only. Do not write ~/.zcode/AGENTS.md.",t,"","Process:","1. First check whether .zcode/AGENTS.md or .agents/AGENTS.md exists in the workspace. If either exists, tell the user they already have an instructions file, mention the path found, and stop without creating a new AGENTS.md.","2. Inspect the repository before writing. Prefer Read, Glob, Grep, and safe Bash commands such as ls, find, git status, and package-manager script inspection.","3. If AGENTS.md already exists, read it first and update it with Edit instead of replacing it wholesale.","4. If AGENTS.md does not exist, create it at the workspace root.","5. Keep the file practical and short enough for future agents to read quickly.","6. Include only project-specific facts future ZCode agents would otherwise miss.","7. Ask the user only if a repository-specific decision cannot be inferred and would materially change the file.","","Recommended AGENTS.md content:","- Repository purpose and major directories.","- Build, typecheck, lint, and focused test commands discovered from the repo.","- Architecture boundaries and layer rules that matter for edits.","- Coding conventions, import/path rules, logging rules, UI/design rules, and platform compatibility constraints if present.","- Known gotchas for desktop app, web, remote, stdio, protocols, or agent runtime if this repo has them.","- Any documentation files that agents should read before changing sensitive areas.","","After creating or editing AGENTS.md, summarize the main sections you wrote and mention the file path."].join(`
|
|
15249
|
-
`)}var zkt,lHa,uHa,YVo=Y(()=>{"use strict";zkt=require("node:path");GAn();lHa=/^\/([^\s]+)(?:\s+([\s\S]*))?$/,uHa="init";r(ZVo,"resolveZCodeBuiltinPromptCommand");r(dHa,"parseBuiltinPromptCommandInvocation");r(pHa,"buildInitAgentsPrompt")});async function XVo(e){let t=await Zqt((0,BK.join)(e.storageRoot,"agents"));await Kqt((0,BK.join)(e.storageRoot,"v2","agents-state.json"));let n=[{path:(0,BK.join)(e.storageRoot,"agents"),source:"user"},{path:(0,BK.join)(e.workingDirectory,".zcode","agents"),source:"project"}],o=[];for(let l of t.failures)o.push({code:"agent_read_failed",message:"Subagent Markdown migration failed; original file preserved",path:l.path}),e.logger?.warn("Subagent Markdown migration failed",{module:"bootstrap.subagents",path:l.path,error:String(l.error)});let s=vHa(e.storageRoot),a=[];for(let l of n)for(let u of eHo(l.path)){let f=(0,R8.readFileSync)(u,"utf8"),g=qvn({content:f,path:u,source:l.source});if(g.diagnostic&&(o.push(g.diagnostic),e.logger?.warn("Agent profile diagnostic",{code:g.diagnostic.code,message:g.diagnostic.message,module:"bootstrap.subagents",path:u})),g.profile){let _=mHa(g.profile);if(SHa(_,s.disabledAgentIds))continue;a.push(_)}}return e.logger?.debug("Agent profiles loaded",{diagnosticCount:o.length,module:"bootstrap.subagents",profileCount:a.length}),{builtInModelSelectionOverrides:s.builtInModelSelectionOverrides,pluginAgentModelSelectionOverrides:s.pluginAgentModelSelectionOverrides,diagnostics:o,profiles:a}}function mHa(e){if(e.source!=="project"||e.permissionMode===void 0)return e;let{permissionMode:t,...n}=e;return n}function QVo(e){let t=[],n=[],o=new Set([...fHa,...e.reservedProfileNames??[]]);for(let l of e.plugins){if(!l.enabled)continue;let u=l.components.find(f=>f.kind==="agent")?.items??[];for(let f of u){let g=(0,BK.join)(l.rootPath,"agents",`${f.name}.md`),_=hHa({filePath:g,logger:e.logger,plugin:l});_.diagnostic&&t.push(_.diagnostic),_.parsed&&n.push(_.parsed)}}let s=yHa(n),a=[];for(let l of n){let u=e.modelSelectionOverrides?.[Wqt(l.plugin.id,l.bareName)],f={...gHa(l),...u?{modelSelection:u}:{}};a.push(f);let g=l.bareName.trim();s.get(g)===1&&!o.has(g)?a.push({...f,name:g}):o.has(g)?t.push({code:"agent_ambiguous_name",message:`Plugin agent bare name conflicts with an existing profile; use ${f.name}: ${g}`,path:f.path}):(s.get(g)??0)>1&&t.push({code:"agent_ambiguous_name",message:`Plugin agent bare name is ambiguous; use ${f.name}: ${g}`,path:f.path})}return e.logger?.debug("Plugin agent profiles loaded",{diagnosticCount:t.length,module:"bootstrap.subagents",profileCount:a.length}),{builtInModelSelectionOverrides:{},pluginAgentModelSelectionOverrides:{},diagnostics:t,profiles:a}}function hHa(e){try{let t=(0,R8.readFileSync)(e.filePath,"utf8"),n=qvn({content:t,path:e.filePath,source:"user"});return n.diagnostic&&(e.logger?.warn("Plugin agent profile diagnostic",{code:n.diagnostic.code,message:n.diagnostic.message,module:"bootstrap.subagents",path:e.filePath,pluginId:e.plugin.id}),!n.profile)?{diagnostic:n.diagnostic}:n.profile?{...n.diagnostic?{diagnostic:n.diagnostic}:{},parsed:{bareName:n.profile.name,plugin:e.plugin,profile:n.profile}}:{}}catch(t){return{diagnostic:{code:"agent_read_failed",message:t instanceof Error?t.message:`Failed to read plugin agent: ${e.filePath}`,path:e.filePath}}}}function gHa(e){return{...e.profile,name:`${e.plugin.name}:${e.bareName}`}}function _Ha(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yHa(e){let t=new Map;for(let n of e){let o=n.bareName.trim();t.set(o,(t.get(o)??0)+1)}return t}function vHa(e){try{let t=(0,R8.readFileSync)((0,BK.join)(e,"v2","agents-state.json"),"utf8"),n=JSON.parse(t);return{pluginAgentModelSelectionOverrides:eAe(n.pluginAgentModelSelectionOverrides),builtInModelSelectionOverrides:bHa(n.builtInModelSelectionOverrides),disabledAgentIds:new Set(Array.isArray(n.disabledAgentIds)?n.disabledAgentIds.filter(o=>typeof o=="string"&&o.trim().length>0):[])}}catch{return{builtInModelSelectionOverrides:{},pluginAgentModelSelectionOverrides:{},disabledAgentIds:new Set}}}function bHa(e){let t={},n=_Ha(e)?e:{},o=Pu.safeParse(n["general-purpose"]),s=Pu.safeParse(n.Explore);return o.success&&(t["general-purpose"]=o.data),s.success&&(t.Explore=s.data),t}function SHa(e,t){return e.source!=="user"?!1:t.has(Vqt({name:e.name,scope:"user",source:"user"}))}function eHo(e){if(!(0,R8.existsSync)(e))return[];if(!(0,R8.statSync)(e).isDirectory())return[];let t=[];for(let n of(0,R8.readdirSync)(e,{withFileTypes:!0})){let o=(0,BK.join)(e,n.name);if(n.isDirectory()){t.push(...eHo(o));continue}n.isFile()&&/\.(md|markdown)$/iu.test(n.name)&&t.push(o)}return t.sort((n,o)=>n.localeCompare(o))}var R8,BK,fHa,tHo=Y(()=>{"use strict";R8=require("node:fs"),BK=require("node:path");bz();Y0();ms();fHa=new Set(["general-purpose","Explore"]);r(XVo,"loadZCodeAgentProfiles");r(mHa,"sanitizeProjectAgentProfile");r(QVo,"loadPluginAgentProfiles");r(hHa,"parsePluginAgentProfile");r(gHa,"namespacePluginAgentProfile");r(_Ha,"isRecord");r(yHa,"countBareProfileNames");r(vHa,"readAgentState");r(bHa,"normalizeBuiltInSelectionOverrides");r(SHa,"isDisabledUserProfile");r(eHo,"listMarkdownFiles")});function nHo(){let e=Zie(process.platform),t=Zie((0,$kt.arch)()),n=Zie((0,$kt.release)());return{...e&&t?{"X-Platform":`${e}-${t}`}:{},"X-Os-Category":kHa(process.platform),...n?{"X-Os-Version":n}:{}}}function Zie(e){let t=e?.trim();if(!(!t||!wHa.test(t)))return t}function kHa(e){switch(e){case"darwin":return"macos";case"win32":return"windows";default:return"linux"}}var $kt,wHa,rHo=Y(()=>{"use strict";$kt=require("node:os"),wHa=/^[\x20-\x7e]+$/;r(nHo,"createRuntimePlatformHeaders");r(Zie,"normalizePrintableHeaderValue");r(kHa,"normalizeOsCategory")});function oHo(e=process.env,t={}){let n=THa(t.network);return{defaultHeaders:iHo(e,t),codingPlanSignature:xHa(e,t),env:e,...n?{network:n}:{},...t.endpointRoutingPort?{endpointRoutingPort:t.endpointRoutingPort}:{}}}function xHa(e,t){return{configUrl:YAe(e,JJt),headers:iHo(e,t)}}function THa(e){if(!(!e?.caCertFile&&!e?.httpProxy&&!e?.noProxy))return{...e.caCertFile?{caCertFile:e.caCertFile}:{},...e.httpProxy?{httpProxy:e.httpProxy}:{},...e.noProxy?{noProxy:e.noProxy}:{}}}function iHo(e,t={}){let n=t.sourceTitle??CHa(),o=IHa(e,t),s=Zie(Intl.DateTimeFormat().resolvedOptions().locale),a=Zie(Intl.DateTimeFormat().resolvedOptions().timeZone);return{"HTTP-Referer":p1(e),"User-Agent":`ZCode/${o??"unknown"}`,...o?{"X-ZCode-App-Version":o}:{},"X-Title":`Z Code@${n}`,"X-Release-Channel":YL(e),"X-Client-Language":s??"unknown","X-Client-Timezone":a??"unknown","X-ZCode-Agent":"glm",...nHo()}}function IHa(e,t){return Zie(e[Ape]??t.appVersion)}function CHa(){return process.argv.includes("app-server")||process.argv.includes("agent-server")?"electron":"cli"}var sHo=Y(()=>{"use strict";ms();rHo();r(oHo,"createRuntimeAiSdkModelExecutionConfig");r(xHa,"createCodingPlanSignatureConfig");r(THa,"normalizeAiSdkNetworkConfig");r(iHo,"buildCliZCodeSourceHeaders");r(IHa,"resolveAppVersionForHeaders");r(CHa,"detectDefaultProviderSourceTitle")});var qkt,aHo=Y(()=>{"use strict";NK();qkt=class{static{r(this,"ApiProviderModelRuntime")}#e;#t;#n=!1;constructor(t){this.#e=t.registry,this.#t=t.modelAdapter}modelFactory=r(t=>{if(!this.#n)throw new Error("ApiProviderModelRuntime \u5FC5\u987B\u5148 start() \u518D\u521B\u5EFA Model");let n=this.#e.validateSelection(t.selection);if(!n.ok)throw $En(n);let o=t.selection.providerId,s=t.selection.modelId,a=this.#e.getProvider(o);if(!a)throw new Error("Registry Selection \u6821\u9A8C\u4E0E Provider \u7D22\u5F15\u7ED3\u679C\u4E0D\u4E00\u81F4");let l=this.#e.getModel(o,s);if(!l)throw new Error("Registry Selection \u6821\u9A8C\u4E0E Model \u7D22\u5F15\u7ED3\u679C\u4E0D\u4E00\u81F4");return this.#r(a,l,t)},"modelFactory");start(){this.#n||(this.#n=!0)}dispose(){this.#n=!1}#r(t,n,o){let s=n.config,a=o.selection.options.reasoningLevel;return this.#t.createModel({providerId:t.providerId,modelId:n.modelId,providerConfig:t.config,modelConfig:s,...t.config.access.type==="zhipu-account"&&t.config.access.mode==="off-peak"?{requestDependencies:{requestAuth:{source:o.requestDependencies?.requestAuth?.source}}}:{},options:{reasoningLevel:a}})}}});function Wkt(e){let t=e.options.pluginStorageRoot??bbe(e.cliStorageRoot),n=wct({config:e.configResult.config.plugins,env:e.env??process.env,officialPluginRoots:Aje({extraRoots:e.options.officialPluginRoots,logger:e.logger,storageRoot:t,suppressedBuiltins:new Set(e.configResult.config.plugins.suppressedBuiltins)}),officialPluginsEnabledByDefault:$wt,storageRoot:t,workingDirectory:e.workingDirectory});return e.startupTimer.mark("ZCode plugins resolved",{context:{commandRootCount:n.commandRoots.length,diagnosticCount:n.diagnostics.length,enabledPluginCount:n.plugins.filter(o=>o.enabled).length,hookCount:Object.values(n.hooks??{}).reduce((o,s)=>o+(s??[]).reduce((a,l)=>a+l.hooks.length,0),0),mcpServerCount:Object.keys(n.mcpServers).length,pluginCount:n.plugins.length,pluginStorageRoot:t,skillRootCount:n.skillRoots.length},event:"bootstrap.app.startup.plugins.completed",stage:"resolve_plugins"}),n}function cHo(e){e.startupTimer.start("ZCode app startup started",{context:{hasInjectedModelAdapter:e.hasInjectedModelAdapter,resume:e.resume},event:"bootstrap.app.startup.started",stage:"start"})}function lHo(e){e.startupTimer.mark("ZCode app configuration loaded",{context:{configSourceEnv:e.configResult.sources.env,configSourceProject:e.configResult.sources.project.loaded,configSourceUser:e.configResult.sources.user.loaded},event:"bootstrap.app.startup.config.completed",stage:"load_config"})}function uHo(e){e.startupTimer.mark("ZCode storage adapters initialized",{context:{hasInjectedArtifactStore:e.hasInjectedArtifactStore,hasInjectedSessionStore:e.hasInjectedSessionStore,cliStorageRoot:e.cliStorageRoot,storageRoot:e.storageRoot},event:"bootstrap.app.startup.storage.completed",stage:"initialize_storage"})}function dHo(e){e.startupTimer.mark("ZCode MCP adapter initialized",{context:{hasInjectedMcpPort:e.hasInjectedMcpPort,mcpEnabled:e.mcpEnabled,mcpServerCount:Object.keys(e.configuredMcpServers).length,trustedMcpServerCount:e.trustedMcpServerCount},event:"bootstrap.app.startup.mcp.completed",stage:"initialize_mcp"})}function pHo(e){e.startupTimer.mark("ZCode runtime constructed",{context:{hasInjectedModelAdapter:e.hasInjectedModelAdapter,sessionId:e.sessionId},event:"bootstrap.app.startup.runtime.completed",stage:"create_runtime"})}function fHo(e){e.startupTimer.complete("ZCode app startup completed",{context:{sessionId:e.sessionId,workingDirectory:e.workingDirectory},event:"bootstrap.app.startup.completed",stage:"total"})}function mHo(e){e.logger.debug("Runtime config resolved",{mode:e.runtimeConfig.mode,module:"bootstrap",permissionAllowedToolCount:e.configResult.config.permission.allowedTools.length,permissionDisallowedToolCount:e.configResult.config.permission.disallowedTools.length,permissionSourceEnv:e.configResult.sources.env,permissionSourceUserConfig:e.configResult.sources.user.loaded})}var JAn=Y(()=>{"use strict";GOe();qwt();MK();l9();r(Wkt,"resolveStartupPlugins");r(cHo,"startAppStartup");r(lHo,"markConfigurationLoaded");r(uHo,"markStorageAdaptersInitialized");r(dHo,"markMcpAdapterInitialized");r(pHo,"markRuntimeConstructed");r(fHo,"completeAppStartup");r(mHo,"debugRuntimeConfigResolved")});function EHa(e,t,n){let o=e.indexOf(","),s=e.slice(0,5).toLowerCase()==="data:"&&o>=0?e.slice(5,o).split(";"):[],a=(s.shift()?.trim()||t).split(";",1)[0].toLowerCase(),l=o>=0?e.slice(o+1):"";if(s.at(-1)?.trim().toLowerCase()!=="base64"||!/^[A-Za-z0-9+/]*={0,2}$/u.test(l)||l.length%4!==0)throw new Error("fault.attachment.previewArtifactInvalid");if(!a.startsWith("image/")&&!a.startsWith("video/")&&a!=="application/pdf")throw new Error("fault.attachment.previewNotMedia");let u=Buffer.from(l,"base64");if(u.byteLength>n)throw new Error("fault.attachment.previewTooLarge");return{bytes:u,mediaType:a}}async function KAn(e){if(!e?.providerRegistry)throw new Error("createZCodeApp requires a Provider Registry");let t=I4(),n=e.version??"0.0.0",o=e.sessionId??Ov(),s=e.traceContext??vA({sessionId:o}),a=(0,A4.resolve)(e.runtimeConfig?.workingDirectory??process.cwd()),l=Jzo(K0({env:e.env,projectConfigPath:e.projectConfigPath,workingDirectory:a,workspaceIdentity:e.runtimeConfig?.memory?.workspaceIdentity,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,cliOverrides:Gzo(e)}),e),u=e.loggerFactory??rB({env:e.env}),f=u.createLogger("zcode").child({...Qa(s),module:"bootstrap"}),g=new DK(f,{...Qa(s),module:"bootstrap",startupKind:"zcode_app"},t);cHo({hasInjectedModelAdapter:e.modelAdapter!==void 0,resume:e.resume===!0,startupTimer:g}),lHo({configResult:l,startupTimer:g});let _=u.createLogger("zcode").child({...Qa(s),module:"adapters.model"}),b=Bzo({owner:e.telemetryOwner,sessionId:o}),w,T,I;try{let E=zg(l.config.storage.dir),R=k8(E),L=Zzo(R,OCe(e.env??process.env)==="development"),U=await XVo({logger:f,storageRoot:E,workingDirectory:a}),B=U.profiles,z=Wkt({cliStorageRoot:R,configResult:l,env:e.env,logger:f,options:e,startupTimer:g,workingDirectory:a}),$=ekt({cliStorageRoot:R,logger:f}),J=QVo({logger:f,plugins:z.plugins,reservedProfileNames:B.map(kn=>kn.name),modelSelectionOverrides:U.pluginAgentModelSelectionOverrides}).profiles,q=s$o(z),ie=MVo({pluginOutcome:z,workingDirectory:a}),ae=[...B,...J],Ce=e.sessionStore===void 0,pe=e.sessionStore??await n7o(l,g),ze=Qzo(pe),rt=Sbe(a),Pe=e.runtimeConfig?.mode?void 0:e7o(ze,rt),{configuredMcpServers:Tt,runtimeConfig:Ye,untrustedProjectMcpServers:Fe}=T$o({cliStorageRoot:R,configResult:l,options:e,persistedMode:Pe,pluginHooks:z.hooks,pluginMcpServers:z.mcpServers,builtInMcpServers:ie,pluginRuntimeFeatures:q,builtInSubagentModelSelectionOverrides:U.builtInModelSelectionOverrides,subagentOutputRootDir:(0,A4.join)(R,"agents"),subagentProfiles:ae,storageRoot:E,workingDirectory:a,workspaceIdentity:e.runtimeConfig?.memory?.workspaceIdentity}),St=e.browserControlPort;St&&q.browserUse===!0&&Ye.mcp?.servers?.node_repl?.type==="stdio"&&(w=e.nodeReplBrowserBroker??(T=Nkt({browserControlPort:St,logger:f,platform:e.platform})),Tt=zAn(Tt,w),Ye.mcp={...Ye.mcp,servers:zAn(Ye.mcp.servers??{},w)}),g.mark("ZCode runtime configuration resolved",{context:I$o(Ye,a),event:"bootstrap.app.startup.runtime_config.completed",stage:"resolve_runtime_config"});let kt=Uye(z.plugins);Ye.pluginReferenceCatalog=kt;let st,$e=K$o({appVersion:n,logger:f,projectConfigPath:e.projectConfigPath,policy:e.workspaceHookPolicy,policyProvider:e.workspaceHookPolicyProvider,reviewHost:e.workspaceHookReviewHost,workspaceHookTrustEnabled:e.workspaceHookTrustEnabled,runtimeRoot:l.sources.project.workspaceHookRuntimeRoot??{enabled:Ye.hooks?.enabled===!0,timeoutMs:Ye.hooks?.timeoutMs??6e4,maxOutputBytes:Ye.hooks?.maxOutputBytes??32768},sessionId:o,snapshot:l.sources.project.workspaceHookSnapshot,userConfigPath:l.sources.user.path,workingDirectory:a,...e.workspaceHookReviewHost?{emitReviewEvent:r(async kn=>{if(!st)throw new Error("ZCode runtime is not initialized yet.");await st.appendEvent(om(kn.type,o,kn.payload,{traceId:s.traceId}),s)},"emitReviewEvent"),emitAdmissionEvent:r(async kn=>{if(!st)throw new Error("ZCode runtime is not initialized yet.");await st.appendEvent(om(kn.type,o,kn.payload,{traceId:s.traceId}),s)},"emitAdmissionEvent")}:{}}),jt=new UM({allowedTools:new Set(l.config.permission.allowedTools),autoApproveHighRisk:l.config.permission.autoApproveHighRisk,disallowedTools:new Set(l.config.permission.disallowedTools),allowMediumRiskInAutoMode:l.config.permission.allowMediumRiskInAuto}),Je=e.inputHistoryStore??Xzo(pe),Xe=e.artifactStore??yxr({imageCacheRootDir:(0,A4.join)(E,"cli","image-cache"),pdfCacheRootDir:(0,A4.join)(E,"cli","pdf-cache"),rootDir:(0,A4.join)(E,"cli","artifacts"),videoCacheRootDir:(0,A4.join)(E,"cli","video-cache")}),_t=e.imageProcessorPort??y3r(),Dt=Hzo(e.env??process.env),gn=e.sessionMailboxPort??(Dt?F2o({rootDir:zg((e.env??process.env).ZCODE_MAILBOX_ROOT??"~/.zcode/mailbox")}):void 0);uHo({cliStorageRoot:R,hasInjectedArtifactStore:e.artifactStore!==void 0,hasInjectedSessionStore:e.sessionStore!==void 0,startupTimer:g,storageRoot:E});let cn=e.mcpPort??(Ye.mcp?.enabled===!1?void 0:e.mcpPortFactory?.({workingDirectory:a})??Amn({clientVersion:n,env:e.env,logger:f,network:{httpProxy:l.config.network.httpProxy,noProxy:l.config.network.noProxy,caCertFile:l.config.network.caCertFile},workingDirectory:a})),Fn=e.mcpPort===void 0&&cn!==void 0,on=e.executionPort??sne({onToolExecResource:e.onToolExecResource,network:{httpProxy:l.config.network.httpProxy,noProxy:l.config.network.noProxy,caCertFile:l.config.network.caCertFile},outputRootDir:(0,A4.join)(E,"cli","exec"),processEnv:e.env??process.env}),dt=e.executionPort===void 0,we=e.pdfDocumentPort??S3r({executionPort:on}),_e=e.fileSystemPort??hH(),Pt=e.httpClientPort??C3({env:e.env??process.env,timeoutMs:l.config.network.timeout,proxyUrl:l.config.network.httpProxy,noProxy:l.config.network.noProxy,caCertFile:l.config.network.caCertFile}),ut=e.providerEndpointRoutingPort;dHo({configuredMcpServers:Tt,hasInjectedMcpPort:e.mcpPort!==void 0,mcpEnabled:Ye.mcp?.enabled!==!1,startupTimer:g,trustedMcpServerCount:Object.keys(Ye.mcp?.servers??{}).length}),mHo({configResult:l,logger:f,runtimeConfig:Ye});let Mn=r(()=>{if(!st)throw new Error("ZCode runtime is not initialized yet.");return st},"getRuntime"),Dr=!1,gr=r(()=>Qte({env:e.env??process.env,platform:e.platform??process.platform}).selection,"resolveDefaultShellSelection"),eo,to=r(()=>(eo??=(async()=>await e.resolveInitialBashShellSelection?.()??gr())(),eo),"resolveInitialShellSelection"),oo=r(async()=>{Mn().initializeSessionShellEnvironmentIfNeeded(await to())},"initializeSessionShellEnvironment"),ro=r(async()=>{let kn=e.providerRegistry,Nn;try{Nn=await t7o(pe,o)}catch(Vo){f.warn("Session model selection restore failed",{error:Vo instanceof Error?Vo.message:String(Vo),event:"session.model_selection.restore_failed",sessionId:o})}let Ur=Nn&&kn.validateSelection(Nn);Mn().$zRestoredSessionModel={selection:Nn,registry:kn};return Mn().setSessionModelSelection(Ur?.ok?Nn:void 0),Nn},"restorePersistedModelSelection"),Ji=r(async kn=>{let Nn=Mn(),Ur=kn?.onEvent?Nn.subscribeEvents({onSessionEvent:kn.onEvent}):void 0;try{let Vo=kn?.traceContext??s,qe=await ro();await oo();let Kt=await Nn.resumeFromStore({...kn?.abortSignal?{abortSignal:kn.abortSignal}:{},modeOverride:e.runtimeConfig?.mode,persistedMessages:kn?.persistedMessages,traceContext:Vo});return await Nn.activatePausedTargetAfterResume(Vo),Dr=!0,{...Kt,modelSelection:qe}}finally{Ur?.()}},"resumeFromStore"),pi=r(async(kn,Nn)=>{!e.resume||Dr||(await Ji({...Nn?{abortSignal:Nn}:{},traceContext:kn??s}),Dr=!0)},"prepareResume"),Wi=r(async kn=>{await oo(),await pi(kn?.traceContext,kn?.abortSignal)},"prepareUserExecutionBoundary"),Ii=oHo(e.env,{appVersion:n,endpointRoutingPort:ut,network:l.config.network,sourceTitle:e.sourceTitle}),Rs=e.modelAdapter??Ewt({env:e.env,logger:_,modelIoDir:L,modelIoFullRetentionEnabled:e.modelIoFullRetentionEnabled,executionConfig:Ii,statusSink:b.statusSink,streamIdleTimeoutMs:l.config.modelStream.idleTimeoutMs});e.modelAdapter&&b.statusSink&&Rs.addStatusSink(b.statusSink);let ht=zqo();Rs.setModelIoFullRetentionEnabled(e.modelIoFullRetentionEnabled??!1),I=new qkt({registry:e.providerRegistry,modelAdapter:Rs}),I.start();let mr=I.modelFactory,mi=F9o({agentTelemetry:b.agentExecution,appOptions:e,appVersion:n,artifactStore:Xe,configResult:l,fileSystemPort:_e,httpClientPort:Pt,imageProcessorPort:_t,pdfDocumentPort:we,logger:f,mcpPort:cn,modelFactory:mr,permissionService:jt,prepareUserExecutionBoundary:Wi,getRuntime:Mn,runtimeConfig:Ye,sessionId:o,sessionStore:pe,storageRoot:E,traceContext:s,workingDirectory:a}),Ar=qje(pe,f),hi=Ar===void 0?void 0:mVo({concurrency:ht,createActorRuntime:r(({persona:kn,pinnedModel:Nn,runSubagentModel:Ur,sessionId:Vo,submitPort:qe,submitProfile:Kt,escalatePort:Jt,modelRequestAdmission:en})=>lkt({childSessionId:Vo,configOverrides:{workflowActor:{...kn.name===void 0?{}:{name:kn.name},...kn.system===void 0?{}:{persona:kn.system}},...IVo(),...xVo({parentSelection:Mn().getSessionModelSelection(),...Ur===void 0?{}:{runSelection:Ur}},Nn).configOverrides},deps:{agentTelemetry:b.agentExecution,appOptions:e,appVersion:n,artifactStore:Xe,configResult:l,fileSystemPort:_e,httpClientPort:Pt,imageProcessorPort:_t,logger:f,mcpPort:cn,modelFactory:mr,permissionService:jt,runtime:Mn(),runtimeConfig:Ye,sessionId:o,sessionStore:pe,storageRoot:E,workingDirectory:a},request:{opts:{}},traceContext:s,...Kt.kind==="untyped"?{}:{workflowSubmitPort:qe},...Kt.kind==="mono"?{workflowSubmitSchema:{...Kt.schema}}:{},workflowEscalatePort:Jt,...en===void 0?{}:{modelRequestAdmission:en}}),"createActorRuntime"),actorTranscriptStore:pe,artifactStore:Xe,executionPort:on,fileSystemPort:_e,journal:Ar,logger:f,onRunEvent:wVo({getRuntime:Mn,logger:f,sessionId:o}),parentSessionId:o,registerResidencyBlockingWork:r(kn=>{Mn().trackResidencyBlockingWork(kn)},"registerResidencyBlockingWork"),resolveLaunchInputId:r(kn=>{let Nn=Mn().getActiveTurnInfo();return Nn!==void 0&&Nn.turnId===kn.turnId?Nn.inputId:void 0},"resolveLaunchInputId"),...sAn(pe)?{taskLinkStore:pe}:{}}),Js=yVo({executionPort:on,fileSystemPort:_e,logger:f}),qa=bVo({registry:e.providerRegistry,currentSelection:r(()=>Mn().getSessionModelSelection(),"currentSelection")});st=new V2(o,Ye,{agentTelemetry:b.agentExecution,modelRequestAdmission:ht.observer(),eventStore:e.eventStore??zz(),sessionStore:pe,sessionMailboxPort:gn,logger:f,executionPort:on,workspaceHookAdmission:$e?.admission,workspaceHookSnapshot:$e?.snapshot,browserControlPort:St,fileSystemPort:_e,httpClientPort:Pt,imageProcessorPort:_t,pdfDocumentPort:we,artifactStore:Xe,contextSourcePort:e.contextSourcePort??bme({env:e.env}),skillPort:l.config.features.skill&&l.config.skills.enabled?e.skillPort??mG({extraRoots:l.config.skills.roots,extraResolvedRoots:[...z.skillRoots,...$],disabledPaths:[...x8(l.config.skillOverrides),...Ye.dynamicWorkflowEnabled===!1?M$o($):[]]}):void 0,mcpPort:cn,eventSink:e.eventSink,modelFactory:mr,modelIoDir:L,providerRuntimeHeadersPort:e.providerRuntimeHeadersPort,resolveEffectiveModelSelection:e.resolveEffectiveModelSelection,isRemoteWorkspace:r(()=>YJt(Ye.memory?.workspaceIdentity??""),"isRemoteWorkspace"),permissionBroker:e.permissionBroker,permissionService:jt,workflowPort:mi.workflowPort,dynamicWorkflowRunPort:hi,dynamicWorkflowSnippetPort:Js,modelCatalogPort:qa,automationPort:e.automationPort,offPeakPort:e.offPeakPort,appVersion:n,traceContext:s}),pHo({hasInjectedModelAdapter:e.modelAdapter!==void 0,sessionId:o,startupTimer:g}),fHo({sessionId:o,startupTimer:g,workingDirectory:a}),Rwt(u,f);let li=d7o({artifactStore:Xe,customCommandPromptResolver:r(async(kn,Nn)=>{let Ur=ZVo(kn,{dynamicWorkflowEnabled:Ye.dynamicWorkflowEnabled,workingDirectory:a});return Ur!==void 0?Ur:await HVo(kn,{env:e.env,executionPort:on,logger:f,projectConfigPath:e.projectConfigPath,sessionId:o,signal:Nn?.abortSignal,skipUserConfig:e.skipUserConfig,traceContext:Nn?.traceContext??s,userConfigPath:e.userConfigPath,workingDirectory:a})},"customCommandPromptResolver"),inputHistoryStore:Je,logger:f,prepareUserExecutionBoundary:Wi,runtime:st,sessionId:o,traceContext:s}),oa=i7o({agentTelemetry:b.agentExecution,appOptions:e,appVersion:n,artifactStore:Xe,cliStorageRoot:R,configResult:l,eventSink:e.eventSink,imageProcessorPort:_t,pdfDocumentPort:we,logger:f,mcpPort:cn,modelFactory:mr,permissionService:jt,prepareUserExecutionBoundary:Wi,runtime:st,runtimeConfig:Ye,sessionId:o,sessionStore:pe,storageRoot:E,traceContext:s,workingDirectory:a}),Fs=S$o({...hi===void 0?{}:{closeDynamicWorkflowRuns:r(()=>hi.close(),"closeDynamicWorkflowRuns")},configResult:l,configuredMcpServers:Tt,...e.configuredDefaultModelSelection?{configuredDefaultModelSelection:e.configuredDefaultModelSelection}:{},executionPort:on,localSettingStore:ze,logger:f,loggerFactory:u,mcpPort:cn,ownsExecutionPort:dt,ownsMcpPort:Fn,closeNodeReplBrowserBroker:r(async()=>{await T?.close()},"closeNodeReplBrowserBroker"),ownsSessionStore:Ce,prepareUserExecutionBoundary:Wi,prepareResume:pi,projectID:rt,providerRegistry:e.providerRegistry,resolveUiLocale:r(kn=>xEn(kn,e),"resolveUiLocale"),runtime:st,sessionId:o,sessionStore:pe,traceContext:s,untrustedProjectMcpServers:Fe,workingDirectory:a}),Qo=Fs.close,gi=r(async kn=>{let Nn=kn.ref,Ur=kn.mime,Vo;if(kn.messageId&&kn.attachmentIndex!==void 0){let Kt=(await pe.messageWithParts({sessionID:o,messageID:kn.messageId}))?.parts.filter(Jt=>Jt.type==="file")[kn.attachmentIndex];Kt?.type==="file"&&(Ur=Kt.mime,Vo=Kt.metadata?.artifactUri??(Kt.url.startsWith("zcode-artifact://")?Kt.url:void 0),Nn=Vo??(Kt.url.startsWith("data:")?kn.ref:Kt.url))}return{ref:Nn,mediaType:Ur,...Vo?{artifactUri:Vo}:{}}},"resolvePromptAttachment");return{sessionId:o,traceId:s.traceId,runtime:st,respondWorkspaceHookReview:r(kn=>$e?.respond({sessionId:kn.sessionId,taskId:kn.taskId,runId:kn.runId,...kn.remoteSessionId?{remoteSessionId:kn.remoteSessionId}:{},workspaceIdentity:kn.workspaceIdentity,bundleDigest:kn.bundleDigest,reviewFlowId:kn.reviewFlowId,generation:kn.generation,interactionId:kn.interactionId},kn.decision)??Promise.resolve({accepted:!1,reasonCode:"workspace_hooks_require_trust_capable_host"}),"respondWorkspaceHookReview"),toggleWorkspaceHookReviewItem:r(kn=>$e?.toggle({sessionId:kn.sessionId,taskId:kn.taskId,runId:kn.runId,...kn.remoteSessionId?{remoteSessionId:kn.remoteSessionId}:{},workspaceIdentity:kn.workspaceIdentity,bundleDigest:kn.bundleDigest,reviewFlowId:kn.reviewFlowId,generation:kn.generation,interactionId:kn.interactionId},kn.reviewItemId,kn.enabled)??Promise.resolve({accepted:!1,reasonCode:"workspace_hooks_require_trust_capable_host"}),"toggleWorkspaceHookReviewItem"),revokeWorkspaceHookTrust:r(kn=>("hookDeclarationDigests"in kn?$e?.revokeCurrent(kn):$e?.revoke({sessionId:kn.sessionId,taskId:kn.taskId,runId:kn.runId,...kn.remoteSessionId?{remoteSessionId:kn.remoteSessionId}:{},workspaceIdentity:kn.workspaceIdentity,bundleDigest:kn.bundleDigest,reviewFlowId:kn.reviewFlowId,generation:kn.generation,interactionId:kn.interactionId},kn.reviewItemIds))??Promise.resolve({accepted:!1,reasonCode:"workspace_hooks_require_trust_capable_host"}),"revokeWorkspaceHookTrust"),requestWorkspaceHookReview:r(kn=>$e?.requestReview({workspaceIdentity:kn.workspaceIdentity,bundleDigest:kn.bundleDigest})??Promise.resolve({accepted:!1,reasonCode:"workspace_hooks_require_trust_capable_host"}),"requestWorkspaceHookReview"),reloadWorkspaceHookTrust:r(()=>$e?.reloadTrust()??Promise.resolve(),"reloadWorkspaceHookTrust"),setModelIoFullRetentionEnabled:r(kn=>Rs.setModelIoFullRetentionEnabled(kn),"setModelIoFullRetentionEnabled"),readToolResultArtifact:r(kn=>Xe.readToolResultArtifact({uri:kn,trace:s}),"readToolResultArtifact"),writePromptAttachment:r(async kn=>{let Nn=await Xe.writeToolResultArtifact({content:`data:${kn.mime};base64,${Buffer.from(kn.bytes).toString("base64")}`,contentType:"text/plain",retention:"session",sessionId:o,toolCallId:`prompt-attachment-upload-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,toolName:"prompt-attachment:upload",trace:s});return(kn.mime.startsWith("image/")||kn.mime.startsWith("video/")||kn.mime.split(";",1)[0]?.trim().toLowerCase()==="application/pdf")&&Xe.primeMediaAttachmentPath?.({bytes:kn.bytes,mediaType:kn.mime,uri:Nn.uri}).catch(()=>{}),{ref:Nn.uri}},"writePromptAttachment"),readPromptAttachment:r(async kn=>{let{ref:Nn,mediaType:Ur}=await gi(kn);if(Nn.startsWith("zcode-artifact://")){let qe=await Xe.readToolResultArtifact({uri:Nn,trace:s});return EHa(qe.content,Ur,kn.maxBytes)}return{bytes:(await _e.readBinaryFile({path:Nn,maxBytes:kn.maxBytes,trace:s})).content,mediaType:Ur}},"readPromptAttachment"),statPromptAttachment:r(async kn=>{let{ref:Nn,mediaType:Ur,artifactUri:Vo}=await gi(kn);if(Vo){if(!Xe.statToolResultArtifact)throw new m1(nC.statUnsupported);let Kt=await Xe.statToolResultArtifact({uri:Vo,trace:s});return{totalBytes:Kt.bytes,mediaType:Kt.contentType||Ur,...Kt.mtimeMs===void 0?{}:{mtimeMs:Kt.mtimeMs}}}let qe=await _e.stat({path:Nn,trace:s});if(qe.kind!=="file")throw new m1(nC.statNotFile);return{totalBytes:qe.sizeBytes,mediaType:Ur,...qe.mtimeMs===void 0?{}:{mtimeMs:qe.mtimeMs}}},"statPromptAttachment"),resolvePromptAttachmentPreviewSource:r(async kn=>{let Nn=await gi(kn);if(!Nn.mediaType.startsWith("video/"))return{kind:"chunked"};if(Nn.artifactUri){if(!Xe.ensureMediaAttachmentPath)return{kind:"chunked"};try{let Ur=await Xe.ensureMediaAttachmentPath({uri:Nn.artifactUri,mediaType:Nn.mediaType});if(Ur.status==="ready"&&Ur.path.trim())return{kind:"local_path",path:Ur.path,mediaType:Nn.mediaType}}catch{}return{kind:"chunked"}}return(0,A4.isAbsolute)(Nn.ref)?{kind:"local_path",path:Nn.ref,mediaType:Nn.mediaType}:{kind:"chunked"}},"resolvePromptAttachmentPreviewSource"),...Fs,close:r(async()=>{try{await Qo?.()}finally{try{I?.dispose()}finally{await b.shutdown()}}},"close"),...oa,...mi,...hi===void 0?{}:{listDynamicWorkflowRunEvents:r(async kn=>hi.listEvents(kn.runId,{...kn.afterSequence===void 0?{}:{afterSequence:kn.afterSequence},...kn.limit===void 0?{}:{limit:kn.limit}}),"listDynamicWorkflowRunEvents")},...hi===void 0||typeof hi.listArtifacts!="function"||typeof hi.listArtifactItems!="function"||typeof hi.readArtifact!="function"?{}:{listDynamicWorkflowRunArtifacts:r(async kn=>hi.listArtifacts(kn.runId),"listDynamicWorkflowRunArtifacts"),listDynamicWorkflowRunArtifactItems:r(async kn=>hi.listArtifactItems(kn.runId,kn.artifactId,{...kn.afterSequence===void 0?{}:{afterSequence:kn.afterSequence},limit:kn.limit}),"listDynamicWorkflowRunArtifactItems"),readDynamicWorkflowRunArtifact:r(async kn=>hi.readArtifact(kn.runId,kn.artifactId,kn.version),"readDynamicWorkflowRunArtifact")},...hi===void 0||typeof hi.listWorkspaceNodes!="function"||typeof hi.readWorkspaceNodeResult!="function"?{}:{listDynamicWorkflowRunWorkspaceNodes:r(async kn=>hi.listWorkspaceNodes(kn.runId),"listDynamicWorkflowRunWorkspaceNodes"),readDynamicWorkflowRunNodeResult:r(async kn=>hi.readWorkspaceNodeResult(kn.runId,kn.siteId,kn.ordinal,{maxBytes:kn.maxBytes}),"readDynamicWorkflowRunNodeResult")},...hi===void 0?{}:{},...hi===void 0||typeof hi.listRunsForSession!="function"?{}:{listDynamicWorkflowRuns:r(async kn=>hi.listRunsForSession(kn.limit),"listDynamicWorkflowRuns")},...hi===void 0||typeof hi.replayProgressForSession!="function"?{}:{replayDynamicWorkflowRuns:r(async kn=>hi.replayProgressForSession(kn),"replayDynamicWorkflowRuns")},...hi===void 0||typeof hi.resume!="function"?{}:{resumeWorkflowRun:r(async kn=>{let Nn=await hi.resume(kn.workId);return Nn.ok&&await Mn().trackResumedDynamicWorkflowRun({runId:Nn.runId,...Nn.toolCallId===void 0?{}:{toolCallId:Nn.toolCallId},...kn.name===void 0?{}:{name:kn.name},traceContext:s}),Nn},"resumeWorkflowRun")},...hi===void 0?{}:{startSavedWorkflow:r(async kn=>(await Wi({traceContext:s}),await Mn().startSavedWorkflowRun({...kn,traceContext:s})),"startSavedWorkflow")},...hi===void 0||typeof hi.amend!="function"||typeof hi.getScript!="function"?{}:{amendWorkflowRunSettings:r(async kn=>(await Wi({traceContext:s}),await Mn().amendWorkflowRunSettings({...kn,traceContext:s})),"amendWorkflowRunSettings")},...r$o({configResult:l,options:e,workingDirectory:a}),getPluginReferenceCatalog:r(()=>kt,"getPluginReferenceCatalog"),getSkillCatalog:r(async()=>(await Wi({traceContext:s}),await Mn().getSkillCatalog(s)),"getSkillCatalog"),resume:Ji,...li}}catch(E){throw I?.dispose(),b.shutdown().catch(()=>{}),T?.close(),g.fail("ZCode app startup failed",E,{context:{sessionId:o,workingDirectory:a},event:"bootstrap.app.startup.failed",stage:"total"}),E}}var A4,ZAn=Y(()=>{"use strict";A4=require("node:path");f3();W0e();vw();Eme();yme();a7();Msn();Fsn();j2o();xRe();K0e();sdt();Y0();Cwt();nr();ms();g0();wEn();Pwt();kEn();Kzo();l9();wbe();s7o();p7o();o$o();a$o();w$o();C$o();Mje();N$o();Z$o();j9o();BAn();SAn();vVo();SVo();kVo();QEn();TVo();CVo();$An();NVo();GVo();YVo();kbe();tHo();sHo();aHo();JAn();r(EHa,"decodePromptAttachmentDataUrl");r(KAn,"createZCodeApp")});function QAn(e){let t=DHa.parse(e),n=t.model,o=Hkt(typeof n=="string"?n:n?.main),s=typeof n=="object"?Hkt(n?.lite):void 0,a=o||s?{...o?{main:o}:{},...s?{lite:s}:{}}:void 0;return{...a?{model:a}:{},...t.provider?{provider:t.provider}:{}}}function Hkt(e){if(!e)return;let t=e.indexOf("/");if(t<=0||t===e.length-1)return;let n=e.slice(0,t).trim(),o=e.slice(t+1).trim();if(!(!n||!o))return{provider:n,model:o}}var XAn,hHo,Vkt,AHa,PHa,RHa,YAn,DHa,gHo=Y(()=>{"use strict";Fa();XAn=m.record(m.string(),m.string()),hHo=m.record(m.string(),m.unknown()),Vkt=m.number().finite().positive(),AHa=m.object({enabled:m.boolean().optional(),levels:m.array(m.string().min(1)).optional(),defaultLevel:m.string().min(1).optional(),providerOptionsByLevel:m.record(m.string(),hHo).optional()}),PHa=m.object({id:m.string().min(1).optional(),name:m.string().min(1).optional(),attachment:m.boolean().optional(),reasoning:m.union([m.boolean(),AHa]).optional(),tool_call:m.boolean().optional(),structured_output:m.boolean().optional(),supportsImages:m.boolean().optional(),supportsPdf:m.boolean().optional(),supportsVideo:m.boolean().optional(),supportsToolCall:m.boolean().optional(),supportsJsonSchemaOutput:m.boolean().optional(),contextWindow:Vkt.optional(),maxOutputTokens:Vkt.optional(),limit:m.object({context:Vkt.optional(),output:Vkt.optional()}).optional(),modalities:m.object({input:m.array(m.enum(["text","audio","image","video","pdf"])).optional(),output:m.array(m.enum(["text","audio","image","video","pdf"])).optional()}).optional(),options:hHo.optional(),headers:XAn.optional()}).passthrough(),RHa=m.object({kind:m.enum(["anthropic","openai","openai-compatible"]),name:m.string().min(1).optional(),npm:m.never().optional(),options:m.object({apiKey:m.string().optional(),baseURL:m.string().min(1).optional(),apiKeyRequired:m.boolean().optional(),headers:XAn.optional()}).passthrough().optional(),headers:XAn.optional(),models:m.record(m.string(),PHa).optional()}).passthrough(),YAn=m.string().refine(e=>Hkt(e)!==void 0,{message:"Model references must use provider/model format"}),DHa=m.object({provider:m.record(m.string(),RHa).optional(),model:m.union([YAn,m.object({main:YAn.optional(),lite:YAn.optional()}).strict().refine(e=>e.main!==void 0||e.lite!==void 0)]).optional(),small_model:m.never().optional()}).passthrough();r(QAn,"parseLegacyCliModelConfig");r(Hkt,"parseModelTarget")});function MHa(e){switch(e){case"anthropic":return"anthropic-messages";case"openai":return"openai-responses";case"openai-compatible":case void 0:return"openai-chat-completions"}return"openai-chat-completions"}function NHa(e){let t=QAn(e.input),n=uw.empty(),o=dA.empty();for(let[a,l]of Object.entries(t.provider??{})){let u=a.trim();if(!u)continue;let f=u==="builtin:bigmodel"?aee.bigmodel:u==="builtin:zai"?aee.zai:void 0;if(f){let w=l.options?.apiKey?.trim();w&&(n=n.setRule({providerId:f,templateId:f,config:new Tk({group:"standard-personal",access:new xz({apiKey:w})})}));continue}if(u.startsWith("builtin:")||u.startsWith("account:")||l.source!==void 0&&l.source!=="custom")continue;if(BHa(l))throw new Gkt(u);let g=FHa(l),_=g.map(w=>w.modelId),b=l.name?.trim();n=n.setRule({providerId:u,providerName:b&&b!==u?b:void 0,config:new Tk({group:"standard-personal",access:new xz({apiKey:l.options?.apiKey}),api:new _pe({type:MHa(l.kind),baseUrl:l.options?.baseURL,headers:jHa(l.headers,l.options?.headers)}),..._.length>0?{personalModelIds:_,modelOrder:_}:{}})});for(let w of g)w.contextWindow!==void 0&&(o=o.setExact(u,w.modelId,new uA({properties:new lAe({contextWindow:w.contextWindow})})))}let s=LHa(e.input)??void 0;return Object.freeze({providers:n,models:o,defaultModelSelection:s})}async function Jkt(e){let t=e.filePath??U7();try{let n=JSON.parse(await(0,_Ho.readFile)(t,"utf8"));return NHa({input:n})}catch(n){if(UHa(n)||n instanceof Gkt)return null;throw n}}function LHa(e){let t=QAn(e).model?.main;return!t||t.provider===OHa?null:Object.freeze({providerId:t.provider,modelId:t.model})}function FHa(e){let t=new Set,n=[];for(let[o,s]of Object.entries(e.models??{})){if(s.deleted===!0)continue;let a=(s.id??o).trim();if(!a||t.has(a))continue;t.add(a);let l=s.contextWindow??s.limit?.context;n.push({modelId:a,...zHa(l)?{contextWindow:l}:{}})}return n}function jHa(...e){let t=Object.assign({},...e.filter(Boolean));return Object.keys(t).length>0?t:void 0}function BHa(e){return e.options?.apiKeyRequired===!1}function UHa(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function zHa(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0}var _Ho,OHa,Gkt,ePn=Y(()=>{"use strict";_Ho=require("node:fs/promises");ms();vw();gHo();pA();OHa="builtin:zapi",Gkt=class extends Error{static{r(this,"UnsupportedLegacyCliProviderConfigError")}providerId;constructor(t){super(`\u65E7 CLI Provider ${t} \u542B\u6709\u6B63\u5F0F Config \u5C1A\u4E0D\u80FD\u8868\u8FBE\u7684\u6267\u884C\u5B57\u6BB5`),this.name="UnsupportedLegacyCliProviderConfigError",this.providerId=t}};r(MHa,"resolveLegacyProviderApiType");r(NHa,"importLegacyCliPersonalProviderConfig");r(Jkt,"readLegacyCliPersonalProviderConfig");r(LHa,"importLegacyCliConfiguredDefault");r(FHa,"collectLegacyCliModelMembers");r(jHa,"mergeHeaders");r(BHa,"requiresUnsupportedNoAuthentication");r(UHa,"isFileNotFound");r(zHa,"isPositiveInteger")});async function tPn(e){return(await nPn(e)).providers}async function nPn(e,t){if(t)return{zcodeBuiltinRevision:t.revision,providers:t.providers.entries().flatMap(([s,a])=>{let l=a.access,u=a.builtinModelIds?.find(f=>f.trim())?.trim();return l?.type==="zhipu-account"&&l.mode==="individual-coding-plan"&&l.accountType&&u?[{family:l.accountType,modelId:u,providerId:s}]:[]})};let n=e[LV]?.trim();if(!n)throw new Error(`${LV} is required for login`);let o=new UO({bundledFilePath:n,watch:!1});try{let s=await o.read();return nPn(e,s)}finally{o.dispose()}}async function vHo(e,t){let n=(await tPn(t)).filter(o=>o.family===e);if(n.length!==1)throw new Error(`ZCode Built-in Config \u5FC5\u987B\u4E3A ${e} \u58F0\u660E\u552F\u4E00 Individual Coding Plan Provider`);return n[0]}function Yie(e){let t=e.trim();if(!t)throw new Error("Standalone Account Provider ID \u4E0D\u80FD\u4E3A\u7A7A");return`account-provider:${t}:identity`}function t3e(e){let t=e.providerId.trim(),n=e.accountIdentity.trim();if(!t)throw new Error("Standalone Account Provider ID \u4E0D\u80FD\u4E3A\u7A7A");if(!n)throw new Error("Standalone Account Identity \u4E0D\u80FD\u4E3A\u7A7A");return`account-provider:coding-plan:${t}:account:${encodeURIComponent(n)}:api-key`}function rPn(e){let t=e.trim();if(!t)throw new Error("Standalone Account Secret \u4E0D\u80FD\u4E3A\u7A7A");return`key-${(0,yHo.createHash)("sha256").update(t).digest("hex").slice(0,24)}`}async function oPn(e,t,n){let o=await nPn(t,n),s=o.providers,a=s.map(({providerId:b})=>Yie(b)),l=await e.loadMany(a),u=s.flatMap(({family:b,providerId:w})=>{let T=l[Yie(w)]?.trim();if(!T)return[];let I=t3e({providerId:w,accountIdentity:T});return[{accountIdentity:T,credentialKey:I,family:b,providerId:w}]}),f=await e.loadMany(u.map(({credentialKey:b})=>b)),g=new Map(u.map(b=>[b.providerId,b])),_=new uw(s.map(({family:b,providerId:w})=>{let T=g.get(w),I=T?f[T.credentialKey]?.trim():void 0;return!T||!I?[w,new Tk({access:new zj({entitled:!1})})]:[w,new Tk({access:new zj({entitled:!0})})]}));return pAe(o.zcodeBuiltinRevision,_)}async function bHo(e,t){return(await oPn(e,t)).providers.entries().some(([,n])=>n.access?.type==="zhipu-account"?n.access.entitled===!0:!1)}function SHo(e,t){return{shouldRefreshBeforeModelRequest(){return!0},async refreshBeforeModelRequest(n){n.abortSignal?.throwIfAborted();let o=n.providerId.trim(),s=n.accountAccess;if(!s||s.mode!=="individual-coding-plan")throw new Error(`Standalone Account Provider \u8BF7\u6C42\u8EAB\u4EFD\u65E0\u6548: ${o}`);let a=(await e.load(Yie(o)))?.trim();if(!a)throw new Error(`Standalone Account Provider \u51ED\u636E\u5DF2\u7ECF\u5931\u6548: ${o}`);let l=(await e.load(t3e({providerId:o,accountIdentity:a})))?.trim();if(!l)throw new Error(`Standalone Account Provider \u7F3A\u5C11\u8BF7\u6C42\u51ED\u636E: ${o}`);return{headersApplied:!0,requestAuth:{apiKey:l}}}}}var yHo,iPn=Y(()=>{"use strict";yHo=require("node:crypto");pA();hfe();r(tPn,"readStandaloneCodingPlanProviders");r(nPn,"readStandaloneCodingPlanCatalog");r(vHo,"resolveStandaloneCodingPlanProvider");r(Yie,"standaloneAccountIdentityCredentialKey");r(t3e,"standaloneAccountProviderCredentialKey");r(rPn,"createStandaloneAccountIdentityFromSecret");r(oPn,"readStandaloneAccountProviderConfigSnapshot");r(bHo,"hasStandaloneCodingPlanAccess");r(SHo,"createStandaloneProviderRuntimeHeadersPort")});function UK(e){if(e?.aborted)throw sPn(e)}async function wHo(e,t,n){if(!n){await e(t);return}await Promise.race([e(t),xHo(n)])}async function kHo(e){let t;try{return await Promise.race([e.callbackServer.waitForCallback(),new Promise((n,o)=>{t=setTimeout(()=>o(e.createTimeoutError()),e.timeoutMs)}),xHo(e.signal)])}finally{t&&clearTimeout(t)}}function xHo(e){return e?new Promise((t,n)=>{if(e.aborted){n(sPn(e));return}e.addEventListener("abort",()=>n(sPn(e)),{once:!0})}):new Promise(()=>{})}function sPn(e){return e.reason??new Error("Login cancelled.")}var THo=Y(()=>{"use strict";r(UK,"throwIfAborted");r(wHo,"sleepWithAbort");r(kHo,"waitForCallbackWithAbort");r(xHo,"rejectOnAbort");r(sPn,"abortReason")});async function WHa(e={}){let t=e.credentialStore??jM({env:e.env});return bHo(t,e.env??process.env)}async function VHa(e={}){if((e.env??process.env).ZCODE_CLI_OAUTH_CALLBACK_STDIN==="1"){let $zEnv=e.env??process.env;UK(e.abortSignal);let $zStore=e.credentialStore??jM({env:$zEnv}),$zHttp=e.httpClient??CHo($zEnv),$zPayload;try{$zPayload=JSON.parse(require("node:fs").readFileSync(0,"utf8"))}catch($zError){throw new m9("invalid_callback","Unable to read the Z.AI OAuth callback.",{cause:$zError})}if(!$zPayload||typeof $zPayload.callbackUrl!=="string"||typeof $zPayload.state!=="string")throw new m9("invalid_callback","The Z.AI OAuth callback payload is invalid.");let $zUrl;try{$zUrl=new URL($zPayload.callbackUrl)}catch($zError){throw new m9("invalid_callback","The Z.AI OAuth callback URL is invalid.",{cause:$zError})}if($zUrl.protocol!=="zcode:"||$zUrl.hostname!=="zai-auth"||$zUrl.pathname.replace(/\/+$/u,"")!=="/callback")throw new m9("invalid_callback","The Z.AI OAuth callback target is invalid.");let $zCode=$zUrl.searchParams.get("code")??$zUrl.searchParams.get("authCode"),$zState=$zUrl.searchParams.get("state");if(!$zCode||!$zState||$zState!==$zPayload.state)throw new m9("invalid_callback","The Z.AI OAuth callback state is invalid or expired.");let $zResponse=await $zHttp.request({maxResponseBytes:65536,body:new TextEncoder().encode(JSON.stringify({provider:"zai",code:$zCode,redirect_uri:"zcode://zai-auth/callback",state:$zState})),headers:{"Content-Type":"application/json"},method:"POST",trace:e.trace,url:"https://zcode.z.ai/api/v1/oauth/token"},e.abortSignal),$zText=new TextDecoder().decode($zResponse.body),$zEnvelope;try{$zEnvelope=JSON.parse($zText)}catch($zError){throw new m9("token_exchange_failed",$zResponse.status<200||$zResponse.status>=300?"OAuth HTTP error "+$zResponse.status+" (empty or non-JSON response)":"OAuth response is not valid JSON",{cause:$zError})}let $zMessage=typeof $zEnvelope?.msg==="string"&&$zEnvelope.msg.trim()?$zEnvelope.msg.trim():void 0;if($zResponse.status<200||$zResponse.status>=300)throw new m9("token_exchange_failed",$zMessage??"OAuth HTTP error "+$zResponse.status);if($zEnvelope?.code!==0)throw new m9("token_exchange_failed",$zMessage??"Z.AI token exchange failed.");let $zData=$zEnvelope.data,$zAccessToken=$zData?.zai?.access_token,$zJwtToken=$zData?.token,$zUser=$zData?.user;if(typeof $zAccessToken!=="string"||typeof $zJwtToken!=="string"||!$zUser||typeof $zUser!=="object")throw new m9("token_exchange_failed","Z.AI token response is missing credentials or user data.");UK(e.abortSignal);try{await $zStore.saveZaiLoginCredentials({accessToken:$zAccessToken,jwtToken:$zJwtToken,user:$zUser})}catch($zError){throw new m9("credential_write_failed","Login succeeded but writing credentials failed.",{cause:$zError})}let $zApiKey=await EHo({accessToken:$zAccessToken,env:$zEnv,httpClient:$zHttp,family:"zai",resolver:e.apiKeyResolver}),$zConfig;try{$zConfig=await aPn({accountIdentity:$zUser.user_id,apiKey:$zApiKey,credentialStore:$zStore,env:$zEnv,personalProviderConfigPath:e.personalProviderConfigPath,providerId:"zai"})}catch($zError){throw new m9("config_update_failed","Login succeeded but updating ZCode config failed.",{cause:$zError})}return{configPath:$zConfig.path,credentialsPath:$zStore.filePath,model:$zConfig.mainModel,providerId:"zai",user:$zUser}}let t=e.env??process.env,n=e.now??Date.now,o=e.sleep??XHa;UK(e.abortSignal);let s=e.pollToken??HZr(),a=e.credentialStore??jM({env:t}),l=KHa(e,t),u=await l.init({pollToken:s});await e.onAuthorizeUrl?.(u),UK(e.abortSignal);let f=e.noBrowser?void 0:await(e.openBrowser??Ydn)(u.authorize_url);f&&await e.onBrowserOpen?.(f);let g=await YHa({abortSignal:e.abortSignal,initData:u,now:n,oauthClient:l,onPollStatus:e.onPollStatus,pollToken:s,sleep:o,timeoutMs:e.timeoutMs??IHo});UK(e.abortSignal);try{await a.saveZaiLoginCredentials({accessToken:g.zai.access_token,jwtToken:g.token,user:g.user})}catch(w){throw new m9("credential_write_failed","Login succeeded but writing credentials failed.",{cause:w})}let _=await EHo({accessToken:g.zai.access_token,env:t,httpClient:e.httpClient,family:"zai",resolver:e.apiKeyResolver}),b;try{b=await aPn({accountIdentity:g.user.user_id,apiKey:_,credentialStore:a,env:t,personalProviderConfigPath:e.personalProviderConfigPath,providerId:"zai"})}catch(w){throw new m9("config_update_failed","Login succeeded but updating ZCode config failed.",{cause:w})}return{...f?{browser:f}:{},configPath:b.path,credentialsPath:a.filePath,model:b.mainModel,providerId:"zai",user:g.user}}async function HHa(e={}){let t=e.env??process.env;UK(e.abortSignal);let n=e.httpClient??CHo(t),o=e.state??MZr(),s=e.callbackServer??await YOe({callbackPath:qHa,state:o}),a=OZr({httpClient:n}),l=a.buildAuthorizeUrl({redirectUri:s.callbackUrl,state:o});await e.onAuthorizeUrl?.({authorize_url:l,callback_url:s.callbackUrl,state:o}),UK(e.abortSignal);let u=e.noBrowser?void 0:await(e.openBrowser??Ydn)(l);u&&await e.onBrowserOpen?.(u),UK(e.abortSignal);try{let f=await kHo({callbackServer:s,createTimeoutError:r(()=>new m9("auth_timeout","Authorization timed out. Please retry login."),"createTimeoutError"),signal:e.abortSignal,timeoutMs:e.timeoutMs??IHo}),g=await a.exchangeCode({code:f.code}),_=await EHo({accessToken:g.accessToken,env:t,httpClient:n,family:"bigmodel",resolver:e.apiKeyResolver}),b=e.credentialStore??jM({env:t}),w=rPn(_);await b.saveMany({[R1.activeProvider]:"bigmodel",[R1.bigmodelAccessToken]:g.accessToken,...g.refreshToken?{[R1.bigmodelRefreshToken]:g.refreshToken}:{},[R1.bigmodelUserInfo]:JSON.stringify({id:w})});let T=await aPn({accountIdentity:w,apiKey:_,credentialStore:b,env:t,personalProviderConfigPath:e.personalProviderConfigPath,providerId:"bigmodel"});return{...u?{browser:u}:{},configPath:T.path,model:T.mainModel,providerId:"bigmodel"}}finally{await s.close()}}async function GHa(e){let t=e.apiKey.trim();if(!t)throw new m9("config_update_failed","API key must not be empty.");let n=e.credentialStore??jM({env:e.env}),o=await aPn({accountIdentity:rPn(t),apiKey:t,credentialStore:n,env:e.env??process.env,personalProviderConfigPath:e.personalProviderConfigPath,providerId:e.providerId});return{configPath:o.path,model:o.mainModel,providerId:e.providerId}}async function JHa(e={}){let t=e.credentialStore??jM({env:e.env}),n=(await tPn(e.env??process.env)).map(({providerId:f})=>f),o=n.map(Yie),s=await t.loadMany(o),a=n.flatMap(f=>{let g=s[Yie(f)]?.trim();return g?[t3e({providerId:f,accountIdentity:g})]:[]}),l=[...Object.values(R1),...o,...a],u=await t.loadMany(l);return await t.deleteIfValues(Object.fromEntries(Object.entries(u).flatMap(([f,g])=>g===null?[]:[[f,g]]))),{credentialsPath:t.filePath}}async function aPn(e){let t=await vHo(e.providerId,e.env),n=t.providerId,o=t.modelId,s=t3e({providerId:n,accountIdentity:e.accountIdentity});await e.credentialStore.saveMany({[Yie(n)]:e.accountIdentity,[s]:e.apiKey});let a=e.personalProviderConfigPath??e.env[tte]?.trim()??(0,Kkt.join)((0,Kkt.dirname)(e.credentialStore.filePath),MXe),l=new Cpe({filePath:a,importLegacy:r(()=>Jkt({}),"importLegacy"),pollingIntervalMs:!1}),u=new Tpe({personalRepository:l});try{await u.saveConfiguredDefault({providerId:n,modelId:o})}finally{u.dispose(),l.dispose()}return{mainModel:`${n}/${o}`,path:a}}function KHa(e,t){let n=e.baseUrl??Bee(ZHa(t)).apiBaseUrl;if(e.httpClient)return Xdn({baseUrl:n,httpClient:e.httpClient});let o=K0({env:t});return Xdn({baseUrl:n,httpClient:s2e({env:t,proxyUrl:o.config.network.httpProxy,noProxy:o.config.network.noProxy,caCertFile:o.config.network.caCertFile,timeoutMs:o.config.network.timeout})})}function ZHa(e){return p1(e)}function CHo(e){let t=K0({env:e});return s2e({env:e,proxyUrl:t.config.network.httpProxy,noProxy:t.config.network.noProxy,caCertFile:t.config.network.caCertFile,timeoutMs:t.config.network.timeout})}async function EHo(e){return(e.resolver??$Zr({httpClient:e.httpClient??CHo(e.env)})).resolve({accessToken:e.accessToken,family:e.family})}async function YHa(e){let t=e.initData.expires_at*1e3,n=Math.min(e.now()+e.timeoutMs,t),o=Math.max($Ha,e.initData.poll_interval_sec*1e3);for(;e.now()<n;){UK(e.abortSignal);let s=await e.oauthClient.poll({flowId:e.initData.flow_id,pollToken:e.pollToken});if(await e.onPollStatus?.(s),s.status==="ready")return s;if(s.status==="failed")throw new m9("auth_failed","Authorization failed. Please retry login.");await wHo(e.sleep,Math.min(o,Math.max(0,n-e.now())),e.abortSignal)}throw new m9("auth_timeout","Authorization timed out. Please retry login.")}function XHa(e){return new Promise(t=>setTimeout(t,e))}var Kkt,IHo,$Ha,qHa,m9,AHo=Y(()=>{"use strict";adt();vw();a7();ms();hfe();ePn();Kkt=require("node:path");iPn();THo();IHo=300*1e3,$Ha=1e3,qHa="/oauth/callback/bigmodel";r(WHa,"hasConfiguredStandaloneCodingPlan");m9=class extends Error{static{r(this,"ZCodeCliLoginError")}code;constructor(t,n,o={}){super(n,o),this.name="ZCodeCliLoginError",this.code=t}};r(VHa,"loginZCodeCli");r(HHa,"loginBigmodelCodingPlan");r(GHa,"configureCodingPlanApiKey");r(JHa,"logoutZCodeCli");r(aPn,"persistStandaloneCodingPlanConnection");r(KHa,"createOAuthClient");r(ZHa,"resolveCliZCodeEndpointOrigin");r(CHo,"createDefaultHttpClient");r(EHo,"resolveCodingPlanApiKey");r(YHa,"pollUntilReady");r(XHa,"sleepMs")});async function OHo(e={}){let t=e.env??process.env,n=await rGa(nGa(t));return _Kt({appVersion:t[Ape]??e.appVersion,arch:(0,Bbe.arch)(),clientLanguage:eGa(),clientTimezone:tGa(),deviceMid:n,endpointOrigin:p1(t),osVersion:(0,Bbe.release)(),platform:process.platform,releaseChannel:YL(t),sourceTitle:e.sourceTitle??"cli"})}function eGa(){return Intl.DateTimeFormat().resolvedOptions().locale}function tGa(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function nGa(e){let t=e[QHa]?.trim()||(0,Bbe.homedir)();return(0,DHo.join)(t,".zcode","v2","telemetry-state.json")}async function rGa(e){let t=PHo.get(e);if(t)return t;try{let n=JSON.parse(await(0,RHo.readFile)(e,"utf8"));if(typeof n.deviceMid!="string")return;let o=n.deviceMid.trim();return!o||!/^[\x20-\x7e]+$/.test(o)?void 0:(PHo.set(e,o),o)}catch{return}}var RHo,Bbe,DHo,QHa,PHo,MHo=Y(()=>{"use strict";RHo=require("node:fs/promises"),Bbe=require("node:os"),DHo=require("node:path");ms();QHa="ZCODE_DATA_BASE_DIR",PHo=new Map;r(OHo,"createProviderEndpointRoutingSourceHeaders");r(eGa,"resolveClientLanguage");r(tGa,"resolveClientTimezone");r(nGa,"resolveTelemetryStateFile");r(rGa,"readExistingDeviceMid")});function n3e(e){let t=e.env??process.env,n=YAe(t,oGa),o=iGa(n,e.network),s=NHo.get(o);if(s)return s;let a=new dat({appVersion:e.appVersion,configUrl:n,httpClient:s2e({caCertFile:e.network.caCertFile,env:t,noProxy:e.network.noProxy,proxyUrl:e.network.httpProxy}),logger:e.logger.child({module:"adapters.model.provider_endpoint_routing"}),sourceHeaders:r(()=>OHo({appVersion:e.appVersion,env:t,sourceTitle:e.sourceTitle}),"sourceHeaders")});return NHo.set(o,a),a}function LHo(e){let t=e.env??process.env,n=K0({env:t,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:e.workingDirectory}),s=(e.loggerFactory??rB({env:t})).createLogger("zcode").child({module:"bootstrap.provider_endpoint_routing"});return n3e({appVersion:e.appVersion,env:t,logger:s,network:n.config.network,sourceTitle:e.sourceTitle})}function iGa(e,t){return JSON.stringify({caCertFile:t.caCertFile,configUrl:e,httpProxy:t.httpProxy,noProxy:t.noProxy})}var oGa,NHo,cPn=Y(()=>{"use strict";vw();a7();fOe();W0e();ms();MHo();oGa="/api/v1/agent/configs",NHo=new Map;r(n3e,"resolveProcessProviderEndpointRoutingPort");r(LHo,"createDefaultProviderEndpointRoutingPort");r(iGa,"routingRegistryKey")});async function Ykt(e,t={}){let n=ymr(e);if(!n)throw new Error("\u7F3A\u5C11\u8FDB\u7A0B Provider Registry \u7684 ZCode Built-in / Personal Config \u8DEF\u5F84");let o=new yee,s=t.standalone?t.standalone.credentialStore??jM({env:{...e}}):void 0,a,l=t.standalone?e[OXe]?.trim():void 0,u=new pZe({...n,...l?{zcodeBuiltinFilePath:l,zcodeBuiltinActiveFilePath:n.zcodeBuiltinFilePath,zcodeBuiltinRemote:{controlFilePath:(0,Zkt.join)((0,Zkt.dirname)(n.zcodeBuiltinFilePath),"zcode-builtin-refresh.json"),resolveEndpointKey:r(()=>p1(e),"resolveEndpointKey"),fetchRelease:r((_,b)=>xnr({endpointOrigin:_,signal:b,appVersion:HL,platform:aZe(),request:t.standalone?.request??globalThis.fetch}),"fetchRelease"),onRefreshResult:t.standalone?.onBuiltinRefreshResult}}:{},onZCodeBuiltinRefreshError:t.standalone?.onBuiltinRefreshError,accountSource:o,...s?{createAccountSource(_){return a=new GKe({configSource:_,async resolve({configRevision:b,configuredProviders:w}){let T=await oPn(s,e,{revision:b,providers:w});return{providers:T.providers,states:T.states??{}}}}),a.onDidRefreshError(({error:b})=>{try{t.standalone?.onAccountInitializationError?.(b)}catch{}}),a}}:{},...t.standalone?{importLegacy:r(()=>Jkt({...t.standalone?.legacyCliUserConfigFilePath?{filePath:t.standalone.legacyCliUserConfigFilePath}:{}}),"importLegacy")}:{}}),f=a?u.onDidCheckZCodeBuiltin(async()=>{let[_,b]=await Promise.all([u.configService.read(),a.read()]);_.zcodeBuiltinRevision!==b.basedOnZCodeBuiltinRevision&&await a.refresh("builtin-account-recovery")}):void 0,g=s?.onDidChange?.(async()=>{await a.refresh("standalone-credentials-changed"),await u.registryService.refresh("standalone-credentials-barrier")});try{await u.start();let _=u.registryService.getSnapshot(),b=new Tpe({personalRepository:u.personalRepository});try{let w=await b.read();return Object.freeze({accountSource:a??o,async syncAccountProviderConfig(T){if(a)throw new Error("Standalone Account \u7531\u672C\u8FDB\u7A0B\u7BA1\u7406\uFF0C\u4E0D\u63A5\u6536 Host \u8986\u76D6");let I=o.replace(T,"host-account-config");return await u.registryService.refresh("host-account-config"),I},dispose(){g?.(),f?.(),a?.dispose(),b.dispose(),u.dispose()},...s?{providerRuntimeHeadersPort:SHo(s,e)}:{},runtime:u,snapshot:_,modelSelectionConfigRepository:b,configuredDefaultModelSelection:w})}catch(w){throw g?.(),b.dispose(),w}}catch(_){throw g?.(),f?.(),a?.dispose(),u.dispose(),_}}function FHo(e){let t=e.revision.trim();if(!t)throw new Error("Account Config revision \u4E0D\u80FD\u4E3A\u7A7A");let n=e.basedOnZCodeBuiltinRevision.trim();if(!n)throw new Error("Account Config Built-in revision \u4E0D\u80FD\u4E3A\u7A7A");let o=Qtr(e.providers);for(let[s,a]of o.entries())if(cee(s)&&a.access?.type==="zhipu-account"&&a.access.entitled&&typeof e.states?.[s]?.current!="boolean")throw new Error(`Account State \u7F3A\u5C11 current: ${s}`);return Object.freeze({revision:t,basedOnZCodeBuiltinRevision:n,providers:o,...e.states?{states:e.states}:{}})}var Zkt,Xkt=Y(()=>{"use strict";pA();ms();Zkt=require("node:path");hfe();rpn();ePn();iPn();r(Ykt,"startProcessProviderRegistryRuntime");r(FHo,"parseProcessAccountProviderConfigSnapshot")});async function lPn(e){let t=(0,Ube.randomUUID)(),n=(0,Ube.createHash)("sha256").update(e.dbPath).digest("hex"),o=0,s=!1,a=r(async l=>{let u=vYe.parse({schemaVersion:1,attemptId:t,databaseId:n,databaseKind:"session",sequence:++o,...l});s||=u.phase==="failed",e.onProgress?.(u),await new Promise((f,g)=>{e.output.write(`${JSON.stringify({method:BR.storageStartup,params:u})}
|
|
15249
|
+
`)}var zkt,lHa,uHa,YVo=Y(()=>{"use strict";zkt=require("node:path");GAn();lHa=/^\/([^\s]+)(?:\s+([\s\S]*))?$/,uHa="init";r(ZVo,"resolveZCodeBuiltinPromptCommand");r(dHa,"parseBuiltinPromptCommandInvocation");r(pHa,"buildInitAgentsPrompt")});async function XVo(e){let t=await Zqt((0,BK.join)(e.storageRoot,"agents"));await Kqt((0,BK.join)(e.storageRoot,"v2","agents-state.json"));let n=[{path:(0,BK.join)(e.storageRoot,"agents"),source:"user"},{path:(0,BK.join)(e.workingDirectory,".zcode","agents"),source:"project"}],o=[];for(let l of t.failures)o.push({code:"agent_read_failed",message:"Subagent Markdown migration failed; original file preserved",path:l.path}),e.logger?.warn("Subagent Markdown migration failed",{module:"bootstrap.subagents",path:l.path,error:String(l.error)});let s=vHa(e.storageRoot),a=[];for(let l of n)for(let u of eHo(l.path)){let f=(0,R8.readFileSync)(u,"utf8"),g=qvn({content:f,path:u,source:l.source});if(g.diagnostic&&(o.push(g.diagnostic),e.logger?.warn("Agent profile diagnostic",{code:g.diagnostic.code,message:g.diagnostic.message,module:"bootstrap.subagents",path:u})),g.profile){let _=mHa(g.profile);if(SHa(_,s.disabledAgentIds))continue;a.push(_)}}return e.logger?.debug("Agent profiles loaded",{diagnosticCount:o.length,module:"bootstrap.subagents",profileCount:a.length}),{builtInModelSelectionOverrides:s.builtInModelSelectionOverrides,pluginAgentModelSelectionOverrides:s.pluginAgentModelSelectionOverrides,diagnostics:o,profiles:a}}function mHa(e){if(e.source!=="project"||e.permissionMode===void 0)return e;let{permissionMode:t,...n}=e;return n}function QVo(e){let t=[],n=[],o=new Set([...fHa,...e.reservedProfileNames??[]]);for(let l of e.plugins){if(!l.enabled)continue;let u=l.components.find(f=>f.kind==="agent")?.items??[];for(let f of u){let g=(0,BK.join)(l.rootPath,"agents",`${f.name}.md`),_=hHa({filePath:g,logger:e.logger,plugin:l});_.diagnostic&&t.push(_.diagnostic),_.parsed&&n.push(_.parsed)}}let s=yHa(n),a=[];for(let l of n){let u=e.modelSelectionOverrides?.[Wqt(l.plugin.id,l.bareName)],f={...gHa(l),...u?{modelSelection:u}:{}};a.push(f);let g=l.bareName.trim();s.get(g)===1&&!o.has(g)?a.push({...f,name:g}):o.has(g)?t.push({code:"agent_ambiguous_name",message:`Plugin agent bare name conflicts with an existing profile; use ${f.name}: ${g}`,path:f.path}):(s.get(g)??0)>1&&t.push({code:"agent_ambiguous_name",message:`Plugin agent bare name is ambiguous; use ${f.name}: ${g}`,path:f.path})}return e.logger?.debug("Plugin agent profiles loaded",{diagnosticCount:t.length,module:"bootstrap.subagents",profileCount:a.length}),{builtInModelSelectionOverrides:{},pluginAgentModelSelectionOverrides:{},diagnostics:t,profiles:a}}function hHa(e){try{let t=(0,R8.readFileSync)(e.filePath,"utf8"),n=qvn({content:t,path:e.filePath,source:"user"});return n.diagnostic&&(e.logger?.warn("Plugin agent profile diagnostic",{code:n.diagnostic.code,message:n.diagnostic.message,module:"bootstrap.subagents",path:e.filePath,pluginId:e.plugin.id}),!n.profile)?{diagnostic:n.diagnostic}:n.profile?{...n.diagnostic?{diagnostic:n.diagnostic}:{},parsed:{bareName:n.profile.name,plugin:e.plugin,profile:n.profile}}:{}}catch(t){return{diagnostic:{code:"agent_read_failed",message:t instanceof Error?t.message:`Failed to read plugin agent: ${e.filePath}`,path:e.filePath}}}}function gHa(e){return{...e.profile,name:`${e.plugin.name}:${e.bareName}`}}function _Ha(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yHa(e){let t=new Map;for(let n of e){let o=n.bareName.trim();t.set(o,(t.get(o)??0)+1)}return t}function vHa(e){try{let t=(0,R8.readFileSync)((0,BK.join)(e,"v2","agents-state.json"),"utf8"),n=JSON.parse(t);return{pluginAgentModelSelectionOverrides:eAe(n.pluginAgentModelSelectionOverrides),builtInModelSelectionOverrides:bHa(n.builtInModelSelectionOverrides),disabledAgentIds:new Set(Array.isArray(n.disabledAgentIds)?n.disabledAgentIds.filter(o=>typeof o=="string"&&o.trim().length>0):[])}}catch{return{builtInModelSelectionOverrides:{},pluginAgentModelSelectionOverrides:{},disabledAgentIds:new Set}}}function bHa(e){let t={},n=_Ha(e)?e:{},o=Pu.safeParse(n["general-purpose"]),s=Pu.safeParse(n.Explore);return o.success&&(t["general-purpose"]=o.data),s.success&&(t.Explore=s.data),t}function SHa(e,t){return e.source!=="user"?!1:t.has(Vqt({name:e.name,scope:"user",source:"user"}))}function eHo(e){if(!(0,R8.existsSync)(e))return[];if(!(0,R8.statSync)(e).isDirectory())return[];let t=[];for(let n of(0,R8.readdirSync)(e,{withFileTypes:!0})){let o=(0,BK.join)(e,n.name);if(n.isDirectory()){t.push(...eHo(o));continue}n.isFile()&&/\.(md|markdown)$/iu.test(n.name)&&t.push(o)}return t.sort((n,o)=>n.localeCompare(o))}var R8,BK,fHa,tHo=Y(()=>{"use strict";R8=require("node:fs"),BK=require("node:path");bz();Y0();ms();fHa=new Set(["general-purpose","Explore"]);r(XVo,"loadZCodeAgentProfiles");r(mHa,"sanitizeProjectAgentProfile");r(QVo,"loadPluginAgentProfiles");r(hHa,"parsePluginAgentProfile");r(gHa,"namespacePluginAgentProfile");r(_Ha,"isRecord");r(yHa,"countBareProfileNames");r(vHa,"readAgentState");r(bHa,"normalizeBuiltInSelectionOverrides");r(SHa,"isDisabledUserProfile");r(eHo,"listMarkdownFiles")});function nHo(){let e=Zie(process.platform),t=Zie((0,$kt.arch)()),n=Zie((0,$kt.release)());return{...e&&t?{"X-Platform":`${e}-${t}`}:{},"X-Os-Category":kHa(process.platform),...n?{"X-Os-Version":n}:{}}}function Zie(e){let t=e?.trim();if(!(!t||!wHa.test(t)))return t}function kHa(e){switch(e){case"darwin":return"macos";case"win32":return"windows";default:return"linux"}}var $kt,wHa,rHo=Y(()=>{"use strict";$kt=require("node:os"),wHa=/^[\x20-\x7e]+$/;r(nHo,"createRuntimePlatformHeaders");r(Zie,"normalizePrintableHeaderValue");r(kHa,"normalizeOsCategory")});function oHo(e=process.env,t={}){let n=THa(t.network);return{defaultHeaders:iHo(e,t),codingPlanSignature:xHa(e,t),env:e,...n?{network:n}:{},...t.endpointRoutingPort?{endpointRoutingPort:t.endpointRoutingPort}:{}}}function xHa(e,t){return{configUrl:YAe(e,JJt),headers:iHo(e,t)}}function THa(e){if(!(!e?.caCertFile&&!e?.httpProxy&&!e?.noProxy))return{...e.caCertFile?{caCertFile:e.caCertFile}:{},...e.httpProxy?{httpProxy:e.httpProxy}:{},...e.noProxy?{noProxy:e.noProxy}:{}}}function iHo(e,t={}){let n=t.sourceTitle??CHa(),o=IHa(e,t),s=Zie(Intl.DateTimeFormat().resolvedOptions().locale),a=Zie(Intl.DateTimeFormat().resolvedOptions().timeZone);return{"HTTP-Referer":p1(e),"User-Agent":`ZCode/${o??"unknown"}`,...o?{"X-ZCode-App-Version":o}:{},"X-Title":`Z Code@${n}`,"X-Release-Channel":YL(e),"X-Client-Language":s??"unknown","X-Client-Timezone":a??"unknown","X-ZCode-Agent":"glm",...nHo()}}function IHa(e,t){return Zie(e[Ape]??t.appVersion)}function CHa(){return process.argv.includes("app-server")||process.argv.includes("agent-server")?"electron":"cli"}var sHo=Y(()=>{"use strict";ms();rHo();r(oHo,"createRuntimeAiSdkModelExecutionConfig");r(xHa,"createCodingPlanSignatureConfig");r(THa,"normalizeAiSdkNetworkConfig");r(iHo,"buildCliZCodeSourceHeaders");r(IHa,"resolveAppVersionForHeaders");r(CHa,"detectDefaultProviderSourceTitle")});var qkt,aHo=Y(()=>{"use strict";NK();qkt=class{static{r(this,"ApiProviderModelRuntime")}#e;#t;#n=!1;constructor(t){this.#e=t.registry,this.#t=t.modelAdapter}modelFactory=r(t=>{if(!this.#n)throw new Error("ApiProviderModelRuntime \u5FC5\u987B\u5148 start() \u518D\u521B\u5EFA Model");let n=this.#e.validateSelection(t.selection);if(!n.ok)throw $En(n);let o=t.selection.providerId,s=t.selection.modelId,a=this.#e.getProvider(o);if(!a)throw new Error("Registry Selection \u6821\u9A8C\u4E0E Provider \u7D22\u5F15\u7ED3\u679C\u4E0D\u4E00\u81F4");let l=this.#e.getModel(o,s);if(!l)throw new Error("Registry Selection \u6821\u9A8C\u4E0E Model \u7D22\u5F15\u7ED3\u679C\u4E0D\u4E00\u81F4");return this.#r(a,l,t)},"modelFactory");start(){this.#n||(this.#n=!0)}dispose(){this.#n=!1}#r(t,n,o){let s=n.config,a=o.selection.options.reasoningLevel;return this.#t.createModel({providerId:t.providerId,modelId:n.modelId,providerConfig:t.config,modelConfig:s,...t.config.access.type==="zhipu-account"&&t.config.access.mode==="off-peak"?{requestDependencies:{requestAuth:{source:o.requestDependencies?.requestAuth?.source}}}:{},options:{reasoningLevel:a}})}}});function Wkt(e){let t=e.options.pluginStorageRoot??bbe(e.cliStorageRoot),n=wct({config:e.configResult.config.plugins,env:e.env??process.env,officialPluginRoots:Aje({extraRoots:e.options.officialPluginRoots,logger:e.logger,storageRoot:t,suppressedBuiltins:new Set(e.configResult.config.plugins.suppressedBuiltins)}),officialPluginsEnabledByDefault:$wt,storageRoot:t,workingDirectory:e.workingDirectory});return e.startupTimer.mark("ZCode plugins resolved",{context:{commandRootCount:n.commandRoots.length,diagnosticCount:n.diagnostics.length,enabledPluginCount:n.plugins.filter(o=>o.enabled).length,hookCount:Object.values(n.hooks??{}).reduce((o,s)=>o+(s??[]).reduce((a,l)=>a+l.hooks.length,0),0),mcpServerCount:Object.keys(n.mcpServers).length,pluginCount:n.plugins.length,pluginStorageRoot:t,skillRootCount:n.skillRoots.length},event:"bootstrap.app.startup.plugins.completed",stage:"resolve_plugins"}),n}function cHo(e){e.startupTimer.start("ZCode app startup started",{context:{hasInjectedModelAdapter:e.hasInjectedModelAdapter,resume:e.resume},event:"bootstrap.app.startup.started",stage:"start"})}function lHo(e){e.startupTimer.mark("ZCode app configuration loaded",{context:{configSourceEnv:e.configResult.sources.env,configSourceProject:e.configResult.sources.project.loaded,configSourceUser:e.configResult.sources.user.loaded},event:"bootstrap.app.startup.config.completed",stage:"load_config"})}function uHo(e){e.startupTimer.mark("ZCode storage adapters initialized",{context:{hasInjectedArtifactStore:e.hasInjectedArtifactStore,hasInjectedSessionStore:e.hasInjectedSessionStore,cliStorageRoot:e.cliStorageRoot,storageRoot:e.storageRoot},event:"bootstrap.app.startup.storage.completed",stage:"initialize_storage"})}function dHo(e){e.startupTimer.mark("ZCode MCP adapter initialized",{context:{hasInjectedMcpPort:e.hasInjectedMcpPort,mcpEnabled:e.mcpEnabled,mcpServerCount:Object.keys(e.configuredMcpServers).length,trustedMcpServerCount:e.trustedMcpServerCount},event:"bootstrap.app.startup.mcp.completed",stage:"initialize_mcp"})}function pHo(e){e.startupTimer.mark("ZCode runtime constructed",{context:{hasInjectedModelAdapter:e.hasInjectedModelAdapter,sessionId:e.sessionId},event:"bootstrap.app.startup.runtime.completed",stage:"create_runtime"})}function fHo(e){e.startupTimer.complete("ZCode app startup completed",{context:{sessionId:e.sessionId,workingDirectory:e.workingDirectory},event:"bootstrap.app.startup.completed",stage:"total"})}function mHo(e){e.logger.debug("Runtime config resolved",{mode:e.runtimeConfig.mode,module:"bootstrap",permissionAllowedToolCount:e.configResult.config.permission.allowedTools.length,permissionDisallowedToolCount:e.configResult.config.permission.disallowedTools.length,permissionSourceEnv:e.configResult.sources.env,permissionSourceUserConfig:e.configResult.sources.user.loaded})}var JAn=Y(()=>{"use strict";GOe();qwt();MK();l9();r(Wkt,"resolveStartupPlugins");r(cHo,"startAppStartup");r(lHo,"markConfigurationLoaded");r(uHo,"markStorageAdaptersInitialized");r(dHo,"markMcpAdapterInitialized");r(pHo,"markRuntimeConstructed");r(fHo,"completeAppStartup");r(mHo,"debugRuntimeConfigResolved")});function EHa(e,t,n){let o=e.indexOf(","),s=e.slice(0,5).toLowerCase()==="data:"&&o>=0?e.slice(5,o).split(";"):[],a=(s.shift()?.trim()||t).split(";",1)[0].toLowerCase(),l=o>=0?e.slice(o+1):"";if(s.at(-1)?.trim().toLowerCase()!=="base64"||!/^[A-Za-z0-9+/]*={0,2}$/u.test(l)||l.length%4!==0)throw new Error("fault.attachment.previewArtifactInvalid");if(!a.startsWith("image/")&&!a.startsWith("video/")&&a!=="application/pdf")throw new Error("fault.attachment.previewNotMedia");let u=Buffer.from(l,"base64");if(u.byteLength>n)throw new Error("fault.attachment.previewTooLarge");return{bytes:u,mediaType:a}}async function KAn(e){if(!e?.providerRegistry)throw new Error("createZCodeApp requires a Provider Registry");let t=I4(),n=e.version??"0.0.0",o=e.sessionId??Ov(),s=e.traceContext??vA({sessionId:o}),a=(0,A4.resolve)(e.runtimeConfig?.workingDirectory??process.cwd()),l=Jzo(K0({env:e.env,projectConfigPath:e.projectConfigPath,workingDirectory:a,workspaceIdentity:e.runtimeConfig?.memory?.workspaceIdentity,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,cliOverrides:Gzo(e)}),e),u=e.loggerFactory??rB({env:e.env}),f=u.createLogger("zcode").child({...Qa(s),module:"bootstrap"}),g=new DK(f,{...Qa(s),module:"bootstrap",startupKind:"zcode_app"},t);cHo({hasInjectedModelAdapter:e.modelAdapter!==void 0,resume:e.resume===!0,startupTimer:g}),lHo({configResult:l,startupTimer:g});let _=u.createLogger("zcode").child({...Qa(s),module:"adapters.model"}),b=Bzo({owner:e.telemetryOwner,sessionId:o}),w,T,I;try{let E=zg(l.config.storage.dir),R=k8(E),L=Zzo(R,OCe(e.env??process.env)==="development"),U=await XVo({logger:f,storageRoot:E,workingDirectory:a}),B=U.profiles,z=Wkt({cliStorageRoot:R,configResult:l,env:e.env,logger:f,options:e,startupTimer:g,workingDirectory:a}),$=ekt({cliStorageRoot:R,logger:f}),J=QVo({logger:f,plugins:z.plugins,reservedProfileNames:B.map(kn=>kn.name),modelSelectionOverrides:U.pluginAgentModelSelectionOverrides}).profiles,q=s$o(z),ie=MVo({pluginOutcome:z,workingDirectory:a}),ae=[...B,...J],Ce=e.sessionStore===void 0,pe=e.sessionStore??await n7o(l,g),ze=Qzo(pe),rt=Sbe(a),Pe=e.runtimeConfig?.mode?void 0:e7o(ze,rt),{configuredMcpServers:Tt,runtimeConfig:Ye,untrustedProjectMcpServers:Fe}=T$o({cliStorageRoot:R,configResult:l,options:e,persistedMode:Pe,pluginHooks:z.hooks,pluginMcpServers:z.mcpServers,builtInMcpServers:ie,pluginRuntimeFeatures:q,builtInSubagentModelSelectionOverrides:U.builtInModelSelectionOverrides,subagentOutputRootDir:(0,A4.join)(R,"agents"),subagentProfiles:ae,storageRoot:E,workingDirectory:a,workspaceIdentity:e.runtimeConfig?.memory?.workspaceIdentity}),St=e.browserControlPort;St&&q.browserUse===!0&&Ye.mcp?.servers?.node_repl?.type==="stdio"&&(w=e.nodeReplBrowserBroker??(T=Nkt({browserControlPort:St,logger:f,platform:e.platform})),Tt=zAn(Tt,w),Ye.mcp={...Ye.mcp,servers:zAn(Ye.mcp.servers??{},w)}),g.mark("ZCode runtime configuration resolved",{context:I$o(Ye,a),event:"bootstrap.app.startup.runtime_config.completed",stage:"resolve_runtime_config"});let kt=Uye(z.plugins);Ye.pluginReferenceCatalog=kt;let st,$e=K$o({appVersion:n,logger:f,projectConfigPath:e.projectConfigPath,policy:e.workspaceHookPolicy,policyProvider:e.workspaceHookPolicyProvider,reviewHost:e.workspaceHookReviewHost,workspaceHookTrustEnabled:e.workspaceHookTrustEnabled,runtimeRoot:l.sources.project.workspaceHookRuntimeRoot??{enabled:Ye.hooks?.enabled===!0,timeoutMs:Ye.hooks?.timeoutMs??6e4,maxOutputBytes:Ye.hooks?.maxOutputBytes??32768},sessionId:o,snapshot:l.sources.project.workspaceHookSnapshot,userConfigPath:l.sources.user.path,workingDirectory:a,...e.workspaceHookReviewHost?{emitReviewEvent:r(async kn=>{if(!st)throw new Error("ZCode runtime is not initialized yet.");await st.appendEvent(om(kn.type,o,kn.payload,{traceId:s.traceId}),s)},"emitReviewEvent"),emitAdmissionEvent:r(async kn=>{if(!st)throw new Error("ZCode runtime is not initialized yet.");await st.appendEvent(om(kn.type,o,kn.payload,{traceId:s.traceId}),s)},"emitAdmissionEvent")}:{}}),jt=new UM({allowedTools:new Set(l.config.permission.allowedTools),autoApproveHighRisk:l.config.permission.autoApproveHighRisk,disallowedTools:new Set(l.config.permission.disallowedTools),allowMediumRiskInAutoMode:l.config.permission.allowMediumRiskInAuto}),Je=e.inputHistoryStore??Xzo(pe),Xe=e.artifactStore??yxr({imageCacheRootDir:(0,A4.join)(E,"cli","image-cache"),pdfCacheRootDir:(0,A4.join)(E,"cli","pdf-cache"),rootDir:(0,A4.join)(E,"cli","artifacts"),videoCacheRootDir:(0,A4.join)(E,"cli","video-cache")}),_t=e.imageProcessorPort??y3r(),Dt=Hzo(e.env??process.env),gn=e.sessionMailboxPort??(Dt?F2o({rootDir:zg((e.env??process.env).ZCODE_MAILBOX_ROOT??"~/.zcode/mailbox")}):void 0);uHo({cliStorageRoot:R,hasInjectedArtifactStore:e.artifactStore!==void 0,hasInjectedSessionStore:e.sessionStore!==void 0,startupTimer:g,storageRoot:E});let cn=e.mcpPort??(Ye.mcp?.enabled===!1?void 0:e.mcpPortFactory?.({workingDirectory:a})??Amn({clientVersion:n,env:e.env,logger:f,network:{httpProxy:l.config.network.httpProxy,noProxy:l.config.network.noProxy,caCertFile:l.config.network.caCertFile},workingDirectory:a})),Fn=e.mcpPort===void 0&&cn!==void 0,on=e.executionPort??sne({onToolExecResource:e.onToolExecResource,network:{httpProxy:l.config.network.httpProxy,noProxy:l.config.network.noProxy,caCertFile:l.config.network.caCertFile},outputRootDir:(0,A4.join)(E,"cli","exec"),processEnv:e.env??process.env}),dt=e.executionPort===void 0,we=e.pdfDocumentPort??S3r({executionPort:on}),_e=e.fileSystemPort??hH(),Pt=e.httpClientPort??C3({env:e.env??process.env,timeoutMs:l.config.network.timeout,proxyUrl:l.config.network.httpProxy,noProxy:l.config.network.noProxy,caCertFile:l.config.network.caCertFile}),ut=e.providerEndpointRoutingPort;dHo({configuredMcpServers:Tt,hasInjectedMcpPort:e.mcpPort!==void 0,mcpEnabled:Ye.mcp?.enabled!==!1,startupTimer:g,trustedMcpServerCount:Object.keys(Ye.mcp?.servers??{}).length}),mHo({configResult:l,logger:f,runtimeConfig:Ye});let Mn=r(()=>{if(!st)throw new Error("ZCode runtime is not initialized yet.");return st},"getRuntime"),Dr=!1,gr=r(()=>Qte({env:e.env??process.env,platform:e.platform??process.platform}).selection,"resolveDefaultShellSelection"),eo,to=r(()=>(eo??=(async()=>await e.resolveInitialBashShellSelection?.()??gr())(),eo),"resolveInitialShellSelection"),oo=r(async()=>{Mn().initializeSessionShellEnvironmentIfNeeded(await to())},"initializeSessionShellEnvironment"),ro=r(async()=>{let kn=e.providerRegistry,Nn;try{Nn=await t7o(pe,o)}catch(Vo){f.warn("Session model selection restore failed",{error:Vo instanceof Error?Vo.message:String(Vo),event:"session.model_selection.restore_failed",sessionId:o})}let Ur=Nn&&kn.validateSelection(Nn);Mn().$zRestoredSessionModel={selection:Nn,registry:kn};return Mn().setSessionModelSelection(Ur?.ok?Nn:void 0),Nn},"restorePersistedModelSelection"),Ji=r(async kn=>{let Nn=Mn(),Ur=kn?.onEvent?Nn.subscribeEvents({onSessionEvent:kn.onEvent}):void 0;try{let Vo=kn?.traceContext??s,qe=await ro();await oo();let Kt=await Nn.resumeFromStore({...kn?.abortSignal?{abortSignal:kn.abortSignal}:{},modeOverride:e.runtimeConfig?.mode,persistedMessages:kn?.persistedMessages,traceContext:Vo});return await Nn.activatePausedTargetAfterResume(Vo),Dr=!0,{...Kt,modelSelection:qe}}finally{Ur?.()}},"resumeFromStore"),pi=r(async(kn,Nn)=>{!e.resume||Dr||(await Ji({...Nn?{abortSignal:Nn}:{},traceContext:kn??s}),Dr=!0)},"prepareResume"),Wi=r(async kn=>{await oo(),await pi(kn?.traceContext,kn?.abortSignal)},"prepareUserExecutionBoundary"),Ii=oHo(e.env,{appVersion:n,endpointRoutingPort:ut,network:l.config.network,sourceTitle:e.sourceTitle}),Rs=e.modelAdapter??Ewt({env:e.env,logger:_,modelIoDir:L,modelIoFullRetentionEnabled:e.modelIoFullRetentionEnabled,executionConfig:Ii,statusSink:b.statusSink,streamIdleTimeoutMs:l.config.modelStream.idleTimeoutMs});e.modelAdapter&&b.statusSink&&Rs.addStatusSink(b.statusSink);let ht=zqo();Rs.setModelIoFullRetentionEnabled(e.modelIoFullRetentionEnabled??!1),I=new qkt({registry:e.providerRegistry,modelAdapter:Rs}),I.start();let mr=I.modelFactory,mi=F9o({agentTelemetry:b.agentExecution,appOptions:e,appVersion:n,artifactStore:Xe,configResult:l,fileSystemPort:_e,httpClientPort:Pt,imageProcessorPort:_t,pdfDocumentPort:we,logger:f,mcpPort:cn,modelFactory:mr,permissionService:jt,prepareUserExecutionBoundary:Wi,getRuntime:Mn,runtimeConfig:Ye,sessionId:o,sessionStore:pe,storageRoot:E,traceContext:s,workingDirectory:a}),Ar=qje(pe,f),hi=Ar===void 0?void 0:mVo({concurrency:ht,createActorRuntime:r(({persona:kn,pinnedModel:Nn,runSubagentModel:Ur,sessionId:Vo,submitPort:qe,submitProfile:Kt,escalatePort:Jt,modelRequestAdmission:en})=>lkt({childSessionId:Vo,configOverrides:{workflowActor:{...kn.name===void 0?{}:{name:kn.name},...kn.system===void 0?{}:{persona:kn.system}},...IVo(),...xVo({parentSelection:Mn().getSessionModelSelection(),...Ur===void 0?{}:{runSelection:Ur}},Nn).configOverrides},deps:{agentTelemetry:b.agentExecution,appOptions:e,appVersion:n,artifactStore:Xe,configResult:l,fileSystemPort:_e,httpClientPort:Pt,imageProcessorPort:_t,logger:f,mcpPort:cn,modelFactory:mr,permissionService:jt,runtime:Mn(),runtimeConfig:Ye,sessionId:o,sessionStore:pe,storageRoot:E,workingDirectory:a},request:{opts:{}},traceContext:s,...Kt.kind==="untyped"?{}:{workflowSubmitPort:qe},...Kt.kind==="mono"?{workflowSubmitSchema:{...Kt.schema}}:{},workflowEscalatePort:Jt,...en===void 0?{}:{modelRequestAdmission:en}}),"createActorRuntime"),actorTranscriptStore:pe,artifactStore:Xe,executionPort:on,fileSystemPort:_e,journal:Ar,logger:f,onRunEvent:wVo({getRuntime:Mn,logger:f,sessionId:o}),parentSessionId:o,registerResidencyBlockingWork:r(kn=>{Mn().trackResidencyBlockingWork(kn)},"registerResidencyBlockingWork"),resolveLaunchInputId:r(kn=>{let Nn=Mn().getActiveTurnInfo();return Nn!==void 0&&Nn.turnId===kn.turnId?Nn.inputId:void 0},"resolveLaunchInputId"),...sAn(pe)?{taskLinkStore:pe}:{}}),Js=yVo({executionPort:on,fileSystemPort:_e,logger:f}),qa=bVo({registry:e.providerRegistry,currentSelection:r(()=>Mn().getSessionModelSelection(),"currentSelection")});st=new V2(o,Ye,{agentTelemetry:b.agentExecution,modelRequestAdmission:ht.observer(),eventStore:e.eventStore??zz(),sessionStore:pe,sessionMailboxPort:gn,logger:f,executionPort:on,workspaceHookAdmission:$e?.admission,workspaceHookSnapshot:$e?.snapshot,browserControlPort:St,fileSystemPort:_e,httpClientPort:Pt,imageProcessorPort:_t,pdfDocumentPort:we,artifactStore:Xe,contextSourcePort:e.contextSourcePort??bme({env:e.env}),skillPort:l.config.features.skill&&l.config.skills.enabled?e.skillPort??mG({extraRoots:l.config.skills.roots,extraResolvedRoots:[...z.skillRoots,...$],disabledPaths:[...x8(l.config.skillOverrides),...Ye.dynamicWorkflowEnabled===!1?M$o($):[]]}):void 0,mcpPort:cn,eventSink:e.eventSink,modelFactory:mr,modelIoDir:L,providerRuntimeHeadersPort:e.providerRuntimeHeadersPort,resolveEffectiveModelSelection:e.resolveEffectiveModelSelection,isRemoteWorkspace:r(()=>YJt(Ye.memory?.workspaceIdentity??""),"isRemoteWorkspace"),permissionBroker:e.permissionBroker,permissionService:jt,workflowPort:mi.workflowPort,dynamicWorkflowRunPort:hi,dynamicWorkflowSnippetPort:Js,modelCatalogPort:qa,automationPort:e.automationPort,offPeakPort:e.offPeakPort,appVersion:n,traceContext:s}),pHo({hasInjectedModelAdapter:e.modelAdapter!==void 0,sessionId:o,startupTimer:g}),fHo({sessionId:o,startupTimer:g,workingDirectory:a}),Rwt(u,f);let li=d7o({artifactStore:Xe,customCommandPromptResolver:r(async(kn,Nn)=>{let Ur=ZVo(kn,{dynamicWorkflowEnabled:Ye.dynamicWorkflowEnabled,workingDirectory:a});return Ur!==void 0?Ur:await HVo(kn,{env:e.env,executionPort:on,logger:f,projectConfigPath:e.projectConfigPath,sessionId:o,signal:Nn?.abortSignal,skipUserConfig:e.skipUserConfig,traceContext:Nn?.traceContext??s,userConfigPath:e.userConfigPath,workingDirectory:a})},"customCommandPromptResolver"),inputHistoryStore:Je,logger:f,prepareUserExecutionBoundary:Wi,runtime:st,sessionId:o,traceContext:s}),oa=i7o({agentTelemetry:b.agentExecution,appOptions:e,appVersion:n,artifactStore:Xe,cliStorageRoot:R,configResult:l,eventSink:e.eventSink,imageProcessorPort:_t,pdfDocumentPort:we,logger:f,mcpPort:cn,modelFactory:mr,permissionService:jt,prepareUserExecutionBoundary:Wi,runtime:st,runtimeConfig:Ye,sessionId:o,sessionStore:pe,storageRoot:E,traceContext:s,workingDirectory:a}),Fs=S$o({...hi===void 0?{}:{closeDynamicWorkflowRuns:r(()=>hi.close(),"closeDynamicWorkflowRuns")},configResult:l,configuredMcpServers:Tt,...e.configuredDefaultModelSelection?{configuredDefaultModelSelection:e.configuredDefaultModelSelection}:{},executionPort:on,localSettingStore:ze,logger:f,loggerFactory:u,mcpPort:cn,ownsExecutionPort:dt,ownsMcpPort:Fn,closeNodeReplBrowserBroker:r(async()=>{await T?.close()},"closeNodeReplBrowserBroker"),ownsSessionStore:Ce,prepareUserExecutionBoundary:Wi,prepareResume:pi,projectID:rt,providerRegistry:e.providerRegistry,resolveUiLocale:r(kn=>xEn(kn,e),"resolveUiLocale"),runtime:st,sessionId:o,sessionStore:pe,traceContext:s,untrustedProjectMcpServers:Fe,workingDirectory:a}),Qo=Fs.close,gi=r(async kn=>{let Nn=kn.ref,Ur=kn.mime,Vo;if(kn.messageId&&kn.attachmentIndex!==void 0){let Kt=(await pe.messageWithParts({sessionID:o,messageID:kn.messageId}))?.parts.filter(Jt=>Jt.type==="file")[kn.attachmentIndex];Kt?.type==="file"&&(Ur=Kt.mime,Vo=Kt.metadata?.artifactUri??(Kt.url.startsWith("zcode-artifact://")?Kt.url:void 0),Nn=Vo??(Kt.url.startsWith("data:")?kn.ref:Kt.url))}return{ref:Nn,mediaType:Ur,...Vo?{artifactUri:Vo}:{}}},"resolvePromptAttachment");return{sessionId:o,traceId:s.traceId,runtime:st,respondWorkspaceHookReview:r(kn=>$e?.respond({sessionId:kn.sessionId,taskId:kn.taskId,runId:kn.runId,...kn.remoteSessionId?{remoteSessionId:kn.remoteSessionId}:{},workspaceIdentity:kn.workspaceIdentity,bundleDigest:kn.bundleDigest,reviewFlowId:kn.reviewFlowId,generation:kn.generation,interactionId:kn.interactionId},kn.decision)??Promise.resolve({accepted:!1,reasonCode:"workspace_hooks_require_trust_capable_host"}),"respondWorkspaceHookReview"),toggleWorkspaceHookReviewItem:r(kn=>$e?.toggle({sessionId:kn.sessionId,taskId:kn.taskId,runId:kn.runId,...kn.remoteSessionId?{remoteSessionId:kn.remoteSessionId}:{},workspaceIdentity:kn.workspaceIdentity,bundleDigest:kn.bundleDigest,reviewFlowId:kn.reviewFlowId,generation:kn.generation,interactionId:kn.interactionId},kn.reviewItemId,kn.enabled)??Promise.resolve({accepted:!1,reasonCode:"workspace_hooks_require_trust_capable_host"}),"toggleWorkspaceHookReviewItem"),revokeWorkspaceHookTrust:r(kn=>("hookDeclarationDigests"in kn?$e?.revokeCurrent(kn):$e?.revoke({sessionId:kn.sessionId,taskId:kn.taskId,runId:kn.runId,...kn.remoteSessionId?{remoteSessionId:kn.remoteSessionId}:{},workspaceIdentity:kn.workspaceIdentity,bundleDigest:kn.bundleDigest,reviewFlowId:kn.reviewFlowId,generation:kn.generation,interactionId:kn.interactionId},kn.reviewItemIds))??Promise.resolve({accepted:!1,reasonCode:"workspace_hooks_require_trust_capable_host"}),"revokeWorkspaceHookTrust"),requestWorkspaceHookReview:r(kn=>$e?.requestReview({workspaceIdentity:kn.workspaceIdentity,bundleDigest:kn.bundleDigest})??Promise.resolve({accepted:!1,reasonCode:"workspace_hooks_require_trust_capable_host"}),"requestWorkspaceHookReview"),reloadWorkspaceHookTrust:r(()=>$e?.reloadTrust()??Promise.resolve(),"reloadWorkspaceHookTrust"),setModelIoFullRetentionEnabled:r(kn=>Rs.setModelIoFullRetentionEnabled(kn),"setModelIoFullRetentionEnabled"),readToolResultArtifact:r(kn=>Xe.readToolResultArtifact({uri:kn,trace:s}),"readToolResultArtifact"),writePromptAttachment:r(async kn=>{let Nn=await Xe.writeToolResultArtifact({content:`data:${kn.mime};base64,${Buffer.from(kn.bytes).toString("base64")}`,contentType:"text/plain",retention:"session",sessionId:o,toolCallId:`prompt-attachment-upload-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,toolName:"prompt-attachment:upload",trace:s});return(kn.mime.startsWith("image/")||kn.mime.startsWith("video/")||kn.mime.split(";",1)[0]?.trim().toLowerCase()==="application/pdf")&&Xe.primeMediaAttachmentPath?.({bytes:kn.bytes,mediaType:kn.mime,uri:Nn.uri}).catch(()=>{}),{ref:Nn.uri}},"writePromptAttachment"),readPromptAttachment:r(async kn=>{let{ref:Nn,mediaType:Ur}=await gi(kn);if(Nn.startsWith("zcode-artifact://")){let qe=await Xe.readToolResultArtifact({uri:Nn,trace:s});return EHa(qe.content,Ur,kn.maxBytes)}return{bytes:(await _e.readBinaryFile({path:Nn,maxBytes:kn.maxBytes,trace:s})).content,mediaType:Ur}},"readPromptAttachment"),statPromptAttachment:r(async kn=>{let{ref:Nn,mediaType:Ur,artifactUri:Vo}=await gi(kn);if(Vo){if(!Xe.statToolResultArtifact)throw new m1(nC.statUnsupported);let Kt=await Xe.statToolResultArtifact({uri:Vo,trace:s});return{totalBytes:Kt.bytes,mediaType:Kt.contentType||Ur,...Kt.mtimeMs===void 0?{}:{mtimeMs:Kt.mtimeMs}}}let qe=await _e.stat({path:Nn,trace:s});if(qe.kind!=="file")throw new m1(nC.statNotFile);return{totalBytes:qe.sizeBytes,mediaType:Ur,...qe.mtimeMs===void 0?{}:{mtimeMs:qe.mtimeMs}}},"statPromptAttachment"),resolvePromptAttachmentPreviewSource:r(async kn=>{let Nn=await gi(kn);if(!Nn.mediaType.startsWith("video/"))return{kind:"chunked"};if(Nn.artifactUri){if(!Xe.ensureMediaAttachmentPath)return{kind:"chunked"};try{let Ur=await Xe.ensureMediaAttachmentPath({uri:Nn.artifactUri,mediaType:Nn.mediaType});if(Ur.status==="ready"&&Ur.path.trim())return{kind:"local_path",path:Ur.path,mediaType:Nn.mediaType}}catch{}return{kind:"chunked"}}return(0,A4.isAbsolute)(Nn.ref)?{kind:"local_path",path:Nn.ref,mediaType:Nn.mediaType}:{kind:"chunked"}},"resolvePromptAttachmentPreviewSource"),...Fs,close:r(async()=>{try{await Qo?.()}finally{try{I?.dispose()}finally{await b.shutdown()}}},"close"),...oa,...mi,...hi===void 0?{}:{listDynamicWorkflowRunEvents:r(async kn=>hi.listEvents(kn.runId,{...kn.afterSequence===void 0?{}:{afterSequence:kn.afterSequence},...kn.limit===void 0?{}:{limit:kn.limit}}),"listDynamicWorkflowRunEvents")},...hi===void 0||typeof hi.listArtifacts!="function"||typeof hi.listArtifactItems!="function"||typeof hi.readArtifact!="function"?{}:{listDynamicWorkflowRunArtifacts:r(async kn=>hi.listArtifacts(kn.runId),"listDynamicWorkflowRunArtifacts"),listDynamicWorkflowRunArtifactItems:r(async kn=>hi.listArtifactItems(kn.runId,kn.artifactId,{...kn.afterSequence===void 0?{}:{afterSequence:kn.afterSequence},limit:kn.limit}),"listDynamicWorkflowRunArtifactItems"),readDynamicWorkflowRunArtifact:r(async kn=>hi.readArtifact(kn.runId,kn.artifactId,kn.version),"readDynamicWorkflowRunArtifact")},...hi===void 0||typeof hi.listWorkspaceNodes!="function"||typeof hi.readWorkspaceNodeResult!="function"?{}:{listDynamicWorkflowRunWorkspaceNodes:r(async kn=>hi.listWorkspaceNodes(kn.runId),"listDynamicWorkflowRunWorkspaceNodes"),readDynamicWorkflowRunNodeResult:r(async kn=>hi.readWorkspaceNodeResult(kn.runId,kn.siteId,kn.ordinal,{maxBytes:kn.maxBytes}),"readDynamicWorkflowRunNodeResult")},...hi===void 0?{}:{},...hi===void 0||typeof hi.listRunsForSession!="function"?{}:{listDynamicWorkflowRuns:r(async kn=>hi.listRunsForSession(kn.limit),"listDynamicWorkflowRuns")},...hi===void 0||typeof hi.replayProgressForSession!="function"?{}:{replayDynamicWorkflowRuns:r(async kn=>hi.replayProgressForSession(kn),"replayDynamicWorkflowRuns")},...hi===void 0||typeof hi.resume!="function"?{}:{resumeWorkflowRun:r(async kn=>{let Nn=await hi.resume(kn.workId);return Nn.ok&&await Mn().trackResumedDynamicWorkflowRun({runId:Nn.runId,...Nn.toolCallId===void 0?{}:{toolCallId:Nn.toolCallId},...kn.name===void 0?{}:{name:kn.name},traceContext:s}),Nn},"resumeWorkflowRun")},...hi===void 0?{}:{startSavedWorkflow:r(async kn=>(await Wi({traceContext:s}),await Mn().startSavedWorkflowRun({...kn,traceContext:s})),"startSavedWorkflow")},...hi===void 0||typeof hi.amend!="function"||typeof hi.getScript!="function"?{}:{amendWorkflowRunSettings:r(async kn=>(await Wi({traceContext:s}),await Mn().amendWorkflowRunSettings({...kn,traceContext:s})),"amendWorkflowRunSettings")},...r$o({configResult:l,options:e,workingDirectory:a}),getPluginReferenceCatalog:r(()=>kt,"getPluginReferenceCatalog"),getSkillCatalog:r(async()=>(await Wi({traceContext:s}),await Mn().getSkillCatalog(s)),"getSkillCatalog"),resume:Ji,...li}}catch(E){throw I?.dispose(),b.shutdown().catch(()=>{}),T?.close(),g.fail("ZCode app startup failed",E,{context:{sessionId:o,workingDirectory:a},event:"bootstrap.app.startup.failed",stage:"total"}),E}}var A4,ZAn=Y(()=>{"use strict";A4=require("node:path");f3();W0e();vw();Eme();yme();a7();Msn();Fsn();j2o();xRe();K0e();sdt();Y0();Cwt();nr();ms();g0();wEn();Pwt();kEn();Kzo();l9();wbe();s7o();p7o();o$o();a$o();w$o();C$o();Mje();N$o();Z$o();j9o();BAn();SAn();vVo();SVo();kVo();QEn();TVo();CVo();$An();NVo();GVo();YVo();kbe();tHo();sHo();aHo();JAn();r(EHa,"decodePromptAttachmentDataUrl");r(KAn,"createZCodeApp")});function QAn(e){let t=DHa.parse(e),n=t.model,o=Hkt(typeof n=="string"?n:n?.main),s=typeof n=="object"?Hkt(n?.lite):void 0,a=o||s?{...o?{main:o}:{},...s?{lite:s}:{}}:void 0;return{...a?{model:a}:{},...t.provider?{provider:t.provider}:{}}}function Hkt(e){if(!e)return;let t=e.indexOf("/");if(t<=0||t===e.length-1)return;let n=e.slice(0,t).trim(),o=e.slice(t+1).trim();if(!(!n||!o))return{provider:n,model:o}}var XAn,hHo,Vkt,AHa,PHa,RHa,YAn,DHa,gHo=Y(()=>{"use strict";Fa();XAn=m.record(m.string(),m.string()),hHo=m.record(m.string(),m.unknown()),Vkt=m.number().finite().positive(),AHa=m.object({enabled:m.boolean().optional(),levels:m.array(m.string().min(1)).optional(),defaultLevel:m.string().min(1).optional(),providerOptionsByLevel:m.record(m.string(),hHo).optional()}),PHa=m.object({id:m.string().min(1).optional(),name:m.string().min(1).optional(),attachment:m.boolean().optional(),reasoning:m.union([m.boolean(),AHa]).optional(),tool_call:m.boolean().optional(),structured_output:m.boolean().optional(),supportsImages:m.boolean().optional(),supportsPdf:m.boolean().optional(),supportsVideo:m.boolean().optional(),supportsToolCall:m.boolean().optional(),supportsJsonSchemaOutput:m.boolean().optional(),contextWindow:Vkt.optional(),maxOutputTokens:Vkt.optional(),limit:m.object({context:Vkt.optional(),output:Vkt.optional()}).optional(),modalities:m.object({input:m.array(m.enum(["text","audio","image","video","pdf"])).optional(),output:m.array(m.enum(["text","audio","image","video","pdf"])).optional()}).optional(),options:hHo.optional(),headers:XAn.optional()}).passthrough(),RHa=m.object({kind:m.enum(["anthropic","openai","openai-compatible"]),name:m.string().min(1).optional(),npm:m.never().optional(),options:m.object({apiKey:m.string().optional(),baseURL:m.string().min(1).optional(),apiKeyRequired:m.boolean().optional(),headers:XAn.optional()}).passthrough().optional(),headers:XAn.optional(),models:m.record(m.string(),PHa).optional()}).passthrough(),YAn=m.string().refine(e=>Hkt(e)!==void 0,{message:"Model references must use provider/model format"}),DHa=m.object({provider:m.record(m.string(),RHa).optional(),model:m.union([YAn,m.object({main:YAn.optional(),lite:YAn.optional()}).strict().refine(e=>e.main!==void 0||e.lite!==void 0)]).optional(),small_model:m.never().optional()}).passthrough();r(QAn,"parseLegacyCliModelConfig");r(Hkt,"parseModelTarget")});function MHa(e){switch(e){case"anthropic":return"anthropic-messages";case"openai":return"openai-responses";case"openai-compatible":case void 0:return"openai-chat-completions"}return"openai-chat-completions"}function NHa(e){let t=QAn(e.input),n=uw.empty(),o=dA.empty();for(let[a,l]of Object.entries(t.provider??{})){let u=a.trim();if(!u)continue;let f=u==="builtin:bigmodel"?aee.bigmodel:u==="builtin:zai"?aee.zai:void 0;if(f){let w=l.options?.apiKey?.trim();w&&(n=n.setRule({providerId:f,templateId:f,config:new Tk({group:"standard-personal",access:new xz({apiKey:w})})}));continue}if(u.startsWith("builtin:")||u.startsWith("account:")||l.source!==void 0&&l.source!=="custom")continue;if(BHa(l))throw new Gkt(u);let g=FHa(l),_=g.map(w=>w.modelId),b=l.name?.trim();n=n.setRule({providerId:u,providerName:b&&b!==u?b:void 0,config:new Tk({group:"standard-personal",access:new xz({apiKey:l.options?.apiKey}),api:new _pe({type:MHa(l.kind),baseUrl:l.options?.baseURL,headers:jHa(l.headers,l.options?.headers)}),..._.length>0?{personalModelIds:_,modelOrder:_}:{}})});for(let w of g)w.contextWindow!==void 0&&(o=o.setExact(u,w.modelId,new uA({properties:new lAe({contextWindow:w.contextWindow})})))}let s=LHa(e.input)??void 0;return Object.freeze({providers:n,models:o,defaultModelSelection:s})}async function Jkt(e){let t=e.filePath??U7();try{let n=JSON.parse(await(0,_Ho.readFile)(t,"utf8"));return NHa({input:n})}catch(n){if(UHa(n)||n instanceof Gkt)return null;throw n}}function LHa(e){let t=QAn(e).model?.main;return!t||t.provider===OHa?null:Object.freeze({providerId:t.provider,modelId:t.model})}function FHa(e){let t=new Set,n=[];for(let[o,s]of Object.entries(e.models??{})){if(s.deleted===!0)continue;let a=(s.id??o).trim();if(!a||t.has(a))continue;t.add(a);let l=s.contextWindow??s.limit?.context;n.push({modelId:a,...zHa(l)?{contextWindow:l}:{}})}return n}function jHa(...e){let t=Object.assign({},...e.filter(Boolean));return Object.keys(t).length>0?t:void 0}function BHa(e){return e.options?.apiKeyRequired===!1}function UHa(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function zHa(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0}var _Ho,OHa,Gkt,ePn=Y(()=>{"use strict";_Ho=require("node:fs/promises");ms();vw();gHo();pA();OHa="builtin:zapi",Gkt=class extends Error{static{r(this,"UnsupportedLegacyCliProviderConfigError")}providerId;constructor(t){super(`\u65E7 CLI Provider ${t} \u542B\u6709\u6B63\u5F0F Config \u5C1A\u4E0D\u80FD\u8868\u8FBE\u7684\u6267\u884C\u5B57\u6BB5`),this.name="UnsupportedLegacyCliProviderConfigError",this.providerId=t}};r(MHa,"resolveLegacyProviderApiType");r(NHa,"importLegacyCliPersonalProviderConfig");r(Jkt,"readLegacyCliPersonalProviderConfig");r(LHa,"importLegacyCliConfiguredDefault");r(FHa,"collectLegacyCliModelMembers");r(jHa,"mergeHeaders");r(BHa,"requiresUnsupportedNoAuthentication");r(UHa,"isFileNotFound");r(zHa,"isPositiveInteger")});async function tPn(e){return(await nPn(e)).providers}async function nPn(e,t){if(t)return{zcodeBuiltinRevision:t.revision,providers:t.providers.entries().flatMap(([s,a])=>{let l=a.access,u=a.builtinModelIds?.find(f=>f.trim())?.trim();return l?.type==="zhipu-account"&&l.mode==="individual-coding-plan"&&l.accountType&&u?[{family:l.accountType,modelId:u,providerId:s}]:[]})};let n=e[LV]?.trim();if(!n)throw new Error(`${LV} is required for login`);let o=new UO({bundledFilePath:n,watch:!1});try{let s=await o.read();return nPn(e,s)}finally{o.dispose()}}async function vHo(e,t){let n=(await tPn(t)).filter(o=>o.family===e);if(n.length!==1)throw new Error(`ZCode Built-in Config \u5FC5\u987B\u4E3A ${e} \u58F0\u660E\u552F\u4E00 Individual Coding Plan Provider`);return n[0]}function Yie(e){let t=e.trim();if(!t)throw new Error("Standalone Account Provider ID \u4E0D\u80FD\u4E3A\u7A7A");return`account-provider:${t}:identity`}function t3e(e){let t=e.providerId.trim(),n=e.accountIdentity.trim();if(!t)throw new Error("Standalone Account Provider ID \u4E0D\u80FD\u4E3A\u7A7A");if(!n)throw new Error("Standalone Account Identity \u4E0D\u80FD\u4E3A\u7A7A");return`account-provider:coding-plan:${t}:account:${encodeURIComponent(n)}:api-key`}function rPn(e){let t=e.trim();if(!t)throw new Error("Standalone Account Secret \u4E0D\u80FD\u4E3A\u7A7A");return`key-${(0,yHo.createHash)("sha256").update(t).digest("hex").slice(0,24)}`}async function oPn(e,t,n){let o=await nPn(t,n),s=o.providers,a=s.map(({providerId:b})=>Yie(b)),l=await e.loadMany(a),u=s.flatMap(({family:b,providerId:w})=>{let T=l[Yie(w)]?.trim();if(!T)return[];let I=t3e({providerId:w,accountIdentity:T});return[{accountIdentity:T,credentialKey:I,family:b,providerId:w}]}),f=await e.loadMany(u.map(({credentialKey:b})=>b)),g=new Map(u.map(b=>[b.providerId,b])),_=new uw(s.map(({family:b,providerId:w})=>{let T=g.get(w),I=T?f[T.credentialKey]?.trim():void 0;return!T||!I?[w,new Tk({access:new zj({entitled:!1})})]:[w,new Tk({access:new zj({entitled:!0})})]}));return pAe(o.zcodeBuiltinRevision,_)}async function bHo(e,t){return(await oPn(e,t)).providers.entries().some(([,n])=>n.access?.type==="zhipu-account"?n.access.entitled===!0:!1)}function SHo(e,t){return{shouldRefreshBeforeModelRequest(){return!0},async refreshBeforeModelRequest(n){n.abortSignal?.throwIfAborted();let o=n.providerId.trim(),s=n.accountAccess;if(!s||s.mode!=="individual-coding-plan")throw new Error(`Standalone Account Provider \u8BF7\u6C42\u8EAB\u4EFD\u65E0\u6548: ${o}`);let a=(await e.load(Yie(o)))?.trim();if(!a)throw new Error(`Standalone Account Provider \u51ED\u636E\u5DF2\u7ECF\u5931\u6548: ${o}`);let l=(await e.load(t3e({providerId:o,accountIdentity:a})))?.trim();if(!l)throw new Error(`Standalone Account Provider \u7F3A\u5C11\u8BF7\u6C42\u51ED\u636E: ${o}`);return{headersApplied:!0,requestAuth:{apiKey:l}}}}}var yHo,iPn=Y(()=>{"use strict";yHo=require("node:crypto");pA();hfe();r(tPn,"readStandaloneCodingPlanProviders");r(nPn,"readStandaloneCodingPlanCatalog");r(vHo,"resolveStandaloneCodingPlanProvider");r(Yie,"standaloneAccountIdentityCredentialKey");r(t3e,"standaloneAccountProviderCredentialKey");r(rPn,"createStandaloneAccountIdentityFromSecret");r(oPn,"readStandaloneAccountProviderConfigSnapshot");r(bHo,"hasStandaloneCodingPlanAccess");r(SHo,"createStandaloneProviderRuntimeHeadersPort")});function UK(e){if(e?.aborted)throw sPn(e)}async function wHo(e,t,n){if(!n){await e(t);return}await Promise.race([e(t),xHo(n)])}async function kHo(e){let t;try{return await Promise.race([e.callbackServer.waitForCallback(),new Promise((n,o)=>{t=setTimeout(()=>o(e.createTimeoutError()),e.timeoutMs)}),xHo(e.signal)])}finally{t&&clearTimeout(t)}}function xHo(e){return e?new Promise((t,n)=>{if(e.aborted){n(sPn(e));return}e.addEventListener("abort",()=>n(sPn(e)),{once:!0})}):new Promise(()=>{})}function sPn(e){return e.reason??new Error("Login cancelled.")}var THo=Y(()=>{"use strict";r(UK,"throwIfAborted");r(wHo,"sleepWithAbort");r(kHo,"waitForCallbackWithAbort");r(xHo,"rejectOnAbort");r(sPn,"abortReason")});async function WHa(e={}){let t=e.credentialStore??jM({env:e.env});return bHo(t,e.env??process.env)}async function VHa(e={}){if((e.env??process.env).ZCODE_CLI_OAUTH_CALLBACK_STDIN==="1"){let $zEnv=e.env??process.env;UK(e.abortSignal);let $zStore=e.credentialStore??jM({env:$zEnv}),$zHttp=e.httpClient??CHo($zEnv),$zPayload;try{$zPayload=JSON.parse(require("node:fs").readFileSync(0,"utf8"))}catch($zError){throw new m9("invalid_callback","Unable to read the Z.AI OAuth callback.",{cause:$zError})}if(!$zPayload||typeof $zPayload.callbackUrl!=="string"||typeof $zPayload.state!=="string")throw new m9("invalid_callback","The Z.AI OAuth callback payload is invalid.");let $zUrl;try{$zUrl=new URL($zPayload.callbackUrl)}catch($zError){throw new m9("invalid_callback","The Z.AI OAuth callback URL is invalid.",{cause:$zError})}if($zUrl.protocol!=="zcode:"||$zUrl.hostname!=="zai-auth"||$zUrl.pathname.replace(/\/+$/u,"")!=="/callback")throw new m9("invalid_callback","The Z.AI OAuth callback target is invalid.");let $zCode=$zUrl.searchParams.get("code")??$zUrl.searchParams.get("authCode"),$zState=$zUrl.searchParams.get("state");if(!$zCode||!$zState||$zState!==$zPayload.state)throw new m9("invalid_callback","The Z.AI OAuth callback state is invalid or expired.");let $zResponse=await $zHttp.request({maxResponseBytes:65536,body:new TextEncoder().encode(JSON.stringify({provider:"zai",code:$zCode,redirect_uri:"zcode://zai-auth/callback",state:$zState})),headers:{"Content-Type":"application/json"},method:"POST",trace:e.trace,url:"https://zcode.z.ai/api/v1/oauth/token"},e.abortSignal),$zText=new TextDecoder().decode($zResponse.body),$zEnvelope;try{$zEnvelope=JSON.parse($zText)}catch($zError){throw new m9("token_exchange_failed",$zResponse.status<200||$zResponse.status>=300?"OAuth HTTP error "+$zResponse.status+" (empty or non-JSON response)":"OAuth response is not valid JSON",{cause:$zError})}let $zMessage=typeof $zEnvelope?.msg==="string"&&$zEnvelope.msg.trim()?$zEnvelope.msg.trim():void 0;if($zResponse.status<200||$zResponse.status>=300)throw new m9("token_exchange_failed",$zMessage??"OAuth HTTP error "+$zResponse.status);if($zEnvelope?.code!==0)throw new m9("token_exchange_failed",$zMessage??"Z.AI token exchange failed.");let $zData=$zEnvelope.data,$zAccessToken=$zData?.zai?.access_token,$zJwtToken=$zData?.token,$zUser=$zData?.user;if(typeof $zAccessToken!=="string"||typeof $zJwtToken!=="string"||!$zUser||typeof $zUser!=="object")throw new m9("token_exchange_failed","Z.AI token response is missing credentials or user data.");UK(e.abortSignal);try{await $zStore.saveZaiLoginCredentials({accessToken:$zAccessToken,jwtToken:$zJwtToken,user:$zUser})}catch($zError){throw new m9("credential_write_failed","Login succeeded but writing credentials failed.",{cause:$zError})}let $zApiKey=await EHo({accessToken:$zAccessToken,env:$zEnv,httpClient:$zHttp,family:"zai",resolver:e.apiKeyResolver}),$zConfig;try{$zConfig=await aPn({accountIdentity:$zUser.user_id,apiKey:$zApiKey,credentialStore:$zStore,env:$zEnv,personalProviderConfigPath:e.personalProviderConfigPath,providerId:"zai"})}catch($zError){throw new m9("config_update_failed","Login succeeded but updating ZCode config failed.",{cause:$zError})}return{configPath:$zConfig.path,credentialsPath:$zStore.filePath,model:$zConfig.mainModel,providerId:"zai",user:$zUser}}let t=e.env??process.env,n=e.now??Date.now,o=e.sleep??XHa;UK(e.abortSignal);let s=e.pollToken??HZr(),a=e.credentialStore??jM({env:t}),l=KHa(e,t),u=await l.init({pollToken:s});await e.onAuthorizeUrl?.(u),UK(e.abortSignal);let f=e.noBrowser?void 0:await(e.openBrowser??Ydn)(u.authorize_url);f&&await e.onBrowserOpen?.(f);let g=await YHa({abortSignal:e.abortSignal,initData:u,now:n,oauthClient:l,onPollStatus:e.onPollStatus,pollToken:s,sleep:o,timeoutMs:e.timeoutMs??IHo});UK(e.abortSignal);try{await a.saveZaiLoginCredentials({accessToken:g.zai.access_token,jwtToken:g.token,user:g.user})}catch(w){throw new m9("credential_write_failed","Login succeeded but writing credentials failed.",{cause:w})}let _=await EHo({accessToken:g.zai.access_token,env:t,httpClient:e.httpClient,family:"zai",resolver:e.apiKeyResolver}),b;try{b=await aPn({accountIdentity:g.user.user_id,apiKey:_,credentialStore:a,env:t,personalProviderConfigPath:e.personalProviderConfigPath,providerId:"zai"})}catch(w){throw new m9("config_update_failed","Login succeeded but updating ZCode config failed.",{cause:w})}return{...f?{browser:f}:{},configPath:b.path,credentialsPath:a.filePath,model:b.mainModel,providerId:"zai",user:g.user}}async function HHa(e={}){let t=e.env??process.env;if(t.ZCODE_CLI_BIGMODEL_REUSE_SESSION!=="0"){UK(e.abortSignal);let $bStore=e.credentialStore??jM({env:t}),$bToken,$bApiKey;try{$bToken=(await $bStore.load(R1.bigmodelAccessToken))?.trim()}catch{}if($bToken)try{$bApiKey=await EHo({accessToken:$bToken,env:t,httpClient:e.httpClient??CHo(t),family:"bigmodel",resolver:e.apiKeyResolver})}catch{}if($bApiKey){UK(e.abortSignal);let $bConfig=await aPn({accountIdentity:rPn($bApiKey),apiKey:$bApiKey,credentialStore:$bStore,env:t,personalProviderConfigPath:e.personalProviderConfigPath,providerId:"bigmodel"});return{configPath:$bConfig.path,model:$bConfig.mainModel,providerId:"bigmodel"}}}UK(e.abortSignal);let n=e.httpClient??CHo(t),o=e.state??MZr(),s=e.callbackServer??await YOe({callbackPath:qHa,state:o}),a=OZr({httpClient:n}),l=a.buildAuthorizeUrl({redirectUri:s.callbackUrl,state:o});await e.onAuthorizeUrl?.({authorize_url:l,callback_url:s.callbackUrl,state:o}),UK(e.abortSignal);let u=e.noBrowser?void 0:await(e.openBrowser??Ydn)(l);u&&await e.onBrowserOpen?.(u),UK(e.abortSignal);try{let f=await kHo({callbackServer:s,createTimeoutError:r(()=>new m9("auth_timeout","Authorization timed out. Please retry login."),"createTimeoutError"),signal:e.abortSignal,timeoutMs:e.timeoutMs??IHo}),g=await require(require("node:path").join(__dirname,"cli-config.cjs")).exchangeBigmodelOAuthCode({code:f.code,redirectUri:s.callbackUrl,state:o,httpClient:n,abortSignal:e.abortSignal,trace:e.trace}),_=await EHo({accessToken:g.accessToken,env:t,httpClient:n,family:"bigmodel",resolver:e.apiKeyResolver}),b=e.credentialStore??jM({env:t}),w=rPn(_);await b.saveMany({[R1.activeProvider]:"bigmodel",[R1.bigmodelAccessToken]:g.accessToken,[R1.zcodeJwtToken]:g.zcodeJwtToken,...g.refreshToken?{[R1.bigmodelRefreshToken]:g.refreshToken}:{},[R1.bigmodelUserInfo]:JSON.stringify({id:w})});let T=await aPn({accountIdentity:w,apiKey:_,credentialStore:b,env:t,personalProviderConfigPath:e.personalProviderConfigPath,providerId:"bigmodel"});return{...u?{browser:u}:{},configPath:T.path,model:T.mainModel,providerId:"bigmodel"}}finally{await s.close()}}async function GHa(e){let t=e.apiKey.trim();if(!t)throw new m9("config_update_failed","API key must not be empty.");let n=e.credentialStore??jM({env:e.env}),o=await aPn({accountIdentity:rPn(t),apiKey:t,credentialStore:n,env:e.env??process.env,personalProviderConfigPath:e.personalProviderConfigPath,providerId:e.providerId});return{configPath:o.path,model:o.mainModel,providerId:e.providerId}}async function JHa(e={}){let t=e.credentialStore??jM({env:e.env}),n=(await tPn(e.env??process.env)).map(({providerId:f})=>f),o=n.map(Yie),s=await t.loadMany(o),a=n.flatMap(f=>{let g=s[Yie(f)]?.trim();return g?[t3e({providerId:f,accountIdentity:g})]:[]}),l=[...Object.values(R1),...o,...a],u=await t.loadMany(l);return await t.deleteIfValues(Object.fromEntries(Object.entries(u).flatMap(([f,g])=>g===null?[]:[[f,g]]))),{credentialsPath:t.filePath}}async function aPn(e){let t=await vHo(e.providerId,e.env),n=t.providerId,o=t.modelId,s=t3e({providerId:n,accountIdentity:e.accountIdentity});await e.credentialStore.saveMany({[Yie(n)]:e.accountIdentity,[s]:e.apiKey});let a=e.personalProviderConfigPath??e.env[tte]?.trim()??(0,Kkt.join)((0,Kkt.dirname)(e.credentialStore.filePath),MXe),l=new Cpe({filePath:a,importLegacy:r(()=>Jkt({}),"importLegacy"),pollingIntervalMs:!1}),u=new Tpe({personalRepository:l});try{await u.saveConfiguredDefault({providerId:n,modelId:o})}finally{u.dispose(),l.dispose()}return{mainModel:`${n}/${o}`,path:a}}function KHa(e,t){let n=e.baseUrl??Bee(ZHa(t)).apiBaseUrl;if(e.httpClient)return Xdn({baseUrl:n,httpClient:e.httpClient});let o=K0({env:t});return Xdn({baseUrl:n,httpClient:s2e({env:t,proxyUrl:o.config.network.httpProxy,noProxy:o.config.network.noProxy,caCertFile:o.config.network.caCertFile,timeoutMs:o.config.network.timeout})})}function ZHa(e){return p1(e)}function CHo(e){let t=K0({env:e});return s2e({env:e,proxyUrl:t.config.network.httpProxy,noProxy:t.config.network.noProxy,caCertFile:t.config.network.caCertFile,timeoutMs:t.config.network.timeout})}async function EHo(e){return(e.resolver??$Zr({httpClient:e.httpClient??CHo(e.env)})).resolve({accessToken:e.accessToken,family:e.family})}async function YHa(e){let t=e.initData.expires_at*1e3,n=Math.min(e.now()+e.timeoutMs,t),o=Math.max($Ha,e.initData.poll_interval_sec*1e3);for(;e.now()<n;){UK(e.abortSignal);let s=await e.oauthClient.poll({flowId:e.initData.flow_id,pollToken:e.pollToken});if(await e.onPollStatus?.(s),s.status==="ready")return s;if(s.status==="failed")throw new m9("auth_failed","Authorization failed. Please retry login.");await wHo(e.sleep,Math.min(o,Math.max(0,n-e.now())),e.abortSignal)}throw new m9("auth_timeout","Authorization timed out. Please retry login.")}function XHa(e){return new Promise(t=>setTimeout(t,e))}var Kkt,IHo,$Ha,qHa,m9,AHo=Y(()=>{"use strict";adt();vw();a7();ms();hfe();ePn();Kkt=require("node:path");iPn();THo();IHo=300*1e3,$Ha=1e3,qHa="/oauth/callback/bigmodel";r(WHa,"hasConfiguredStandaloneCodingPlan");m9=class extends Error{static{r(this,"ZCodeCliLoginError")}code;constructor(t,n,o={}){super(n,o),this.name="ZCodeCliLoginError",this.code=t}};r(VHa,"loginZCodeCli");r(HHa,"loginBigmodelCodingPlan");r(GHa,"configureCodingPlanApiKey");r(JHa,"logoutZCodeCli");r(aPn,"persistStandaloneCodingPlanConnection");r(KHa,"createOAuthClient");r(ZHa,"resolveCliZCodeEndpointOrigin");r(CHo,"createDefaultHttpClient");r(EHo,"resolveCodingPlanApiKey");r(YHa,"pollUntilReady");r(XHa,"sleepMs")});async function OHo(e={}){let t=e.env??process.env,n=await rGa(nGa(t));return _Kt({appVersion:t[Ape]??e.appVersion,arch:(0,Bbe.arch)(),clientLanguage:eGa(),clientTimezone:tGa(),deviceMid:n,endpointOrigin:p1(t),osVersion:(0,Bbe.release)(),platform:process.platform,releaseChannel:YL(t),sourceTitle:e.sourceTitle??"cli"})}function eGa(){return Intl.DateTimeFormat().resolvedOptions().locale}function tGa(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function nGa(e){let t=e[QHa]?.trim()||(0,Bbe.homedir)();return(0,DHo.join)(t,".zcode","v2","telemetry-state.json")}async function rGa(e){let t=PHo.get(e);if(t)return t;try{let n=JSON.parse(await(0,RHo.readFile)(e,"utf8"));if(typeof n.deviceMid!="string")return;let o=n.deviceMid.trim();return!o||!/^[\x20-\x7e]+$/.test(o)?void 0:(PHo.set(e,o),o)}catch{return}}var RHo,Bbe,DHo,QHa,PHo,MHo=Y(()=>{"use strict";RHo=require("node:fs/promises"),Bbe=require("node:os"),DHo=require("node:path");ms();QHa="ZCODE_DATA_BASE_DIR",PHo=new Map;r(OHo,"createProviderEndpointRoutingSourceHeaders");r(eGa,"resolveClientLanguage");r(tGa,"resolveClientTimezone");r(nGa,"resolveTelemetryStateFile");r(rGa,"readExistingDeviceMid")});function n3e(e){let t=e.env??process.env,n=YAe(t,oGa),o=iGa(n,e.network),s=NHo.get(o);if(s)return s;let a=new dat({appVersion:e.appVersion,configUrl:n,httpClient:s2e({caCertFile:e.network.caCertFile,env:t,noProxy:e.network.noProxy,proxyUrl:e.network.httpProxy}),logger:e.logger.child({module:"adapters.model.provider_endpoint_routing"}),sourceHeaders:r(()=>OHo({appVersion:e.appVersion,env:t,sourceTitle:e.sourceTitle}),"sourceHeaders")});return NHo.set(o,a),a}function LHo(e){let t=e.env??process.env,n=K0({env:t,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:e.workingDirectory}),s=(e.loggerFactory??rB({env:t})).createLogger("zcode").child({module:"bootstrap.provider_endpoint_routing"});return n3e({appVersion:e.appVersion,env:t,logger:s,network:n.config.network,sourceTitle:e.sourceTitle})}function iGa(e,t){return JSON.stringify({caCertFile:t.caCertFile,configUrl:e,httpProxy:t.httpProxy,noProxy:t.noProxy})}var oGa,NHo,cPn=Y(()=>{"use strict";vw();a7();fOe();W0e();ms();MHo();oGa="/api/v1/agent/configs",NHo=new Map;r(n3e,"resolveProcessProviderEndpointRoutingPort");r(LHo,"createDefaultProviderEndpointRoutingPort");r(iGa,"routingRegistryKey")});async function Ykt(e,t={}){let n=ymr(e);if(!n)throw new Error("\u7F3A\u5C11\u8FDB\u7A0B Provider Registry \u7684 ZCode Built-in / Personal Config \u8DEF\u5F84");let o=new yee,s=t.standalone?t.standalone.credentialStore??jM({env:{...e}}):void 0,a,l=t.standalone?e[OXe]?.trim():void 0,u=new pZe({...n,...l?{zcodeBuiltinFilePath:l,zcodeBuiltinActiveFilePath:n.zcodeBuiltinFilePath,zcodeBuiltinRemote:{controlFilePath:(0,Zkt.join)((0,Zkt.dirname)(n.zcodeBuiltinFilePath),"zcode-builtin-refresh.json"),resolveEndpointKey:r(()=>p1(e),"resolveEndpointKey"),fetchRelease:r((_,b)=>xnr({endpointOrigin:_,signal:b,appVersion:HL,platform:aZe(),request:t.standalone?.request??globalThis.fetch}),"fetchRelease"),onRefreshResult:t.standalone?.onBuiltinRefreshResult}}:{},onZCodeBuiltinRefreshError:t.standalone?.onBuiltinRefreshError,accountSource:o,...s?{createAccountSource(_){return a=new GKe({configSource:_,async resolve({configRevision:b,configuredProviders:w}){let T=await oPn(s,e,{revision:b,providers:w});return{providers:T.providers,states:T.states??{}}}}),a.onDidRefreshError(({error:b})=>{try{t.standalone?.onAccountInitializationError?.(b)}catch{}}),a}}:{},...t.standalone?{importLegacy:r(()=>Jkt({...t.standalone?.legacyCliUserConfigFilePath?{filePath:t.standalone.legacyCliUserConfigFilePath}:{}}),"importLegacy")}:{}}),f=a?u.onDidCheckZCodeBuiltin(async()=>{let[_,b]=await Promise.all([u.configService.read(),a.read()]);_.zcodeBuiltinRevision!==b.basedOnZCodeBuiltinRevision&&await a.refresh("builtin-account-recovery")}):void 0,g=s?.onDidChange?.(async()=>{await a.refresh("standalone-credentials-changed"),await u.registryService.refresh("standalone-credentials-barrier")});try{await u.start();let _=u.registryService.getSnapshot(),b=new Tpe({personalRepository:u.personalRepository});try{let w=await b.read();return Object.freeze({accountSource:a??o,async syncAccountProviderConfig(T){if(a)throw new Error("Standalone Account \u7531\u672C\u8FDB\u7A0B\u7BA1\u7406\uFF0C\u4E0D\u63A5\u6536 Host \u8986\u76D6");let I=o.replace(T,"host-account-config");return await u.registryService.refresh("host-account-config"),I},dispose(){g?.(),f?.(),a?.dispose(),b.dispose(),u.dispose()},...s?{providerRuntimeHeadersPort:SHo(s,e)}:{},runtime:u,snapshot:_,modelSelectionConfigRepository:b,configuredDefaultModelSelection:w})}catch(w){throw g?.(),b.dispose(),w}}catch(_){throw g?.(),f?.(),a?.dispose(),u.dispose(),_}}function FHo(e){let t=e.revision.trim();if(!t)throw new Error("Account Config revision \u4E0D\u80FD\u4E3A\u7A7A");let n=e.basedOnZCodeBuiltinRevision.trim();if(!n)throw new Error("Account Config Built-in revision \u4E0D\u80FD\u4E3A\u7A7A");let o=Qtr(e.providers);for(let[s,a]of o.entries())if(cee(s)&&a.access?.type==="zhipu-account"&&a.access.entitled&&typeof e.states?.[s]?.current!="boolean")throw new Error(`Account State \u7F3A\u5C11 current: ${s}`);return Object.freeze({revision:t,basedOnZCodeBuiltinRevision:n,providers:o,...e.states?{states:e.states}:{}})}var Zkt,Xkt=Y(()=>{"use strict";pA();ms();Zkt=require("node:path");hfe();rpn();ePn();iPn();r(Ykt,"startProcessProviderRegistryRuntime");r(FHo,"parseProcessAccountProviderConfigSnapshot")});async function lPn(e){let t=(0,Ube.randomUUID)(),n=(0,Ube.createHash)("sha256").update(e.dbPath).digest("hex"),o=0,s=!1,a=r(async l=>{let u=vYe.parse({schemaVersion:1,attemptId:t,databaseId:n,databaseKind:"session",sequence:++o,...l});s||=u.phase==="failed",e.onProgress?.(u),await new Promise((f,g)=>{e.output.write(`${JSON.stringify({method:BR.storageStartup,params:u})}
|
|
15250
15250
|
`,_=>_?g(_):f())})},"report");try{return await a({phase:"checking",elapsedMs:0}),await fH.openStartup({dbPath:e.dbPath},{onProgress:a})}catch(l){if(!s)try{await a({phase:"failed",elapsedMs:0,errorCode:SAe(l),...Ppe(l)})}catch{}throw l}}async function jHo(e){let{createInterface:t}=await import("node:readline"),{zcodeStoragePathReadySchema:n,classifyDatabaseStartupError:o}=await Promise.resolve().then(()=>(ms(),umr)),s=t({input:e.input}),a,l=new Promise((_,b)=>{a=setTimeout(()=>b(Object.assign(new Error("Storage observation handshake timed out"),{kind:"startup_status_timeout"})),3e4),s.once("line",w=>{try{if(w.length>1024)throw new Error("Invalid storage acknowledgement");let T=n.parse(JSON.parse(w));_(T.reuse??!1)}catch(T){b(T)}}),s.once("close",()=>b(Object.assign(new Error("Storage preparation input closed"),{kind:"transport_closed"})))});l.catch(()=>{});let u,f,g=r(_=>new Promise((b,w)=>{e.output.write(`${JSON.stringify(_)}
|
|
15251
15251
|
`,T=>T?w(T):b())}),"write");try{await g({method:"startup/storagePath",params:{path:e.dbPath}});let _=await l;clearTimeout(a),s.close(),_||(u=await lPn(e),u.close(),u=void 0),await g({method:"startup/storagePrepared",params:{}})}catch(_){f=_;try{await g({method:"startup/storageState",params:{schemaVersion:1,attemptId:(0,Ube.randomUUID)(),databaseId:(0,Ube.createHash)("sha256").update(e.dbPath).digest("hex"),databaseKind:"session",sequence:1,phase:"failed",elapsedMs:0,errorCode:o(_),...Ppe(_)}})}catch{}throw _}finally{clearTimeout(a),s.close();try{u?.close()}catch(_){if(!f)throw _}}}var Ube,BHo=Y(()=>{"use strict";Ube=require("node:crypto");f3();ms();r(lPn,"openProtocolStartupStorage");r(jHo,"prepareProtocolStartupStorage")});function UHo(e){globalThis.AI_SDK_LOG_WARNINGS=t=>{try{let n=Array.isArray(t.warnings)?t.warnings:[];e.warn("AI SDK model warning",{event:"model.sdk.warning",module:"bootstrap.zcode_protocol",status:"completed",model:Xie(t.model),provider:Xie(t.provider),warningCount:n.length,warnings:n.map(sGa)})}catch{}}}function sGa(e){if(!e||typeof e!="object")return{value:Xie(e)};let t=e;return{type:Xie(t.type),feature:Xie(t.feature),message:Xie(t.message),details:Xie(t.details)}}function Xie(e){return typeof e=="string"?e:void 0}var zHo=Y(()=>{"use strict";r(UHo,"installZCodeProtocolAiSdkWarningLogger");r(sGa,"summarizeWarning");r(Xie,"stringValue")});function qHo(e){return{async resolveHeaders(t){let n=e.resolveContext(),o=e.resolveWorkspace({...t.workspaceIdentity?{workspaceIdentity:t.workspaceIdentity}:{},...t.workspacePath?{workspacePath:t.workspacePath}:{}});if(!n||!o)return{ok:!1,reason:"official_auth_unavailable"};$Ho+=1;try{return await n.requestClient(va.interactionRequestOfficialMcpAuthHeaders,{mcpKey:t.mcpKey,pluginId:t.pluginId,requestId:`official-mcp-auth:${$Ho}`,targetOrigin:t.targetOrigin,workspace:o},OGt,t.signal?{signal:t.signal}:{})}catch{return{ok:!1,reason:"official_auth_unavailable"}}}}}var $Ho,WHo=Y(()=>{"use strict";ms();$Ho=0;r(qHo,"createOfficialMcpAuthHeadersPort")});function VHo(e){return"method"in e&&"id"in e}function HHo(e){return"method"in e&&!("id"in e)}function GHo(e){return"id"in e&&"result"in e}function JHo(e){return"id"in e&&"error"in e}function aGa(e){let t=e?.issues;if(!Array.isArray(t)||t.length===0)return;let n=t.slice(0,5).map(s=>`${Array.isArray(s.path)&&s.path.length>0?s.path.join("."):"(root)"}: ${s.message??"invalid"}`),o=t.length>5?` (+${t.length-5} more)`:"";return n.join("; ")+o}function yl(e,t){try{return e.parse(t)}catch(n){let o=aGa(n);throw new sf(-32602,o?`Invalid params \u2014 ${o}`:"Invalid params",n)}}function zK(e,t){if(t!==void 0&&t!==e.stateRevision)throw new sf(-32009,"Session state revision mismatch",{actualRevision:e.stateRevision,expectedRevision:t})}function KHo(e){if(e instanceof sf)return{code:e.code,data:e.data,message:e.message};if(e instanceof Error){let t="code"in e&&typeof e.code=="string"?e.code:void 0;return{code:-32603,data:{name:e.name,stack:e.stack,...t?{code:t}:{}},message:e.message}}return{code:-32603,message:String(e)}}function cGa(e){return FV()}function ZHo(e,t){let n=vA({sessionId:e,traceId:t?.traceId??cGa(e)});return t?.spanId&&(n.spanId=t.spanId),t?.parentId&&(n.parentId=t.parentId,n.parentSpanId=t.parentId),n}function r3e(e){return{traceId:e.traceId,...e.spanId?{spanId:e.spanId}:{},...e.parentId??e.parentSpanId?{parentId:e.parentId??e.parentSpanId}:{}}}function Xy(e,t,n={}){let o=e.sessions.get(t);if(!o)throw e.logger?.warn("ZCode Protocol session runtime missing",{activeSessionCount:e.sessions.size,event:"zcode_protocol.session.require_missing",hasSessionStore:!!e.deps.sessionStore,module:"bootstrap.zcode_protocol",operation:n.operation??"unknown",...n.deliveryKind?{deliveryKind:n.deliveryKind}:{},sessionId:t}),new sf($ee.sessionUnavailable,`Session is not active: ${t}`);return o}function Qkt(e){return e.loggerFactory?.createLogger("zcode").child({module:"bootstrap.zcode_protocol"})}var sf,Nw=Y(()=>{"use strict";nr();ms();sf=class extends Error{static{r(this,"ProtocolRequestError")}code;data;constructor(t,n,o){super(n),this.code=t,this.data=o,this.name="ProtocolRequestError"}};r(VHo,"isRequest");r(HHo,"isNotification");r(GHo,"isResponse");r(JHo,"isErrorResponse");r(aGa,"summarizeParamsError");r(yl,"parseParams");r(zK,"assertExpectedRevision");r(KHo,"toProtocolError");r(cGa,"createProtocolTraceId");r(ZHo,"createProtocolRootTraceContext");r(r3e,"protocolTraceFromTraceContext");r(Xy,"requireSession");r(Qkt,"createProtocolLogger")});function eGo(e){return{sessionId:e,rounds:[],networkEntries:[],cache:null}}function XHo(e,t){return e.has(t)?!1:(e.add(t),e.size>ete.dedupe&&e.delete(e.values().next().value),!0)}function QHo(e){return Object.fromEntries(Object.entries(e).slice(0,lGa).map(([t,n])=>[t.slice(0,YHo),n.slice(0,YHo)]))}function $K(e){return e!==void 0&&Number.isFinite(e)&&e>=0?e:void 0}function tGo(e,t){if(t.type!==lt.ModelNetworkStatus||String(t.sessionId)!==e.app.sessionId)return;let n=t.payload,o=tKt({taskId:e.app.sessionId,traceId:t.traceId,eventId:String(t.id),payload:{...n,model:{providerId:n.providerId,modelId:n.modelId}}});if(!o)return;let s=uPn.get(e);if(s||(s={snapshot:eGo(e.app.sessionId),seenEvents:new Set,completedRequests:new Set,hasUnknownCacheUsage:!1},uPn.set(e,s)),!XHo(s.seenEvents,String(t.id)))return;let{type:a,taskId:l,eventId:u,inputId:f,...g}=o,_=Date.parse(n.timestamp),b=Number.isFinite(_)?_:t.timestamp.getTime(),w=s.snapshot;if(w.networkEntries=[...w.networkEntries,{...g,recordedAt:b,maxAttempts:n.maxAttempts,requestHeaders:QHo(g.requestHeaders),responseHeaders:QHo(g.responseHeaders),...g.message?{message:g.message.slice(0,uGa)}:{}}].slice(-ete.network),n.type!=="model_request_completed"||n.querySource!=="main_turn"||!XHo(s.completedRequests,n.requestId))return;let T=n.usage,I=$K(T?.inputTokens),E=$K(T?.outputTokens),R=$K(T?.cacheReadTokens),L=$K(n.durationMs),U=$K(n.timeToFirstContentMs),B=L!==void 0&&U!==void 0&&L>U?L-U:null;s.hasUnknownCacheUsage||=I===void 0||R===void 0;let z=w.cache,$=(z?.totalInputTokens??0)+(I??0),J=(z?.totalCacheReadTokens??0)+(R??0),q=(z?.hitRateRequestCount??0)+1;w.cache={hitRateRequestCount:q,totalInputTokens:$,totalCacheReadTokens:J,hitRate:!s.hasUnknownCacheUsage&&$>0?J/$:null},w.rounds=[...w.rounds,{eventKey:String(t.id),requestId:n.requestId,requestIndex:q,recordedAt:b,usage:{inputTokens:I,outputTokens:E,totalTokens:$K(T?.totalTokens)??(I!==void 0&&E!==void 0?I+E:void 0),reasoningTokens:$K(T?.reasoningTokens),cachedInputTokens:R,cachedWriteInputTokens:$K(T?.cacheWriteTokens)},hitRate:I!==void 0&&I>0&&R!==void 0?R/I:null,generationDurationMs:B,tokensPerSecond:TZt(E,B)}].slice(-ete.rounds)}function dGa(e){return uPn.get(e)?.snapshot??eGo(e.app.sessionId)}function nGo(e,t){let n=xZt.parse(t);return dGa(Xy(e,n.sessionId))}var uPn,lGa,YHo,uGa,dPn=Y(()=>{"use strict";nr();ms();Nw();uPn=new WeakMap,lGa=32,YHo=512,uGa=2048;r(eGo,"emptySnapshot");r(XHo,"remember");r(QHo,"boundedHeaders");r($K,"token");r(tGo,"observeSessionDebug");r(dGa,"readSessionDebug");r(nGo,"querySessionDebug")});function i3e(e){return pGa.has(e??"interactive")}var o3e,pGa,pPn=Y(()=>{"use strict";o3e=["interactive","fork","workflow_parent"],pGa=new Set(o3e);r(i3e,"isTaskListSessionType")});function mGa(e){return fGa.test(e)}function hGa(e){return{filename:e.fileName,mimeType:e.mime,sizeBytes:e.bytes}}function rGo(e){return e.mime.split(";",1)[0]?.trim().toLowerCase().startsWith("image/")??!1}function oGo(e){return e.mime.split(";",1)[0]?.trim().toLowerCase().startsWith("video/")??!1}function iGo(e){return e.mime.split(";",1)[0]?.trim().toLowerCase()==="application/pdf"}function gGa(e){if(!e.startsWith("data:"))return e;let t=e.indexOf(",");if(t===-1)return;let n=e.slice(0,t),o=e.slice(t+1);if(!n.includes(";base64"))return decodeURIComponent(o);try{return Buffer.from(o,"base64").toString("utf8")}catch{return}}async function _Ga(e,t){let n=hGa(t);if(!mGa(t.ref))return oGo(t)?{path:t.ref,type:"video",...n}:{path:t.ref,type:rGo(t)?"image":iGo(t)?"pdf":"file",...n};if(rGo(t))return{content:t.ref,path:t.fileName,type:"image",...n};if(oGo(t))return{content:t.ref,path:t.fileName,type:"video",...n};if(iGo(t))return{content:t.ref,path:t.fileName,type:"pdf",...n};if(t.bytes>65536)return{type:"file",...n};try{let o=await e.readToolResultArtifact(t.ref),s=gGa(o.content);return s!==void 0?{content:s,path:t.fileName,type:"file",...n}:{type:"file",...n}}catch{return{type:"file",...n}}}async function h9(e,t){if(!t||t.length===0)return;let n=await Promise.all(t.map(o=>_Ga(e,o)));return n.length>0?n:void 0}var fGa,s3e=Y(()=>{"use strict";fGa=/^[a-zA-Z][a-zA-Z\d+.-]*:\/\//;r(mGa,"isUriAttachmentRef");r(hGa,"displayMetaOf");r(rGo,"isImageRef");r(oGo,"isVideoRef");r(iGo,"isPdfRef");r(gGa,"decodeDataUrlText");r(_Ga,"mapAttachmentRef");r(h9,"mapAttachmentRefsToTurnAttachments")});function yGa(e){e.residencyFinalizationCount=(e.residencyFinalizationCount??0)+1;let t=!1;return()=>{t||(t=!0,e.residencyFinalizationCount=Math.max(0,(e.residencyFinalizationCount??1)-1))}}function g9(e,t){let n=yGa(e);try{return t().finally(n)}catch(o){return n(),Promise.reject(o)}}async function vGa(e,t){let n=e.sessions.get(t);n&&(e.v4Gateway?.assertSessionRuntimeDeactivatable(t),n.unsubscribe?.(),e.v4Gateway?.deactivateSession(t),e.sessions.delete(t),await n.app.close?.(),await n.eventStore.deleteSession(t))}function aGo(e){return{deactivate:r(t=>vGa(e,t),"deactivate"),listSessionIds:r(()=>[...e.sessions.keys()],"listSessionIds"),readResidencyFacts:r(t=>{let n=e.sessions.get(t);return n?{hasPendingInteractions:e.v4Interactions.hasPendingForSession(t),hasQueuedCommands:e.v4Gateway?.hasResidencyBlockingCommands(t)??!1,hasLegacySubscriber:n.legacyStreamSubscribed===!0,hasResidencyBlockingWork:n.activeAbortController!==void 0||(n.residencyFinalizationCount??0)>0||n.app.runtime.hasResidencyBlockingWork(),hasSubscribers:e.v4Gateway?.hasConversationSubscribers(t)??!1,lastActivityAt:n.updatedAt,persisted:n.persistence==="immediate"}:null},"readResidencyFacts"),onDeactivated:r((t,n)=>{e.logger?.info("Session resident runtime deactivated",{...sGo(n),event:"zcode_protocol.session.resident_deactivated",sessionId:t})},"onDeactivated"),onError:r((t,n,o)=>{e.logger?.warn("Session resident deactivation failed",{...sGo(o),error:n instanceof Error?n.message:String(n),event:"zcode_protocol.session.resident_deactivation_failed",sessionId:t})},"onError")}}function sGo(e){return{highWaterCount:e.highWaterCount,idleMs:e.idleMs,idleTimeoutMs:e.idleTimeoutMs,reason:e.reason,residentCountBefore:e.residentCountBefore,targetCount:e.targetCount}}var a3e=Y(()=>{"use strict";r(yGa,"acquireSessionResidencyFinalization");r(g9,"runWithSessionResidencyFinalization");r(vGa,"deactivateSessionRecord");r(aGo,"createSessionResidentPoolHost");r(sGo,"deactivationLogContext")});async function D8(e,t,n){let o=n.modelExecution?.selectionScope==="execution";if(!o&&t.restoreWarning&&e.hasUsableRuntimeModelTarget?.(t)===!0&&(e.logger?.info?.("v4 restoreWarning cleared by model catalog recovery",{sessionId:t.app.sessionId,warningType:t.restoreWarning.type}),t.restoreWarning=void 0),!o&&t.restoreWarning)throw new txt("restoreWarning",t.restoreWarning.message);o||await e.ensureModelReady?.(t),t.persistence==="deferred"&&(t.persistence="immediate");let s=t.activeAutomationId,a=t.activeOffPeakTaskId,l=t.activeBotDeliveryTarget,u=SGa(n),f=wGa(n),g=bGa(n,u,f);u&&(t.activeAutomationId=u),f&&(t.activeOffPeakTaskId=f),t.activeBotDeliveryTarget=n.botDeliveryTarget;let _;try{_=await t.app.sendInput({text:n.content,...n.attachments?{attachments:n.attachments}:{}},{delivery:"start_turn",...n.intent?.requestedDelivery==="guide"?{queueDelivery:"guide"}:{},...n.browserAmbientContext?{browserAmbientContext:n.browserAmbientContext}:{},inputId:n.inputId,...n.inputPresentation?{inputPresentation:n.inputPresentation}:{},...fPn({automationId:u,offPeakTaskId:f,offPeakRunType:n.offPeakRunType}),intent:n.intent,...n.modelExecution?{modelExecution:n.modelExecution}:{},...n.sharedContextRefs?{sharedContextRefs:n.sharedContextRefs}:{},...g?{toolDisallowlist:g}:{},...n.requireIdle?{requireIdle:!0}:{},queryId:n.inputId})}catch(w){throw ext(t,s,a,l),await e.afterLegacyStateMutation?.(t,"prompt_failed"),w}if(_.kind==="rejected")throw ext(t,s,a,l),new txt("activePrompt",`Core prompt admission rejected: ${_.reason}`);if(_.kind==="queued")return ext(t,s,a,l),{admission:_,turnStarted:Promise.resolve()};let b=g9(t,async()=>{let w="prompt_completed";try{await _.completion}catch(T){w="prompt_failed",e.logger?.warn?.("v4 background turn failed",{error:T instanceof Error?T.message:String(T),inputId:n.inputId,sessionId:t.app.sessionId})}finally{ext(t,s,a,l),await e.afterLegacyStateMutation?.(t,w)}});return b.catch(()=>{}),e.logger?.info?.("v4 prompt admitted",{attachmentCount:n.attachments?.length??0,inputId:n.inputId,sessionId:t.app.sessionId,textLength:n.content.length}),{admission:_,completion:b,turnStarted:Promise.resolve()}}function ext(e,t,n,o){e.activeAutomationId=t,e.activeOffPeakTaskId=n,e.activeBotDeliveryTarget=o}function bGa(e,t=e.automationId,n=e.offPeakTaskId){let o=new Set(e.toolDisallowlist??[]);if(t)for(let s of kGa)o.add(s);if(n)for(let s of xGa)o.add(s);return o.size>0?[...o]:void 0}function SGa(e){let t=e.automationId?.trim();if(t)return t;let n=e.inputId.trim();if(!n.startsWith(cGo))return;let o=n.indexOf(":"),s=o>=0?n.slice(0,o):n;return s.length>cGo.length?s:void 0}function wGa(e){let t=e.offPeakTaskId?.trim();if(t)return t;let n=e.inputId.trim();if(!n.startsWith(lGo))return;let o=n.indexOf(":"),s=o>=0?n.slice(0,o):n;return s.length>lGo.length?s:void 0}function fPn(e){return e.automationId?{automationId:e.automationId}:e.offPeakTaskId?{offPeakTaskId:e.offPeakTaskId,...e.offPeakRunType?{offPeakRunType:e.offPeakRunType}:{}}:{}}var txt,cGo,kGa,lGo,xGa,zbe=Y(()=>{"use strict";a3e();txt=class extends Error{static{r(this,"V4PromptRejectedError")}reasonCode;turnStartUncertain=!1;constructor(t,n){super(n),this.reasonCode=t,this.name="V4PromptRejectedError"}};r(D8,"startPromptTurn");r(ext,"clearPromptRecordState");r(bGa,"buildTurnToolDisallowlist");r(SGa,"resolveTurnAutomationId");r(wGa,"resolveTurnOffPeakTaskId");r(fPn,"turnBackgroundAttributionOf");cGo="automation-",kGa=["CronCreate","CronUpdate","CronDelete"],lGo="offpeak-",xGa=["OffPeakCreate","SendMessage","Workflow"]});function Wp(e,t){if(t===null)throw new c3e("(null)");let n=e.getRecord(t);if(!n)throw new c3e(t);return n}var c3e,cN=Y(()=>{"use strict";c3e=class extends Error{static{r(this,"V4SessionNotFoundError")}constructor(t){super(`v4 command session not found: ${t}`),this.name="V4SessionNotFoundError"}};r(Wp,"requireRecord")});function nxt(e){let t=e.requestAuth?TGa(e.requestAuth):void 0;return{...e.memoryExtraction?{memoryExtraction:e.memoryExtraction}:{},selectionScope:"execution",...t?{requestDependencies:{requestAuth:{source:{resolve:r(async()=>t,"resolve")}}}}:{},...e.subagents?{subagents:e.subagents}:{}}}function TGa(e){return Object.freeze({...e.apiKey?{apiKey:e.apiKey}:{},...e.headers?{headers:Object.freeze({...e.headers})}:{}})}var mPn=Y(()=>{"use strict";r(nxt,"createModelExecutionContext");r(TGa,"freezeRequestAuth")});function uGo(e,t,n){if(e.turnId!==t.turnId||e.outputAt!==void 0||t.type!==lt.CompactStarted&&t.type!==lt.CompactCompleted&&t.type!==lt.CompactFailed)return!1;let o=t.payload,s=e.details??=[],a=`compact:${o.operationId}`,l=s.find(u=>u.id===a);if(!l&&t.type===lt.CompactStarted){if(s.length>=Ez)return e.truncated=!0,!0;l={id:a,stage:"compaction",start:n,source:"cli"},s.push(l)}if(l&&t.type!==lt.CompactStarted&&l.end===void 0){if(n<l.start)return e.clockInvalid=!0,!0;l.end=n,l.outcome=o.status==="interrupted"?"cancelled":t.type===lt.CompactCompleted?"completed":"failed"}return!0}var dGo=Y(()=>{"use strict";nr();ms();r(uGo,"observeLocalTtftCompaction")});var rxt,pGo=Y(()=>{"use strict";rxt=class{static{r(this,"LocalTtftClockWatch")}timer;constructor(t,n){let o=t(),s=Date.now();this.timer=setInterval(()=>{let a=t(),l=Date.now(),u=a-o,f=u>5e3||u<0||Math.abs(l-s-u)>100;o=a,s=l,n(f)},1e3),this.timer.unref()}dispose(){clearInterval(this.timer)}}});function mGo(e,t){let n=t,o=l3e(n.launchInputId);if(o===void 0)return null;let s=l3e(t.toolCallId);if(t.eventType===IGa){let a=l3e(n.actorSessionId),l=EGa(t.payload.actor);return a===void 0||l===void 0?null:rC.parse({...e,kind:"workflow.lifecycle",phase:"actor-spawned",sourceCommandId:o,runId:t.runId,...s===void 0?{}:{toolCallId:s},agentId:l,childSessionId:a})}if(t.eventType===CGa){let a=AGa(t.payload.status);if(a===void 0)return null;let l=a==="stopped"?PGa(t.payload.stopReason):void 0,u=l3e(DGa(t.payload.error)?.message),f=a==="completed"?void 0:u??(a==="stopped"?RGa(l):void 0);return rC.parse({...e,kind:"workflow.lifecycle",phase:"run-settled",sourceCommandId:o,runId:t.runId,...s===void 0?{}:{toolCallId:s},status:a,...l===void 0?{}:{stopReason:l},...f===void 0?{}:{errorMessage:f}})}return null}function EGa(e){if(typeof e!="object"||e===null)return;let t=e,n=l3e(t.siteId);if(!(n===void 0||typeof t.ordinal!="number"||!Number.isFinite(t.ordinal)))return`${n}@${t.ordinal}`}function AGa(e){return e==="completed"||e==="errored"||e==="stopped"?e:void 0}function PGa(e){return e==="user"||e==="model"||e==="provider"||e==="interrupted"||e==="superseded"?e:void 0}function RGa(e){return e===void 0?fGo:`${fGo} (${e})`}function DGa(e){return typeof e=="object"&&e!==null?e:void 0}function l3e(e){return typeof e=="string"&&e.length>0?e:void 0}var IGa,CGa,fGo,hGo=Y(()=>{"use strict";g0();IGa="actor-created",CGa="run-settled",fGo="Workflow run stopped";r(mGo,"workflowLifecycleFactFromProgress");r(EGa,"actorRefString");r(AGa,"settledStatus");r(PGa,"settledStopReason");r(RGa,"stoppedMessage");r(DGa,"errorRecord");r(l3e,"optionalString")});function Bd(e){return typeof e=="string"&&e.length>0?e:void 0}function Y2(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function oxt(e){if(e)try{return new URL(e).hostname||void 0}catch{return}}function X2(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function OGa(e,t){if(e!=="Skill")return{};let n=X2(t),o=Bd(n.qualifiedName),s=Bd(n.pluginId),a=Bd(n.source);return{...o?{skillQualifiedName:o}:{},...s?{skillPluginId:s}:{},...a?{skillSource:a}:{}}}function gPn(e){let t=X2(e._meta),n=X2(t.zcode),o=X2(t.claudeCode);return Bd(e.parentToolCallId)??Bd(e.parentToolUseId)??Bd(t.parentToolCallId)??Bd(t.parentToolUseId)??Bd(n.parentToolCallId)??Bd(n.parentToolUseId)??Bd(o.parentToolCallId)??Bd(o.parentToolUseId)}function gGo(e,t={}){let n=Bd(e.parentToolCallId)??Bd(t.parentToolCallId),o=Bd(e.childToolCallId)??Bd(t.childToolCallId),s=Bd(e.agentId)??Bd(t.agentId),a=Bd(e.agentType)??Bd(t.agentType),l=Bd(e.childSessionId)??Bd(t.childSessionId);return{...n?{parentToolCallId:n}:{},...o?{childToolCallId:o}:{},...s?{agentId:s}:{},...a?{agentType:a}:{},...l?{childSessionId:l}:{},...e.background===!0?{background:!0}:{}}}function MGa(e){let t=e.timestamp instanceof Date?e.timestamp.getTime():Number(e.timestamp);return Number.isFinite(t)&&t>=0?t:0}function NGa(e,t){if(!e||!t)return{};let n=NKt(e);return!n||n.automationId!==t?{automationId:t}:{automationId:t,taskTrigger:n.trigger,...n.scheduledAt!==void 0?{scheduledAt:n.scheduledAt}:{}}}function LGa(e){let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return}let n=X2(t);return Bd(X2(n.automation).automationId)}function FGa(e){return GV({totalTokens:Y2(e.totalTokens),inputTokens:Y2(e.inputTokens),outputTokens:Y2(e.outputTokens),cacheReadTokens:Y2(e.cacheReadTokens)??Y2(e.cacheTokens),cacheWriteTokens:Y2(e.cacheWriteTokens),reasoningTokens:Y2(e.reasoningTokens)})}function jGa(e){if(!e)return;let t=e.detail?.kind==="command"?e.detail.command:void 0,n=e.detail?.kind==="filesystem"||e.detail?.kind==="patch"?e.detail.filesystem:void 0,o=e.detail?.kind==="patch"?e.detail.patch:void 0,s={...e.totalMs!==void 0?{totalMs:e.totalMs}:{},...e.permissionWaitMs!==void 0?{permissionWaitMs:e.permissionWaitMs}:{},...t?.runMs!==void 0?{commandRunMs:t.runMs}:{},...t?.firstOutputMs!==void 0?{firstOutputMs:t.firstOutputMs}:{},...t?.noOutputMs!==void 0?{noOutputMs:t.noOutputMs}:{},...t?.exitCode!==void 0?{exitCode:t.exitCode}:{},...t?.timedOut!==void 0?{timedOut:t.timedOut}:{},...t?.outputBytes!==void 0?{outputBytes:t.outputBytes}:{},...t?.category!==void 0?{commandCategory:t.category}:{},...t?.name!==void 0?{commandName:t.name}:{},...t?.count!==void 0?{commandCount:t.count}:{},...t?.status!==void 0?{commandStatus:t.status}:{},...n?.readMs!==void 0?{fsReadMs:n.readMs}:{},...n?.writeMs!==void 0?{fsWriteMs:n.writeMs}:{},...n?.fileCount!==void 0?{fileCount:n.fileCount}:{},...n?.totalBytes!==void 0?{totalBytes:n.totalBytes}:{},...n?.maxFileBytes!==void 0?{maxFileBytes:n.maxFileBytes}:{},...n?.workspaceKind!==void 0?{workspaceKind:n.workspaceKind}:{},...o?.matchMs!==void 0?{patchMatchMs:o.matchMs}:{},...o?.hunkCount!==void 0?{hunkCount:o.hunkCount}:{},...o?.matchAttempts!==void 0?{matchAttempts:o.matchAttempts}:{}};return Object.keys(s).length>0?s:void 0}function BGa(e){return e==="success"?"success":e==="cancelled"?"interrupted":"failed"}function _Go(e,t){return`${e}\0${t??""}`}function vGo(e){return e===void 0||e==="main_turn"||e==="subagent"||e==="workflow_child"}function UGa(e){return vGo(e.querySource)&&(e.querySource!==void 0||e.stopReason!=="tool_internal")}function zGa(e){switch(e){case"completed":case"failed":case"interrupted":return e;default:return null}}var yGo,hPn,$be,qbe,_Pn=Y(()=>{"use strict";nr();ms();hGo();g0();yGo=2e3,hPn=class{static{r(this,"BoundedKeySet")}keys=new Set;add(t){if(this.keys.has(t))return!1;if(this.keys.add(t),this.keys.size>yGo){let n=this.keys.values().next().value;typeof n=="string"&&this.keys.delete(n)}return!0}deletePrefix(t){for(let n of this.keys)n.startsWith(t)&&this.keys.delete(n)}},$be=class{static{r(this,"BoundedValueMap")}values=new Map;get(t){return this.values.get(t)}set(t,n){if(this.values.delete(t),this.values.set(t,n),this.values.size>yGo){let o=this.values.keys().next().value;typeof o=="string"&&this.values.delete(o)}}delete(t){this.values.delete(t)}deletePrefix(t){for(let n of this.values.keys())n.startsWith(t)&&this.values.delete(n)}};r(Bd,"optionalString");r(Y2,"nonNegative");r(oxt,"providerHostname");r(X2,"recordValue");r(OGa,"skillTelemetryFactFields");r(gPn,"streamingParentToolCallId");r(gGo,"mirroredSubagentToolFields");r(MGa,"eventTimestamp");r(NGa,"automationAdmission");r(LGa,"cronCreateAutomationId");r(FGa,"totalTokensOf");r(jGa,"toToolPerformanceFact");r(BGa,"terminalStatus");r(_Go,"modelRequestQueueKey");r(vGo,"isStepUsageQuerySource");r(UGa,"isStepUsageModelComplete");r(zGa,"compactTerminalStatus");qbe=class{static{r(this,"ConversationTelemetryFactNormalizer")}firstStreamChunks=new hPn;sourceCommandByTurn=new $be;toolNameByCall=new $be;modelBySession=new $be;completedModelRequests=new $be;normalize(t,n,o){let s=n.turnId?String(n.turnId):void 0,a=s?`${t}\0${s}`:void 0,l={...o?.memoryEnabled!==void 0?{memoryEnabled:o.memoryEnabled}:{},version:1,eventId:String(n.id),eventSeq:Math.max(0,Math.floor(n.sequenceNumber)),occurredAt:MGa(n),sessionId:t,...s?{turnId:s}:{}},u=a?this.sourceCommandByTurn.get(a):void 0;switch(n.type){case lt.TurnStarted:{let f=n.payload,g=f.backgroundSource==="bash"||f.backgroundSource==="subagent"||f.backgroundSource==="workflow"?f.backgroundSource:void 0,_=Bd(f.inputId);return a&&_&&this.sourceCommandByTurn.set(a,_),rC.parse({...l,kind:"turn.started",..._?{sourceCommandId:_}:{},...NGa(_,Bd(f.automationId)),...Bd(f.offPeakTaskId)?{offPeakTaskId:Bd(f.offPeakTaskId)}:{},...f.offPeakRunType?{offPeakRunType:f.offPeakRunType}:{},...f.executionKind?{executionKind:f.executionKind}:{},...f.inputSource?{inputSource:f.inputSource}:{},...g?{backgroundSource:g}:{}})}case lt.ModelNetworkStatus:{let f=n.payload;if(f.type==="model_request_queued"||f.type==="model_request_admitted")return null;let g=String(f.providerId),_=String(f.modelId);this.modelBySession.set(t,{modelName:_,modelProvider:g});let b=rC.parse({...l,kind:"model.request.status",...u?{sourceCommandId:u}:{},requestId:String(f.requestId),status:f.type,providerId:g,modelId:_,...f.providerKind?{providerKind:f.providerKind}:{},...oxt(f.baseURL)?{providerHostname:oxt(f.baseURL)}:{},transport:f.transport,...f.querySource?{querySource:f.querySource}:{},...f.queryId?{queryId:String(f.queryId)}:{},attempt:f.attempt,maxAttempts:f.maxAttempts,...f.type==="model_request_completed"?{durationMs:f.durationMs}:{},...f.type==="model_request_failed"?{...f.durationMs!==void 0?{durationMs:f.durationMs}:{},reason:f.reason,retryable:f.retryable,...f.statusCode!==void 0?{statusCode:f.statusCode}:{}}:{},...f.type==="model_retry_scheduled"?{delayMs:f.delayMs,nextAttempt:f.nextAttempt,reason:f.reason,...f.statusCode!==void 0?{statusCode:f.statusCode}:{}}:{},...f.type==="model_stream_stalled"?{idleMs:f.idleMs,timeoutMs:f.timeoutMs}:{}}),w=Bd(f.querySource);if(f.type==="model_request_completed"&&vGo(w)){let T=_Go(t,w),I=this.completedModelRequests.get(T)??[];I.push({requestId:String(f.requestId),providerId:g,modelId:_,...f.providerKind?{providerKind:f.providerKind}:{},...oxt(f.baseURL)?{providerHostname:oxt(f.baseURL)}:{}}),this.completedModelRequests.set(T,I)}return b}case lt.ModelStreaming:{let f=n.payload,g=X2(n.payload),_=f.kind==="text_delta"?"text":f.kind==="reasoning_delta"?"thought":null;if(!_)return null;let b=gPn(g),w=`${t}\0${s??""}\0${_}\0${String(f.partId??"")}\0${b??""}`;return rC.parse({...l,kind:"stream.chunk",...u?{sourceCommandId:u}:{},channel:_,chunkLength:f.delta.length,firstChunk:this.firstStreamChunks.add(w),...f.assistantMessageId?{assistantMessageId:String(f.assistantMessageId)}:{},...f.partId?{partId:String(f.partId)}:{},...b?{parentToolCallId:b}:{}})}case lt.ToolCallScheduled:{let f=n.payload,g=X2(n.payload),_=String(f.toolCallId);return this.toolNameByCall.set(`${a??t}\0${_}`,f.toolName),rC.parse({...l,kind:"tool.lifecycle",...u?{sourceCommandId:u}:{},phase:"scheduled",toolCallId:_,toolName:f.toolName,...gGo(g)})}case lt.ToolCallStarted:case lt.ToolCallProgress:case lt.ToolCallResult:case lt.ToolCallError:{let f=n.payload,g=X2(n.payload),_=String(f.toolCallId),b=`${a??t}\0${_}`,T=("toolName"in f?Bd(f.toolName):void 0)??this.toolNameByCall.get(b),I=n.type===lt.ToolCallResult?f:null,E=n.type===lt.ToolCallError?f:null,R=X2(I?.result.display),L=jGa(I?.result.perf),U=n.type===lt.ToolCallStarted?"started":n.type===lt.ToolCallProgress?"progress":n.type===lt.ToolCallResult?I?.result.success===!1?"failed":"completed":"failed",B=U==="completed"&&T==="CronCreate"?LGa(I?.result.content):void 0;return(U==="completed"||U==="failed")&&this.toolNameByCall.delete(b),rC.parse({...l,kind:"tool.lifecycle",...u?{sourceCommandId:u}:{},phase:U,toolCallId:_,...T?{toolName:T}:{},...B?{automationId:B}:{},...I?{durationMs:I.duration}:{},...E?{errorCode:E.error.code??E.error.type}:{},...E?{errorMessage:E.error.message}:{},...I?.result.error?{errorCode:I.result.error.code??I.result.error.type}:{},...I?.result.error?{errorMessage:I.result.error.message}:{},...OGa(T,E?.skillMetadata??I?.skillMetadata),...gGo(g,R),...L?{performance:L}:{}})}case lt.PermissionRequested:case lt.PermissionResolved:case lt.PermissionDenied:{let f=n.payload,g=X2(f),_=n.type===lt.PermissionRequested?f:null,b=n.type===lt.PermissionResolved?f:null,w=n.type===lt.PermissionDenied?f:null;return rC.parse({...l,kind:"permission.lifecycle",...u?{sourceCommandId:u}:{},phase:_?"requested":b?"resolved":"denied",...Bd(_?.requestId??b?.requestId)?{requestId:Bd(_?.requestId??b?.requestId)}:{},toolCallId:String(f.toolCallId),..._?.toolName?{toolName:_.toolName}:w?.toolName?{toolName:w.toolName}:{},...Bd(g.childSessionId)?{childSessionId:Bd(g.childSessionId)}:{},...g.background===!0?{background:!0}:{},...b?{decision:b.decision}:{}})}case lt.ModelComplete:{let f=n.payload,g=_Go(t,Bd(f.querySource)),_=this.completedModelRequests.get(g)??[],b=_.shift();if(_.length>0?this.completedModelRequests.set(g,_):this.completedModelRequests.delete(g),!UGa(f))return null;let w=X2(f.usage);return rC.parse({...l,kind:"usage.delta",...u?{sourceCommandId:u}:{},...b?{requestId:b.requestId,providerId:b.providerId,modelId:b.modelId,...b.providerKind?{providerKind:b.providerKind}:{},...b.providerHostname?{providerHostname:b.providerHostname}:{}}:{},inputTokens:Y2(w.inputTokens)??0,outputTokens:Y2(w.outputTokens)??0,totalTokens:FGa(w),reasoningTokens:Y2(w.reasoningTokens)??0,cacheReadTokens:Y2(w.cacheReadTokens)??Y2(w.cacheTokens)??0,cacheWriteTokens:Y2(w.cacheWriteTokens)??0})}case lt.DynamicWorkflowRunProgress:return mGo(l,n.payload);case lt.SubagentSpawned:case lt.SubagentStopped:{let f=X2(n.payload),g=Bd(f.agentId),_=Bd(f.childSessionId);return!g||!_?null:rC.parse({...l,kind:"subagent.lifecycle",...u?{sourceCommandId:u}:{},phase:n.type===lt.SubagentSpawned?"spawned":"stopped",agentId:g,...Bd(f.agentType)?{agentType:Bd(f.agentType)}:{},childSessionId:_,...Bd(f.parentToolCallId)?{parentToolCallId:Bd(f.parentToolCallId)}:{},background:f.background===!0,...Bd(f.status)?{status:Bd(f.status)}:{},...n.type===lt.SubagentStopped&&Bd(f.error)?{errorMessage:Bd(f.error)}:{}})}case lt.TurnComplete:{let f=n.payload,g=Bd(f.inputId)??u,_=rC.parse({...l,kind:"turn.terminal",...g?{sourceCommandId:g}:{},status:BGa(f.resultType),resultType:f.resultType,durationMs:f.duration,tokenCount:f.tokenCount,toolCallCount:f.toolCallCount,...f.resultType==="cancelled"?{errorCode:"USER_INTERRUPT",errorMessage:"User stopped generation"}:{},...f.backgroundSubagentResultConsumed?{backgroundSubagentResultConsumed:!0}:{},...f.workflowResultConsumed?{workflowResultConsumed:!0}:{}});return this.clearTurn(a),_}case lt.TurnError:{let f=n.payload,g=Bd(f.inputId)??u,_=rC.parse({...l,kind:"turn.terminal",...g?{sourceCommandId:g}:{},status:"failed",errorCode:f.error.code??f.error.type,errorMessage:f.error.message,...f.error.retryable!==void 0?{errorRetryable:f.error.retryable}:{},...f.backgroundSubagentResultConsumed?{backgroundSubagentResultConsumed:!0}:{},...f.workflowResultConsumed?{workflowResultConsumed:!0}:{},turnPhase:f.turnPhase});return this.clearTurn(a),_}case lt.CompactCompleted:case lt.CompactFailed:{let f=n.payload,g=zGa(f.status);if(!g)return null;let b=this.modelBySession.get(t)??(o?.modelName||o?.modelProvider?{modelName:o.modelName??"",modelProvider:o.modelProvider??""}:void 0);return rC.parse({...l,kind:"compaction.terminal",...f.sourceCommandId?{sourceCommandId:f.sourceCommandId}:{},operationId:f.operationId,...f.messageId?{messageId:String(f.messageId)}:{},...f.summaryMessageId?{summaryMessageId:String(f.summaryMessageId)}:{},status:g,trigger:f.trigger,...f.compactReason?{compactReason:f.compactReason}:{},...f.reason?{reason:f.reason}:{},...f.attempt!==void 0?{attempt:f.attempt}:{},...f.maxAttempts!==void 0?{maxAttempts:f.maxAttempts}:{},...f.startedAt!==void 0?{startedAt:f.startedAt}:{},...f.endedAt!==void 0?{endedAt:f.endedAt}:{},...f.preCompactTokenCount!==void 0?{preCompactTokenCount:f.preCompactTokenCount}:{},...f.postCompactTokenCount!==void 0?{postCompactTokenCount:f.postCompactTokenCount}:{},...f.truePostCompactTokenCount!==void 0?{truePostCompactTokenCount:f.truePostCompactTokenCount}:{},...b||{}})}default:return null}}clearTurn(t){t&&(this.sourceCommandByTurn.delete(t),this.firstStreamChunks.deletePrefix(`${t}\0`),this.toolNameByCall.deletePrefix(`${t}\0`))}clearSession(t){let n=`${t}\0`;this.sourceCommandByTurn.deletePrefix(n),this.firstStreamChunks.deletePrefix(n),this.toolNameByCall.deletePrefix(n),this.modelBySession.delete(t),this.completedModelRequests.deletePrefix(n)}}});var bGo,ixt,SGo=Y(()=>{"use strict";dGo();pGo();nr();_Pn();bGo=require("node:crypto");g0();ixt=class{static{r(this,"LocalTtftRecorder")}now;onDrop;onCheckpoint;instanceId=(0,bGo.randomUUID)();clockWatch;preparationSubscriptions=new Map;normalizer=new qbe;requestState=new Map;queueSources=new Map;checkpointSignatures=new Map;completed=new Map;records=new Map;constructor(t=Gj,n=()=>{},o=()=>{}){this.now=t,this.onDrop=n,this.onCheckpoint=o}receive(t,n){return this.prune(),!t.ttft||this.records.has(t.commandId)||this.completed.has(t.commandId)?!0:this.records.size>=Kpe?!1:(this.records.set(t.commandId,{...t.ttft,instanceId:this.instanceId,commandId:t.commandId,...t.sessionId?{sessionId:t.sessionId}:{},receivedAt:this.now(),sendMode:n?"queued":"idle",details:[]}),this.clockWatch??=new rxt(this.now,o=>{if(o)for(let s of this.records.values())s.outputAt===void 0&&(s.clockInvalid=!0,this.checkpoint(s));this.prune(),this.records.size||(this.clockWatch?.dispose(),this.clockWatch=void 0)}),this.preparationSubscriptions.set(t.commandId,NSr(t.commandId,o=>{let s=this.records.get(t.commandId);if(!(!s||s.sessionId&&s.sessionId!==o.sessionId||s.turnId&&s.turnId!==o.turnId)){if(s.sessionId=o.sessionId,s.turnId=o.turnId,o.stage==="execution")s.executionAt??=o.start;else{let a=s.details??=[],l=a.findIndex(f=>f.id===o.id),u={id:o.id,stage:o.stage,start:o.start,end:o.end,outcome:o.outcome,source:"cli"};l>=0?a[l]=u:a.length<Ez?a.push(u):s.truncated=!0}this.checkpoint(s)}})),!0)}checkpoint(t){let n=JSON.stringify({...t,revision:void 0});if(this.checkpointSignatures.get(t.commandId)!==n){this.checkpointSignatures.set(t.commandId,n),t.revision=(t.revision??0)+1;try{this.onCheckpoint({...t,details:t.details?.map(o=>({...o}))})}catch{}}}admitted(t){let n=this.records.get(t);n&&(n.admittedAt??=this.now(),this.checkpoint(n))}event(t,n){if(!this.records.size)return;if(this.queueEvent(t,n),n.type===lt.CompactStarted||n.type===lt.CompactCompleted||n.type===lt.CompactFailed){let s=this.forSession(t);s&&uGo(s,n,this.now())&&this.checkpoint(s)}let o=this.normalizer.normalize(t,n);if(o&&this.fact(o,n.type===lt.TurnStarted?n.payload.executionStartedAt:void 0),n.type===lt.ModelNetworkStatus){let s=n.payload,a=this.forSession(t);if(a&&s.modelCall){a.requestId===s.requestId&&(a.logicalCallId=s.modelCall.logicalCallId);let l=a.details?.find(u=>u.requestId===s.requestId&&u.stage==="attempt");l&&(l.logicalCallId=s.modelCall.logicalCallId),this.checkpoint(a)}}if(n.type===lt.ModelStreaming){let s=n.payload;if(gPn(n.payload))return;if(s.kind==="tool_call"&&s.toolName?.trim()){this.output(t,n.turnId?String(n.turnId):void 0,"tool");return}if(!s.delta?.trim())return;let a=s.kind==="text_delta"?"text":s.kind==="reasoning_delta"?"reasoning":s.kind==="tool_input_delta"?"tool":void 0;a&&this.output(t,n.turnId?String(n.turnId):void 0,a)}}queueEvent(t,n){if(n.type===lt.TurnSteerQueued){let o=n.payload,s=o.intent?.sourceCommandId??o.inputId,a=s?this.records.get(s):void 0;a&&(!a.sessionId||a.sessionId===t)&&(a.sessionId=t,a.sendMode="queued",this.queueSources.set(o.pendingInputId,a.commandId),this.checkpoint(a))}if(n.type===lt.TurnSteerDrained){let o=n.payload;for(let s of o.drainedInputs??[]){if(s.delivery!=="guide")continue;let a=s.intent?.sourceCommandId??this.queueSources.get(s.pendingInputId),l=a?this.records.get(a):void 0;l?.sessionId===t&&(l.sendMode="guided",this.checkpoint(l),this.retire(l))}}if(n.type===lt.TurnSteerDiscarded){let o=n.payload;if(o.reason==="promoted")return;for(let s of o.pendingInputIds){let a=this.queueSources.get(s),l=a?this.records.get(a):void 0;l?.sessionId===t&&(l.terminal=o.reason==="turn_failed"?"failed":"cancelled",this.checkpoint(l),this.retire(l))}}}fact(t,n){this.prune();let o=t.sourceCommandId?this.records.get(t.sourceCommandId):void 0;if(!(!o||o.sessionId&&o.sessionId!==t.sessionId)){if(t.kind==="turn.started"){o.sessionId=t.sessionId,o.turnId=t.turnId,o.executionAt??=n,this.checkpoint(o);return}if(o.turnId===void 0&&t.kind==="turn.terminal"&&(o.turnId=t.turnId),o.turnId===t.turnId){if(t.kind==="model.request.status"&&o.outputAt===void 0){if(t.querySource!=="main_turn"&&t.querySource!=="compact")return;let s=t.querySource==="main_turn"?"response":"preparation",a=o.details??=[],l=`attempt:${t.requestId}`,u=a.find(f=>f.id===l);if(t.status==="model_request_started"&&!u){this.requestState.set(o.commandId,s),a.length<Ez?(u={id:l,stage:"attempt",start:this.now(),requestId:t.requestId,role:s,source:"cli"},a.push(u)):o.truncated=!0;for(let f of a)f.stage==="retry_wait"&&f.end===void 0&&f.role===s&&(f.end=this.now(),f.outcome="completed");s==="response"&&(o.requestAt??=this.now(),o.queryId??=t.queryId,o.requestId=t.requestId,o.model=t.modelId.slice(0,128),o.provider=t.providerId.slice(0,128))}(t.status==="model_request_failed"||t.status==="model_request_completed")&&u&&u.end===void 0&&(u.end=this.now(),u.outcome=t.status==="model_request_failed"?"failed":"completed",s==="response"&&t.status==="model_request_failed"&&o.requestId===t.requestId&&this.requestState.set(o.commandId,"failed")),t.status==="model_retry_scheduled"&&!a.some(f=>f.id===`retry:${t.requestId}`)&&(a.length<Ez?a.push({id:`retry:${t.requestId}`,stage:"retry_wait",start:this.now(),requestId:t.requestId,role:s,source:"cli"}):o.truncated=!0)}this.checkpoint(o),t.kind==="tool.lifecycle"&&t.phase==="scheduled"&&!t.parentToolCallId&&this.output(t.sessionId,t.turnId,"tool"),t.kind==="turn.terminal"&&(o.terminal=t.status==="success"?"completed":t.status==="failed"?"failed":"cancelled",this.checkpoint(o),this.retire(o))}}}output(t,n,o){for(let s of this.records.values())if(!(this.requestState.get(s.commandId)==="failed"||this.requestState.get(s.commandId)==="preparation")){if(s.sessionId===t&&s.turnId===n&&s.requestAt!==void 0&&s.outputAt===void 0){s.outputAt=this.now(),s.outputKind=o,this.preparationSubscriptions.get(s.commandId)?.(),this.preparationSubscriptions.delete(s.commandId);let a=s.details?.find(l=>l.id===`attempt:${s.requestId}`);a&&a.end===void 0&&(a.end=s.outputAt,a.outcome="first_output")}s.sessionId===t&&s.turnId===n&&s.requestAt!==void 0&&o==="text"&&this.retire(s)}}retire(t){if(this.forget(t.commandId),this.records.delete(t.commandId),this.records.size||(this.clockWatch?.dispose(),this.clockWatch=void 0),this.completed.set(t.commandId,t),this.completed.size>Kpe){this.completed.delete(this.completed.keys().next().value);try{this.onDrop()}catch{}}}forSession(t,n){return this.prune(),[...this.completed.values(),...this.records.values()].reverse().find(o=>o.sessionId===t&&(n?o.commandId===n:o.turnId!==void 0))}clear(){this.clockWatch?.dispose(),this.clockWatch=void 0;for(let t of this.preparationSubscriptions.values())t();this.preparationSubscriptions.clear(),this.records.clear(),this.requestState.clear(),this.queueSources.clear(),this.checkpointSignatures.clear(),this.completed.clear()}forget(t){this.preparationSubscriptions.get(t)?.(),this.preparationSubscriptions.delete(t),this.requestState.delete(t),this.checkpointSignatures.delete(t);for(let[n,o]of this.queueSources)o===t&&this.queueSources.delete(n)}prune(){let t=this.now();for(let n of[this.records,this.completed])for(let[o,s]of n)t-s.receivedAt>FHt&&(this.forget(o),n.delete(o))}}});function sxt(e,t,n){return`${e}\0${t}\0${n}`}function $Ga(e){return{fileName:e.fileName,mime:e.mime,totalBytes:e.totalBytes,totalChunks:e.totalChunks,checksum:e.checksum}}function wGo(e,t){return e.fileName===t.fileName&&e.mime===t.mime&&e.totalBytes===t.totalBytes&&e.totalChunks===t.totalChunks&&e.checksum===t.checksum}function qGa(e,t){if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n+=1)if(e[n]!==t[n])return!1;return!0}var kGo,axt,xGo=Y(()=>{"use strict";kGo=require("node:crypto");g0();r(sxt,"uploadKey");r($Ga,"metadataOf");r(wGo,"sameMetadata");r(qGa,"sameBytes");axt=class{static{r(this,"AttachmentUploadRegistry")}options;staged=new Map;committed=new Map;stagedBytes=0;constructor(t){this.options=t}begin(t){this.pruneExpired();let n=sxt(t.connectionId,t.sessionId,t.uploadId),o=$Ga(t),s=this.committed.get(n);if(s){if(!wGo(s.metadata,o))throw new Error("fault.attachment.beginConflict");return{uploadId:t.uploadId,state:"committed",nextChunkIndex:s.nextChunkIndex,ref:s.ref}}let a=this.staged.get(n);if(a){if(!wGo(a.metadata,o))throw new Error("fault.attachment.beginConflict");return a.expiresAt=this.options.now()+fc.attachmentUploadTtlMs,{uploadId:t.uploadId,state:"staging",nextChunkIndex:a.chunks.length}}if(this.staged.size>=fc.attachmentUploadMaxConcurrent)throw new Error("fault.attachment.tooManyUploads");if(t.totalChunks>0&&t.totalBytes>t.totalChunks*fc.attachmentChunkMaxBytes)throw new Error("fault.attachment.chunkCountInsufficient");return this.staged.set(n,{key:n,connectionId:t.connectionId,sessionId:t.sessionId,uploadId:t.uploadId,metadata:o,chunks:[],receivedBytes:0,expiresAt:this.options.now()+fc.attachmentUploadTtlMs,commitPromise:null}),{uploadId:t.uploadId,state:"staging",nextChunkIndex:0}}chunk(t){this.pruneExpired();let n=sxt(t.connectionId,t.sessionId,t.uploadId),o=this.staged.get(n);if(!o)throw new Error("fault.attachment.uploadNotFound");if(o.commitPromise)throw new Error("fault.attachment.commitInProgress");let s=new Uint8Array(Buffer.from(t.dataBase64,"base64"));if(t.chunkIndex<o.chunks.length){if(!qGa(o.chunks[t.chunkIndex],s))throw new Error("fault.attachment.chunkConflict");return{uploadId:t.uploadId,nextChunkIndex:o.chunks.length}}if(t.chunkIndex>o.chunks.length)throw new Error("fault.attachment.chunkGap");if(t.chunkIndex>=o.metadata.totalChunks)throw new Error("fault.attachment.tooManyChunks");if(s.byteLength===0)throw new Error("fault.attachment.emptyChunk");if(o.receivedBytes+s.byteLength>o.metadata.totalBytes)throw new Error("fault.attachment.totalBytesExceeded");if(this.stagedBytes+s.byteLength>fc.attachmentUploadMaxStagedBytes)throw new Error("fault.attachment.stagingCapacityExceeded");return o.chunks.push(s),o.receivedBytes+=s.byteLength,o.expiresAt=this.options.now()+fc.attachmentUploadTtlMs,this.stagedBytes+=s.byteLength,{uploadId:t.uploadId,nextChunkIndex:o.chunks.length}}async commit(t){this.pruneExpired();let n=sxt(t.connectionId,t.sessionId,t.uploadId),o=this.committed.get(n);if(o)return{ref:o.ref};let s=this.staged.get(n);if(!s)throw new Error("fault.attachment.uploadNotFound");if(s.commitPromise)return s.commitPromise;let a=this.commitStaged(s);s.commitPromise=a;try{return await a}catch(l){throw this.staged.get(n)===s&&(s.commitPromise=null),l}}async abort(t){this.pruneExpired();let n=sxt(t.connectionId,t.sessionId,t.uploadId),o=this.staged.get(n);if(o?.commitPromise){await o.commitPromise;return}this.deleteStaged(n)}clearConnection(t){this.clearWhere(n=>n.connectionId===t);for(let[n,o]of this.committed)o.connectionId===t&&this.committed.delete(n)}clearSession(t){this.clearWhere(n=>n.sessionId===t);for(let[n,o]of this.committed)o.sessionId===t&&this.committed.delete(n)}clear(){this.staged.clear(),this.committed.clear(),this.stagedBytes=0}pruneExpired(){let t=this.options.now();this.clearWhere(n=>n.expiresAt<=t&&n.commitPromise===null);for(let[n,o]of this.committed)o.expiresAt<=t&&this.committed.delete(n)}async commitStaged(t){if(t.chunks.length!==t.metadata.totalChunks||t.receivedBytes!==t.metadata.totalBytes)throw new Error("fault.attachment.uploadIncomplete");let n=(0,kGo.createHash)("sha256");for(let l of t.chunks)n.update(l);if(`sha256:${n.digest("hex")}`!==t.metadata.checksum)throw new Error("fault.attachment.checksumMismatch");let o=new Uint8Array(t.metadata.totalBytes),s=0;for(let l of t.chunks)o.set(l,s),s+=l.byteLength;let{ref:a}=await this.options.putSessionAttachment(t.sessionId,{fileName:t.metadata.fileName,mime:t.metadata.mime,bytes:o});return this.staged.get(t.key)===t&&this.deleteStaged(t.key),this.committed.set(t.key,{connectionId:t.connectionId,sessionId:t.sessionId,uploadId:t.uploadId,metadata:t.metadata,nextChunkIndex:t.chunks.length,ref:a,expiresAt:this.options.now()+fc.attachmentUploadTtlMs}),{ref:a}}deleteStaged(t){let n=this.staged.get(t);n&&(this.staged.delete(t),this.stagedBytes-=n.receivedBytes)}clearWhere(t){for(let[n,o]of this.staged)t(o)&&this.deleteStaged(n)}}});var u3e,cxt,TGo=Y(()=>{"use strict";u3e=class extends Error{static{r(this,"V4SubscribeSessionUnavailableError")}sessionId;reasonCode;constructor(t,n,o,s){super(`${o} (${n})`,s),this.sessionId=t,this.reasonCode=n,this.name="V4SubscribeSessionUnavailableError"}},cxt=class{static{r(this,"ColdSessionResumeCoordinator")}host;flights=new Map;constructor(t){this.host=t}ensureResumed(t,n,o){let s=this.flights.get(t);if(s)return this.host.onDebug?.(`cold resume joined existing flight session=${t}`),s;this.host.onDebug?.(`cold resume flight created session=${t}`);let a=this.resume(t,n,o).finally(()=>{this.flights.delete(t),this.host.onDebug?.(`cold resume flight cleared session=${t}`)});return this.flights.set(t,a),a}clear(){this.flights.clear()}async resume(t,n,o){let s=this.host.resumePersistedSession;if(!s)throw new u3e(t,"fault.subscribe.sessionNotFound",`Session is not active: ${t}`);let a;try{a=o?await s.call(this.host,t,n,o):await s.call(this.host,t,n)}catch(l){throw this.host.onError?.("v4.subscribe.resume",l,{phase:"resumePersistedSession",sessionId:t}),new u3e(t,"fault.subscribe.resumeFailed",`Failed to resume persisted session ${t}: ${l instanceof Error?l.message:String(l)}`,{cause:l})}if(a.status==="notFound")throw new u3e(t,"fault.subscribe.sessionNotFound",`Session is not active and not persisted: ${t}`);return a.persistedMessages}}});function d3e(e){return`queue_${e}`}var WGa,lxt,uxt,dxt=Y(()=>{"use strict";g0();WGa="@global";r(d3e,"queueItemIdForCommand");lxt=class{static{r(this,"AsyncGateRegistry")}tails=new Map;async acquire(t){let n=this.tails.get(t)??Promise.resolve(),o,s=new Promise(u=>{o=u}),a=n.then(()=>s);this.tails.set(t,a),await n;let l=!1;return()=>{l||(l=!0,o(),this.tails.get(t)===a&&this.tails.delete(t))}}},uxt=class{static{r(this,"CommandInbox")}host;inFlight=new Map;liveInputs=new Map;settled=new Map;admissionSeq=new Map;keyGates=new lxt;sessionGates=new lxt;constructor(t){this.host=t}async handle(t){let n=wPe(t);if(!n.ok)return this.ackOnly({commandId:this.extractCommandId(t),status:"rejected",reasonCode:"proto.invalidPayload",message:n.error.message,revisionAtDecision:0});let o=n.envelope,s={sessionId:o.sessionId,commandId:o.commandId},a=this.bucketKey(o.sessionId),l=await this.keyGates.acquire(this.keyGateKey(s));try{let u=this.inFlight.get(a)?.get(o.commandId);if(u)return this.ackOnly(this.retryAck(await u.final));let f=await this.lookupExact(s);if(f)return this.ackOnly(this.retryAck(f));let g=await this.sessionGates.acquire(a);try{let _=this.inFlight.get(a)?.get(o.commandId);if(_)return g(),this.ackOnly(this.retryAck(await _.final));let b=await this.lookupExact(s);if(b)return g(),this.ackOnly(this.retryAck(b));let w=this.decide(o);if(w.kind==="ack")return w.remember&&this.rememberSettled(a,o.commandId,w.ack),g(),this.ackOnly(w.ack);let T=(this.admissionSeq.get(a)??0)+1,I=this.host.now?.()??Date.now();this.admissionSeq.set(a,T);let E,R=new Promise(B=>{E=B}),L={ack:w.ack,final:R,resolveFinal:E};this.mapFor(this.inFlight,a).set(o.commandId,L),l();let U=!1;return{kind:"execute",envelope:o,ack:w.ack,admissionSeq:T,admittedAt:I,queueItemId:d3e(o.commandId),settle:r(B=>{if(U)return;U=!0;let z=this.liveInputs.get(a)?.get(o.commandId),$={...w.ack,...B};this.inFlight.get(a)?.delete(o.commandId),z?z.ack=$:this.rememberSettled(a,o.commandId,$),L.resolveFinal($),g()},"settle")}}catch(_){throw g(),_}}catch(u){return this.ackOnly(this.queryUnavailableAck(s,u))}finally{l()}}async query(t){return Promise.all(t.map(n=>this.queryOne(n)))}pinLiveInput(t,n,o){let s=this.bucketKey(t),a=this.inFlight.get(s)?.get(n.sourceCommandId)?.ack;this.mapFor(this.liveInputs,s).set(n.sourceCommandId,{intent:n,ack:o??a??{commandId:n.sourceCommandId,status:"accepted",revisionAtDecision:0}}),this.settled.get(s)?.delete(n.sourceCommandId)}releaseLiveInput(t,n){let o=this.bucketKey(t.sessionId),s=this.liveInputs.get(o)?.get(t.commandId);this.liveInputs.get(o)?.delete(t.commandId),(n??s?.ack)&&this.rememberSettled(o,t.commandId,n??s.ack)}hasPinnedSessionState(t){let n=this.bucketKey(t);return(this.inFlight.get(n)?.size??0)>0||(this.liveInputs.get(n)?.size??0)>0}clearSession(t){let n=this.bucketKey(t);return this.hasPinnedSessionState(t)?!1:(this.inFlight.delete(n),this.liveInputs.delete(n),this.settled.delete(n),this.admissionSeq.delete(n),!0)}async queryOne(t){let n=await this.keyGates.acquire(this.keyGateKey(t));try{return{key:t,result:await this.lookupExact(t)??"unknown"}}catch(o){return{key:t,result:this.queryUnavailableAck(t,o)}}finally{n()}}async lookupExact(t){let n=this.bucketKey(t.sessionId),o=this.inFlight.get(n)?.get(t.commandId);if(o)return await o.final;let s=this.liveInputs.get(n)?.get(t.commandId);if(s)return s.ack;let a=this.settled.get(n)?.get(t.commandId);if(a)return this.touchSettled(n,t.commandId,a),a;for(let l of[this.host.lookupTranscriptCommand,this.host.lookupTimelineCommand,this.host.lookupChildCommand,this.host.lookupDiscardedCommand]){let u=await l?.(t);if(u)return u}return null}decide(t){let n=t.sessionId===null?0:this.host.getRevision(t.sessionId);if(n===null||t.type!=="createSession"&&t.sessionId===null)return{kind:"ack",remember:!1,ack:{commandId:t.commandId,status:"rejected",reasonCode:"proto.sessionNotFound",revisionAtDecision:0}};if(cYt.has(t.type)){if(t.baseRevision===void 0)return{kind:"ack",remember:!1,ack:{commandId:t.commandId,status:"rejected",reasonCode:"proto.missingBaseRevision",revisionAtDecision:n}};let a=t.sessionId===null?null:this.host.getLogEpoch(t.sessionId);if(lYt.has(t.type)&&t.baseLogEpoch!==a)return{kind:"ack",remember:!1,ack:{commandId:t.commandId,status:"stale",reasonCode:"proto.staleLogEpoch",revisionAtDecision:n}};if(t.baseRevision!==n)return{kind:"ack",remember:!1,ack:{commandId:t.commandId,status:"stale",reasonCode:"proto.staleRevision",revisionAtDecision:n}}}let o=this.host.validateRowTarget?.(t);if(o?.verdict==="stale")return{kind:"ack",remember:!1,ack:{commandId:t.commandId,status:"stale",reasonCode:o.reasonCode,message:o.message,revisionAtDecision:n}};if(o?.verdict==="reject")return{kind:"ack",remember:!1,ack:{commandId:t.commandId,status:"rejected",reasonCode:o.reasonCode,message:o.message,revisionAtDecision:n}};let s=this.host.guard?.(t)??{verdict:"allow"};return s.verdict==="stale"?{kind:"ack",remember:!1,ack:{commandId:t.commandId,status:"stale",reasonCode:s.reasonCode,message:s.message,revisionAtDecision:n}}:s.verdict==="reject"?{kind:"ack",remember:!1,ack:{commandId:t.commandId,status:"rejected",reasonCode:s.reasonCode,message:s.message,revisionAtDecision:n}}:s.verdict==="noop"?{kind:"ack",remember:!0,ack:{commandId:t.commandId,status:"noop",reasonCode:s.reasonCode,revisionAtDecision:n,result:s.result}}:{kind:"execute",ack:{commandId:t.commandId,status:"accepted",revisionAtDecision:n}}}retryAck(t){return t.status==="failed"?t:{...t,status:"duplicate"}}queryUnavailableAck(t,n){return{commandId:t.commandId,status:"failed",reasonCode:"fault.command.queryUnavailable",revisionAtDecision:t.sessionId===null?0:this.host.getRevision(t.sessionId)??0}}ackOnly(t){return{kind:"ack",ack:t}}bucketKey(t){return t??WGa}keyGateKey(t){return`${this.bucketKey(t.sessionId)}\0${t.commandId}`}mapFor(t,n){let o=t.get(n);return o||(o=new Map,t.set(n,o)),o}touchSettled(t,n,o){let s=this.mapFor(this.settled,t);s.delete(n),s.set(n,o)}rememberSettled(t,n,o){let s=this.mapFor(this.settled,t);for(s.delete(n),s.set(n,o);s.size>fc.idempotencyTablePerSession;){let a=s.keys().next().value;if(a===void 0)break;s.delete(a)}}extractCommandId(t){if(typeof t=="object"&&t!==null&&"commandId"in t){let n=t.commandId;if(typeof n=="string")return n}return""}}});function IGo(e){return e.op==="workflowRun.updated"||e.op==="workflowRun.removed"}function CGo(e,t){let n=-1;for(let a=e.length-1;a>=0;a-=1)if(IGo(e[a])){n=a;break}if(n<0)return e;let o=t===void 0?null:{op:"state.updated",patch:{workflowRuns:iQe(t)}},s=[];for(let a=0;a<e.length;a+=1){let l=e[a];if(!IGo(l)){s.push(l);continue}a===n&&o!==null&&s.push(o)}return s}function EGo(e){for(let t of e)if(t.op!=="workflowRun.updated"&&t.op!=="workflowRun.removed")return null;return Mz(e)+VGa}var VGa,AGo=Y(()=>{"use strict";g0();r(IGo,"isWorkflowRunDelta");r(CGo,"encodeConversationDeltasForLegacy");VGa=64;r(EGo,"workflowRunDeltaGrowthUpperBound")});function PGo(e,t){if(!t)return[];if(e.type===lt.ToolCallStarted){let o=e.payload;return[{op:"row.upserted",row:{...t,status:"running",startedAt:e.timestamp.getTime(),...o.display?.kind==="mcp_tool"?{display:o.display}:{}}}]}if(t.toolName!=="Bash"||t.status!=="running"||t.backgrounded)return[];let n=Aee.safeParse(e.payload.outputPreview);return n.success?[{op:"row.upserted",row:{...t,outputPreview:n.data}}]:[]}function RGo(e){return e.map(t=>{if(t.op!=="row.upserted"&&t.op!=="row.appended"||t.row.kind!=="toolCall"||!t.row.outputPreview||t.row.status==="running"&&!t.row.backgrounded)return t;let{outputPreview:n,...o}=t.row;return{...t,row:o}})}var DGo=Y(()=>{"use strict";g0();nr();r(PGo,"projectToolActivity");r(RGo,"clearSettledOutputPreviews")});function OGo(e,t){return e?t.reviewFlowId!==e.reviewFlowId?"cross_flow":t.generation>e.generation?"same_flow_advance":t.generation<e.generation?"same_flow_stale":t.interactionId===e.interactionId?"same_flow_replay":"same_flow_conflict":"no_current"}var MGo=Y(()=>{r(OGo,"verdictWorkspaceHookReviewRequest")});function yPn(e){let t=HGa.find(n=>e.startsWith(n));return t?e.slice(t.length):null}function _9(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function NGo(e){return _9(typeof e=="string"?pxt(e):e)}function GGa(e){let t=_9(e),n=[t?.app_ref,t?.app,_9(t?.target)?.app_ref];for(let o of n){let s=NGo(o)?.pid;if(typeof s=="number"&&Number.isInteger(s)&&s>0)return s}return null}function JGa(e){let t=_9(e),n=[t?.app_ref,t?.app,_9(t?.target)?.app_ref];for(let o of n){let s=NGo(o)?.bundle_id;if(typeof s=="string"&&s.trim())return s.trim()}return null}function LGo(e,t){let n=GGa(e);if(n!==null)return t.get(n);let o=JGa(e);if(!o)return;let s=[...t.values()].filter(a=>a.bundleId===o);return s.length===1?s[0]:void 0}function pxt(e){if(!e)return;let t=e.split(`
|
|
15252
15252
|
|