zcode-app-cli 3.14.4-31 → 3.14.4-33
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 +56 -7
- package/bin/zcode.js +85 -11
- package/docs/CONFIGURATION.md +185 -6
- package/docs/CONFIGURATION.zh-CN.md +161 -5
- package/docs/PROVIDER_CONFIG.md +4 -2
- package/docs/PROVIDER_CONFIG.zh-CN.md +3 -2
- package/package.json +1 -1
- package/vendor/cli-config.cjs +106 -3
- package/vendor/extraction.json +21 -1
- package/vendor/node_modules/@zcode/tui/dist/index.js +51 -10
- package/vendor/zcode.cjs +7 -7
package/vendor/zcode.cjs
CHANGED
|
@@ -1893,7 +1893,7 @@ WHERE id IN (SELECT id FROM repairs);
|
|
|
1893
1893
|
provider_total_tokens as providerTotalTokens
|
|
1894
1894
|
from model_usage
|
|
1895
1895
|
where session_id = ?
|
|
1896
|
-
order by started_at asc, id asc`).all(t.sessionID),o=0,s=0,a=0,l=0,u=0,f=0,g=0,_={};for(let b of n){let w=Number(b.providerTotalTokens??b.computedTotalTokens??0),T=oas(b),I=ias(b.querySource),E=I===void 0?T:Math.max(0,T-(_[I]??0));I!==void 0&&(_[I]=T);let R=Math.max(0,w-T),L=Number(b.outputTokens??0),U=Number(b.reasoningTokens??0);o+=E+R,s+=E,a+=L,l+=U,I===void 0&&(u+=Number(b.cacheCreationTokens??0),f+=Number(b.cacheReadTokens??0)),b.status==="error"&&(g+=1)}return{sessionID:t.sessionID,totalTokens:o,inputTokens:s,outputTokens:a,reasoningTokens:l,cacheCreationTokens:u,cacheReadTokens:f,modelRequestCount:n.length,modelErrorCount:g,inputBaselineBySource:_}}function ras(e,t,n){let o=Ih(e);return o>0?o:Ih(t)+Ih(n)}function oas(e){let t=Ih(e.inputTokens),n=Ih(e.cacheCreationTokens)+Ih(e.cacheReadTokens);if(t<=0)return n;if(n<=0)return t;let o=Ih(e.outputTokens),s=Ih(e.providerTotalTokens??e.computedTotalTokens);if(s>0){let a=Math.abs(s-(t+o));if(Math.abs(s-(t+n+o))<a)return t+n}return t}function ias(e){if(e==="main_turn"||e==="subagent"||e==="workflow_child")return e}function Ih(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.trunc(e))}function p3(e){return e?1:0}function Jkr(e){return e===void 0?null:p3(e)}var eas,tas,exr=Y(()=>{"use strict";bA();eas=30,tas=eas*24*60*60*1e3;r(Kkr,"recordModelUsage");r(Zkr,"upsertTurnUsage");r(Ykr,"upsertToolUsage");r(gRe,"pruneUsage");r(nas,"toolUsageValues");r(Xkr,"queryAppUsage");r(Qkr,"queryTaskUsage");r(ras,"inputSideTokensFromNormalizedUsage");r(oas,"inputSideTokensFromStoredUsage");r(ias,"taskUsageInputBaselineSource");r(Ih,"integer");r(p3,"boolean");r(Jkr,"nullableBoolean")});function txr(e){if(!e.data||typeof e.data!="object"||Array.isArray(e.data))return null;let t=e.data.ack;if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t.result;if(!n||typeof n!="object"||Array.isArray(n))return null;let o=n.sessionId;return typeof o=="string"&&o.length>0?o:null}function aas(e){let t=String(e.child.id),n=e.commandFact.ack.result,o=n&&typeof n=="object"&&!Array.isArray(n)?n:null,s=typeof o?.sessionId=="string"?o.sessionId.trim():"";if(!(o?.type==="forkAssistant"||o?.type==="createSelectionSideSession"||o?.type==="editUserQuery"&&o.disposition==="fork")||!s||s!==t)throw new Error("Fork bundle command result is missing, invalid, or not child-local");let l=new Set(e.messages.map(g=>String(g.info.id))),u=r((g,_)=>{if(typeof g=="string"&&!l.has(g))throw new Error(`Fork bundle ${_} is not child-local: ${g}`)},"assertMessage"),f=new Set;e.goal&&f.add(e.goal.source.targetID);for(let g of e.messages){if(String(g.info.sessionID)!==t)throw new Error("Fork bundle message session is not child-local");if(g.info.role==="assistant"&&!l.has(String(g.info.parentID)))throw new Error("Fork bundle assistant parent is not child-local");let _=g.info.anchor;for(let b of _?.orderedMessageIds??[])u(b,"anchor orderedMessageId");if(u(_?.boundaryMessageId,"anchor boundaryMessageId"),_?.goalBoundary?.kind==="snapshot"){if(String(_.goalBoundary.target.sessionID)!==t)throw new Error("Fork bundle anchor goal session is not child-local");f.add(_.goalBoundary.target.targetID)}for(let b of g.parts){if(String(b.sessionID)!==t||String(b.messageID)!==String(g.info.id))throw new Error("Fork bundle part owner is not child-local");if(b.type==="timeline"&&(u(b.anchorMessageId,"timeline anchorMessageId"),b.timelineType==="context_compaction"&&u(b.summaryMessageId,"timeline summaryMessageId"),b.timelineType==="goal_verification"&&f.add(b.targetId)),b.type==="compaction"){u(b.tail_start_id,"compaction tail_start_id"),u(b.summaryMessageId,"compaction summaryMessageId");let w=b.compactBoundary;u(w?.lastSummarizedMessageId,"compact lastSummarizedMessageId");for(let T of w?.summaryMessageIds??[])u(T,"compact summaryMessageId");for(let T of w?.attachmentMessageIds??[])u(T,"compact attachmentMessageId");for(let T of w?.hookResultMessageIds??[])u(T,"compact hookResultMessageId");u(w?.preservedSegment?.headMessageId,"compact preserved head"),u(w?.preservedSegment?.anchorMessageId,"compact preserved anchor"),u(w?.preservedSegment?.tailMessageId,"compact preserved tail")}if(b.type==="tool"&&b.state.status==="completed"){for(let w of b.state.attachments??[])if(String(w.sessionID)!==t||String(w.messageID)!==String(g.info.id))throw new Error("Fork bundle tool attachment owner is not child-local")}}}if(e.goal&&String(e.goal.source.sessionID)!==t)throw new Error("Fork bundle goal session is not child-local");for(let g of e.entries){if(String(g.sessionID)!==t)throw new Error("Fork bundle verifier entry session is not child-local");let _=g.data&&typeof g.data=="object"&&!Array.isArray(g.data)?g.data:{},b=_.payload&&typeof _.payload=="object"&&!Array.isArray(_.payload)?_.payload:{};if(u(b.anchorAssistantMessageId,"verifier assistant anchor"),typeof b.targetId=="string"&&!f.has(b.targetId))throw new Error("Fork bundle verifier target is not child-local")}}function dtt(e={}){return new fH(e)}var rxr,nxr,fH,oxr=Y(()=>{"use strict";XSr();rxr=require("node:sqlite");pwr();ett();Nwr();jwr();gfe();zwr();$Qt();skr();pkr();HQt();Akr();Nkr();Qet();Wkr();mRe();Gkr();exr();r(txr,"forkChildSessionId");r(aas,"assertForkBundleChildLocal");nxr=Symbol("deferredSqliteStartup"),fH=class e{static{r(this,"SqliteSessionStore")}db;dbPath;forkCommitFaultAt;dwfJournalStore;constructor(t={},n){this.dbPath=t.dbPath??MQt(),this.forkCommitFaultAt=t.forkCommitFaultAt;let o=t.startupLockTimeoutMs??ntt;try{Fwr(this.dbPath),xb({operation:"sqliteOpen",path:this.dbPath}),this.db=new rxr.DatabaseSync(this.dbPath,{timeout:o})}catch(s){throw new aF(`Failed to open SQLite session database at ${this.dbPath}`,{cause:s,dbPath:this.dbPath,kind:"open_failed"})}try{n!==nxr&&(Cwr(this.db,this.dbPath,o),this.db.exec("pragma busy_timeout = 10000"),require(require("node:path").join(__dirname,"cli-config.cjs")).installSqliteWriteRecovery(this))}catch(s){try{this.db.close()}catch{}throw s}}static async openStartup(t={},n={}){let o=new e(t,nxr);try{return await Ewr(o.db,o.dbPath,n),o.db.exec("pragma busy_timeout = 10000"),require(require("node:path").join(__dirname,"cli-config.cjs")).installSqliteWriteRecovery(o),o}catch(s){try{o.close()}catch{}throw s}}getDatabasePath(){return this.dbPath}close(){this.db.close()}throwBeforeWrite(){xb({operation:"sqliteRun",path:this.dbPath})}maybeThrowForkCommitFault(t){if(this.forkCommitFaultAt===t)throw new Error(`injected fork commit fault: ${t}`)}async createSession(t){return this.throwBeforeWrite(),fRe(this.db,t)}async createForkedSessionWithMetadata(t,n){if(this.throwBeforeWrite(),!t.parentID||String(t.parentID)!==n.parentSessionId)throw new Error("Fork child metadata parent does not match session parentID");let o=n.forkTarget.orderedMessageIds,s=n.forkTarget.boundaryMessageId.trim().length>0&&(o.length===0||o.at(-1)===n.forkTarget.boundaryMessageId);if(!n.sourceCommandId.trim()||!s)throw new Error("Fork child metadata is invalid");let a=`v4_command_fact:child:${n.parentSessionId}:${n.sourceCommandId}`;this.db.exec("begin immediate");try{let l=uH(this.db,{sessionID:t.parentID,type:"v4/command_fact"}).find(g=>g.id===a);if(l){let g=txr(l);if(!g)throw new Error(`Fork child command fact is corrupt: ${a}`);let _=Vte(this.db,g);if(!_)throw new Error(`Fork child session is missing: ${g}`);return this.db.exec("commit"),_}let u=fRe(this.db,t),f=Date.now();return tM(this.db,{id:a,sessionID:t.parentID,type:"v4/command_fact",time:{created:f,updated:f},data:{source:"child",ack:{commandId:n.sourceCommandId,status:"accepted",revisionAtDecision:0,result:{type:"forkAssistant",sessionId:String(u.id)}},metadata:n}}),this.db.exec("commit"),u}catch(l){throw this.db.exec("rollback"),l}}async commitForkBundle(t){this.throwBeforeWrite();let{child:n,commandFact:o,initialInput:s}=t;if(!n.parentID||String(n.parentID)!==o.parentSessionId||s&&String(s.sessionID)!==String(n.id)||o.ack.commandId!==o.sourceCommandId)throw new Error("Fork commit bundle identity is invalid");let a=`v4_command_fact:child:${o.parentSessionId}:${o.sourceCommandId}`;this.db.exec("begin immediate");try{let l=uH(this.db,{sessionID:n.parentID,type:"v4/command_fact"}).find(g=>g.id===a);if(l){let g=txr(l),_=g?Vte(this.db,g):null;if(!_)throw new Error(`Fork bundle command fact is corrupt: ${a}`);return this.db.exec("commit"),_}aas(t);let u=fRe(this.db,n);this.maybeThrowForkCommitFault("afterChild");for(let g of t.messages){let _=t.copySources?.messages[g.info.id];await pH(this.db,g.info,_?{sessionID:n.parentID,id:_}:void 0);for(let b of g.parts){let w=t.copySources?.parts[b.id];await pme(this.db,b,w?{sessionID:n.parentID,id:w}:void 0)}}this.maybeThrowForkCommitFault("afterMessages"),t.goal&&DQt(this.db,{source:t.goal.source,sessionID:n.id,status:t.goal.status}),this.maybeThrowForkCommitFault("afterGoal");for(let g of t.entries)tM(this.db,g);this.maybeThrowForkCommitFault("afterEntries"),s&&await ZQt(this.db,s),this.maybeThrowForkCommitFault("afterInput");let f=Date.now();return tM(this.db,{id:a,sessionID:n.parentID,type:"v4/command_fact",time:{created:f,updated:f},data:{source:"child",ack:o.ack,metadata:o.metadata}}),this.maybeThrowForkCommitFault("afterCommandFact"),this.maybeThrowForkCommitFault("beforeCommit"),this.db.exec("commit"),u}catch(l){throw this.db.exec("rollback"),l}}async commitSharedContextImportBundle(t){this.throwBeforeWrite();let{session:n,contextMessage:o,provenance:s}=t;if(String(o.info.sessionID)!==String(n.id)||String(s.sessionID)!==String(n.id)||!s.id.includes(String(n.id))||o.info.role!=="user"||o.info.visibility!=="model-only"||o.info.source!=="shared_context")throw new Error("Shared context import bundle identity is invalid");this.db.exec("begin immediate");try{let a=Vte(this.db,n.id);if(a){if(!uH(this.db,{sessionID:n.id,type:s.type}).find(f=>f.id===s.id))throw new Error("Shared context import session is incomplete");return this.db.exec("commit"),a}let l=fRe(this.db,n);await pH(this.db,o.info);for(let u of o.parts)await pme(this.db,u);return tM(this.db,s),this.db.exec("commit"),l}catch(a){throw this.db.exec("rollback"),a}}async transitionSharedContextImport(t){this.throwBeforeWrite(),this.db.exec("begin immediate");try{let n=uH(this.db,{sessionID:t.sessionID,type:"v4/shared_context_import"}).find(l=>{let u=l.data;return!!(u&&typeof u=="object"&&!Array.isArray(u)&&u.contextId===t.contextId)});if(!n)return this.db.exec("rollback"),!1;let o=n.data;if(!(Array.isArray(t.expectedStatus)?t.expectedStatus:[t.expectedStatus]).includes(o.status))return this.db.exec("rollback"),!1;tM(this.db,{...n,time:{...n.time,updated:Date.now()},data:{...o,status:t.status,...t.sourceId?{sourceId:t.sourceId}:{}}});let a=(await hRe(this.db,{sessionID:t.sessionID})).find(l=>{let u=l.info.metadata;return!!(u&&typeof u=="object"&&u.contextId===t.contextId)});return a&&await pH(this.db,{...a.info,metadata:{...a.info.metadata??{},sharedContextStatus:t.status}}),this.db.exec("commit"),!0}catch(n){throw this.db.exec("rollback"),n}}async updateSession(t){return this.throwBeforeWrite(),Xet(this.db,t)}async getSession(t){return Vte(this.db,t)}async listSessions(t={}){return qSr(this.db,t)}async claimLegacySessionWorkspace(t){return this.throwBeforeWrite(),WSr(this.db,t)}async repairLegacyRemoteSessionWorkspace(t){return this.throwBeforeWrite(),VSr(this.db,t)}async repairRemoteSessionPaths(t){return this.throwBeforeWrite(),HSr(this.db,t)}async saveMessage(t,n){return this.throwBeforeWrite(),pH(this.db,t,n)}async removeMessage(t){return this.throwBeforeWrite(),mkr(this.db,t)}async savePart(t,n){return this.throwBeforeWrite(),pme(this.db,t,n)}async removePart(t){return this.throwBeforeWrite(),gkr(this.db,t)}async messageWithParts(t){return _kr(this.db,t)}async messages(t){return hRe(this.db,t)}async saveSessionEntry(t){return this.throwBeforeWrite(),tM(this.db,t)}async sessionEntries(t){return uH(this.db,t)}async saveSessionInput(t){return this.throwBeforeWrite(),ZQt(this.db,t)}async commitPermissionFullAccess(t){return this.throwBeforeWrite(),YSr(this.db,t)}async updateSessionInputs(t){return this.throwBeforeWrite(),Fkr(this.db,t)}async promoteSessionInput(t){return this.throwBeforeWrite(),jkr(this.db,t)}async markSessionInputPromoted(t){return this.throwBeforeWrite(),Bkr(this.db,t)}async settleSessionInput(t){return this.throwBeforeWrite(),Ukr(this.db,t)}async listSessionInputs(t){return zkr(this.db,t)}async getSessionInputById(t){return $kr(this.db,t)}async readTodos(t){return Vkr(this.db,t)}async updateTodos(t){return this.throwBeforeWrite(),Hkr(this.db,t)}async readTarget(t){return JR(this.db,t)}async setTarget(t){return ewr(this.db,{objective:t.objective,sessionID:t.sessionID,status:t.status??"active",tokenBudget:t.tokenBudget})}async cloneTargetForFork(t){return this.throwBeforeWrite(),DQt(this.db,{source:t.source,sessionID:t.sessionID,status:t.status??t.source.status})}async createTarget(t){return twr(this.db,t)}async updateTargetStatus(t){return nwr(this.db,t)}async startTargetRun(t){return rwr(this.db,t)}async heartbeatTargetRun(t){return owr(this.db,t)}async finishTargetRun(t){return iwr(this.db,t)}async recoverInterruptedTargetRun(t){return swr(this.db,t)}async accountTargetUsage(t){return awr(this.db,t)}async updateTargetSummaryTitle(t){return cwr(this.db,t)}async clearTarget(t){return lwr(this.db,t)}async recordModelUsage(t){return Kkr(this.db,t)}async upsertTurnUsage(t){return Zkr(this.db,t)}async upsertToolUsage(t){return Ykr(this.db,t)}async pruneUsage(t){return gRe(this.db,t)}async queryAppUsage(t){return Xkr(this.db,t)}async queryTaskUsage(t){return Qkr(this.db,t)}async recordInputHistory(t){return okr(this.db,t)}async recallPreviousInputHistory(t){return qQt(this.db,t)}async getProjectPermission(t){return VQt(this.db,t)}async saveProjectPermission(t){return akr(this.db,t)}getProjectPermissionMode(t){return ckr(this.db,t)}saveProjectPermissionMode(t){return lkr(this.db,t)}async setRevert(t){return GSr(this.db,t)}async clearRevert(t){return JSr(this.db,t)}async upsertScriptWorkflowDefinition(t){return Pkr(this.db,t)}async createScriptWorkflowRun(t){return Rkr(this.db,t)}async updateScriptWorkflowRun(t){return Dkr(this.db,t)}async getScriptWorkflowRun(t){return utt(this.db,t)}async listScriptWorkflowRuns(t){return Okr(this.db,t)}async createScriptWorkflowActivity(t){return bkr(this.db,t)}async updateScriptWorkflowActivity(t){return Skr(this.db,t)}async findCachedScriptWorkflowActivity(t){return wkr(this.db,t)}async listScriptWorkflowActivities(t){return kkr(this.db,t)}async appendScriptWorkflowEvent(t){return xkr(this.db,t)}async listScriptWorkflowEvents(t){return Tkr(this.db,t)}async createSessionTaskLink(t){return Ikr(this.db,t)}workflowJournalStore(){return this.dwfJournalStore??=zQt(this.db),this.dwfJournalStore}debugMigrationIds(){return Bwr(this.db)}debugCounts(t){return Uwr(this.db,t)}};r(dtt,"openStartupSqliteSessionStore")});var ixr=Y(()=>{"use strict";oxr();$Qt();ett()});async function gas(e,t){await e.writeFile(t,"utf8")}function pxr(){return YQt===void 0&&(YQt=Math.round(Date.now()-(0,yRe.uptime)()*1e3)),YQt}async function _as(e){if(e===process.pid)return pxr();try{if(process.platform==="linux"){let t=await(0,J0.readFile)(`/proc/${e}/stat`,"utf8"),n=t.lastIndexOf(")");if(n<0)return null;let o=t.slice(n+2).split(" "),s=Number(o[19]);if(!Number.isFinite(s))return null;let a=Date.now()-(0,yRe.uptime)()*1e3;return Math.round(a+s*1e3/has)}if(process.platform==="darwin"){let{stdout:t}=await sxr("ps",["-o","lstart=","-p",String(e)]),n=Date.parse(t.trim());return Number.isFinite(n)?n:null}if(process.platform==="win32"){let{stdout:t}=await sxr("powershell.exe",["-NoProfile","-Command",`[DateTimeOffset]::new((Get-Process -Id ${e}).StartTime).ToUnixTimeMilliseconds()`]),n=Number(t.trim());return Number.isFinite(n)?n:null}return null}catch{return null}}async function yas(e={}){let t=(0,hw.resolve)(e.homeDir??(0,yRe.homedir)()),n=(0,hw.resolve)(e.userConfigPath??(0,hw.join)(t,".zcode","cli","config.json")),o=await was(n),s=fxr(o.storage)?o.storage:{},a=typeof s.dir=="string"?s.dir.trim():"",l=a?kas(a,t):(0,hw.join)(t,".zcode");return(0,hw.join)(l,pas,fas)}async function mme(e={}){return vas({...e,filePath:await yas(e)})}function vas(e){return new XQt(e)}async function bas(e,t,n,o){for(let s=0;;s+=1)try{await e(t,n);return}catch(a){let l=o[s];if(l===void 0||!Sas(a))throw a;await(0,dxr.setTimeout)(l)}}function Sas(e){if(!(e instanceof Error)||!("code"in e))return!1;let t=e.code;return t==="EPERM"||t==="EBUSY"||t==="EACCES"}async function was(e){try{let t=JSON.parse(await(0,J0.readFile)(e,"utf8"));return fxr(t)?t:{}}catch(t){if(_Re(t,"ENOENT"))return{};throw new Error(`Unable to read trusted user config for Workspace Hook Trust store: ${e}`,{cause:t})}}function kas(e,t){return e.startsWith("~/")?(0,hw.join)(t,e.slice(2)):(0,hw.isAbsolute)(e)?(0,hw.resolve)(e):(0,hw.resolve)(t,e)}function fme(e){return`${e.workspaceIdentity}\0${e.hookDeclarationDigest}`}function axr(e){return Date.parse(e.lastUsedAt??e.grantedAt)}function fxr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _Re(e,t){return e instanceof Error&&"code"in e&&e.code===t}function xas(e){return new Promise(t=>setTimeout(t,e))}var J0,cxr,lxr,uxr,yRe,hw,dxr,cas,las,uas,das,pas,fas,mas,has,sxr,YQt,XQt,mxr=Y(()=>{"use strict";J0=require("node:fs/promises"),cxr=require("node:child_process"),lxr=require("node:util"),uxr=require("node:crypto"),yRe=require("node:os"),hw=require("node:path"),dxr=require("node:timers/promises");nr();cas=5e3,las=3e4,uas=10,das=[50,100,200,400,800],pas="security",fas="workspace-hook-trust-v1.json",mas=2e3,has=100,sxr=(0,lxr.promisify)(cxr.execFile);r(gas,"defaultWriteLockOwnerMetadata");r(pxr,"currentProcessStartTimeMs");r(_as,"probeProcessStartTimeDefault");r(yas,"resolveWorkspaceHookTrustStorePath");r(mme,"createDefaultFileWorkspaceHookTrustStore");r(vas,"createFileWorkspaceHookTrustStore");XQt=class{static{r(this,"FileWorkspaceHookTrustStore")}filePath;lockPath;now;lockTimeoutMs;staleLockMs;beforeRename;renameFile;renameRetryDelaysMs;probeProcessStartTime;writeLockOwnerMetadata;mutationQueue=Promise.resolve();constructor(t){this.filePath=(0,hw.resolve)(t.filePath),this.lockPath=`${this.filePath}.lock`,this.now=t.now??Date.now,this.lockTimeoutMs=t.lockTimeoutMs??cas,this.staleLockMs=t.staleLockMs??las,this.beforeRename=t.beforeRename,this.renameFile=t.renameFile??J0.rename,this.renameRetryDelaysMs=t.renameRetryDelaysMs??das,this.probeProcessStartTime=t.probeProcessStartTime??_as,this.writeLockOwnerMetadata=t.writeLockOwnerMetadata??gas}load(){return this.enqueue(async()=>(await this.ensureSecurityDirectory(),this.withLock(()=>this.readCurrent(!0))))}grant(t){let n=t.map(o=>QV.parse(o));return this.mutate(o=>{let s=new Map(o.records.map(a=>[fme(a),a]));for(let a of n)s.set(fme(a),a);return{schemaVersion:XV,records:[...s.values()]}})}revoke(t){if(t.hookDeclarationDigests?.length===0)return Promise.reject(new Error("hookDeclarationDigests must be undefined or non-empty"));let n=t.hookDeclarationDigests?new Set(t.hookDeclarationDigests):void 0;return this.mutate(o=>({schemaVersion:XV,records:o.records.filter(s=>s.workspaceIdentity!==t.workspaceIdentity||n!==void 0&&!n.has(s.hookDeclarationDigest))}))}touch(t){let n=new Set(t.hookDeclarationDigests),o=t.usedAt??new Date(this.now()).toISOString();return this.mutate(s=>({schemaVersion:XV,records:s.records.map(a=>a.workspaceIdentity===t.workspaceIdentity&&n.has(a.hookDeclarationDigest)?{...a,lastUsedAt:o}:a)}))}compact(t){if(!Number.isFinite(t.maxAgeMs)||t.maxAgeMs<0)throw new Error("maxAgeMs must be a nonnegative finite number");if(!Number.isInteger(t.maxRecords)||t.maxRecords<1)throw new Error("maxRecords must be a positive integer");let n=t.now??this.now(),o=new Set(t.current.map(s=>fme({workspaceIdentity:s.workspaceIdentity,hookDeclarationDigest:s.hookDeclarationDigest})));return this.mutate(s=>{let a=s.records.filter(g=>{if(o.has(fme(g)))return!0;let _=Date.parse(g.lastUsedAt??g.grantedAt);return Number.isFinite(_)&&n-_<=t.maxAgeMs}),l=a.filter(g=>o.has(fme(g))),u=a.filter(g=>!o.has(fme(g))).sort((g,_)=>axr(_)-axr(g)),f=Math.max(0,t.maxRecords-l.length);return{schemaVersion:XV,records:[...l,...u.slice(0,f)]}})}mutate(t){return this.enqueue(async()=>(await this.ensureSecurityDirectory(),this.withLock(async()=>{let n=await this.readCurrent(!0),o={schemaVersion:XV,records:n.status==="ok"?n.records:[]},s=$Qe.parse(t(o));return await this.atomicWrite(s),s})))}enqueue(t){let n=this.mutationQueue.then(t,t);return this.mutationQueue=n.then(()=>{},()=>{}),n}async withLock(t){let{handle:n,token:o}=await this.acquireLock();try{return await t()}finally{await n.close().catch(()=>{}),await this.releaseLockIfOwned(o)}}async acquireLock(){let t=Date.now();for(;;){let n;try{n=await(0,J0.open)(this.lockPath,"wx",384);let o=(0,uxr.randomUUID)(),s=`${JSON.stringify({pid:process.pid,startTime:pxr(),token:o})}
|
|
1896
|
+
order by started_at asc, id asc`).all(t.sessionID),o=0,s=0,a=0,l=0,u=0,f=0,g=0,_={};for(let b of n){let w=Number(b.providerTotalTokens??b.computedTotalTokens??0),T=oas(b),I=ias(b.querySource),E=I===void 0?T:Math.max(0,T-(_[I]??0));I!==void 0&&(_[I]=T);let R=Math.max(0,w-T),L=Number(b.outputTokens??0),U=Number(b.reasoningTokens??0);o+=E+R,s+=E,a+=L,l+=U,I===void 0&&(u+=Number(b.cacheCreationTokens??0),f+=Number(b.cacheReadTokens??0)),b.status==="error"&&(g+=1)}return{sessionID:t.sessionID,totalTokens:o,inputTokens:s,outputTokens:a,reasoningTokens:l,cacheCreationTokens:u,cacheReadTokens:f,modelRequestCount:n.length,modelErrorCount:g,inputBaselineBySource:_}}function ras(e,t,n){let o=Ih(e);return o>0?o:Ih(t)+Ih(n)}function oas(e){let t=Ih(e.inputTokens),n=Ih(e.cacheCreationTokens)+Ih(e.cacheReadTokens);if(t<=0)return n;if(n<=0)return t;let o=Ih(e.outputTokens),s=Ih(e.providerTotalTokens??e.computedTotalTokens);if(s>0){let a=Math.abs(s-(t+o));if(Math.abs(s-(t+n+o))<a)return t+n}return t}function ias(e){if(e==="main_turn"||e==="subagent"||e==="workflow_child")return e}function Ih(e){return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.trunc(e))}function p3(e){return e?1:0}function Jkr(e){return e===void 0?null:p3(e)}var eas,tas,exr=Y(()=>{"use strict";bA();eas=30,tas=eas*24*60*60*1e3;r(Kkr,"recordModelUsage");r(Zkr,"upsertTurnUsage");r(Ykr,"upsertToolUsage");r(gRe,"pruneUsage");r(nas,"toolUsageValues");r(Xkr,"queryAppUsage");r(Qkr,"queryTaskUsage");r(ras,"inputSideTokensFromNormalizedUsage");r(oas,"inputSideTokensFromStoredUsage");r(ias,"taskUsageInputBaselineSource");r(Ih,"integer");r(p3,"boolean");r(Jkr,"nullableBoolean")});function txr(e){if(!e.data||typeof e.data!="object"||Array.isArray(e.data))return null;let t=e.data.ack;if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t.result;if(!n||typeof n!="object"||Array.isArray(n))return null;let o=n.sessionId;return typeof o=="string"&&o.length>0?o:null}function aas(e){let t=String(e.child.id),n=e.commandFact.ack.result,o=n&&typeof n=="object"&&!Array.isArray(n)?n:null,s=typeof o?.sessionId=="string"?o.sessionId.trim():"";if(!(o?.type==="forkAssistant"||o?.type==="createSelectionSideSession"||o?.type==="editUserQuery"&&o.disposition==="fork")||!s||s!==t)throw new Error("Fork bundle command result is missing, invalid, or not child-local");let l=new Set(e.messages.map(g=>String(g.info.id))),u=r((g,_)=>{if(typeof g=="string"&&!l.has(g))throw new Error(`Fork bundle ${_} is not child-local: ${g}`)},"assertMessage"),f=new Set;e.goal&&f.add(e.goal.source.targetID);for(let g of e.messages){if(String(g.info.sessionID)!==t)throw new Error("Fork bundle message session is not child-local");if(g.info.role==="assistant"&&!l.has(String(g.info.parentID)))throw new Error("Fork bundle assistant parent is not child-local");let _=g.info.anchor;for(let b of _?.orderedMessageIds??[])u(b,"anchor orderedMessageId");if(u(_?.boundaryMessageId,"anchor boundaryMessageId"),_?.goalBoundary?.kind==="snapshot"){if(String(_.goalBoundary.target.sessionID)!==t)throw new Error("Fork bundle anchor goal session is not child-local");f.add(_.goalBoundary.target.targetID)}for(let b of g.parts){if(String(b.sessionID)!==t||String(b.messageID)!==String(g.info.id))throw new Error("Fork bundle part owner is not child-local");if(b.type==="timeline"&&(u(b.anchorMessageId,"timeline anchorMessageId"),b.timelineType==="context_compaction"&&u(b.summaryMessageId,"timeline summaryMessageId"),b.timelineType==="goal_verification"&&f.add(b.targetId)),b.type==="compaction"){u(b.tail_start_id,"compaction tail_start_id"),u(b.summaryMessageId,"compaction summaryMessageId");let w=b.compactBoundary;u(w?.lastSummarizedMessageId,"compact lastSummarizedMessageId");for(let T of w?.summaryMessageIds??[])u(T,"compact summaryMessageId");for(let T of w?.attachmentMessageIds??[])u(T,"compact attachmentMessageId");for(let T of w?.hookResultMessageIds??[])u(T,"compact hookResultMessageId");u(w?.preservedSegment?.headMessageId,"compact preserved head"),u(w?.preservedSegment?.anchorMessageId,"compact preserved anchor"),u(w?.preservedSegment?.tailMessageId,"compact preserved tail")}if(b.type==="tool"&&b.state.status==="completed"){for(let w of b.state.attachments??[])if(String(w.sessionID)!==t||String(w.messageID)!==String(g.info.id))throw new Error("Fork bundle tool attachment owner is not child-local")}}}if(e.goal&&String(e.goal.source.sessionID)!==t)throw new Error("Fork bundle goal session is not child-local");for(let g of e.entries){if(String(g.sessionID)!==t)throw new Error("Fork bundle verifier entry session is not child-local");let _=g.data&&typeof g.data=="object"&&!Array.isArray(g.data)?g.data:{},b=_.payload&&typeof _.payload=="object"&&!Array.isArray(_.payload)?_.payload:{};if(u(b.anchorAssistantMessageId,"verifier assistant anchor"),typeof b.targetId=="string"&&!f.has(b.targetId))throw new Error("Fork bundle verifier target is not child-local")}}function dtt(e={}){return new fH(e)}var rxr,nxr,fH,oxr=Y(()=>{"use strict";XSr();rxr=require("node:sqlite");pwr();ett();Nwr();jwr();gfe();zwr();$Qt();skr();pkr();HQt();Akr();Nkr();Qet();Wkr();mRe();Gkr();exr();r(txr,"forkChildSessionId");r(aas,"assertForkBundleChildLocal");nxr=Symbol("deferredSqliteStartup"),fH=class e{static{r(this,"SqliteSessionStore")}db;dbPath;forkCommitFaultAt;dwfJournalStore;constructor(t={},n){this.dbPath=t.dbPath??MQt(),this.forkCommitFaultAt=t.forkCommitFaultAt;let o=t.startupLockTimeoutMs??ntt;try{Fwr(this.dbPath),xb({operation:"sqliteOpen",path:this.dbPath}),this.db=new rxr.DatabaseSync(this.dbPath,{timeout:o})}catch(s){throw new aF(`Failed to open SQLite session database at ${this.dbPath}`,{cause:s,dbPath:this.dbPath,kind:"open_failed"})}try{n!==nxr&&(Cwr(this.db,this.dbPath,o),this.db.exec("pragma busy_timeout = 10000"),require(require("node:path").join(__dirname,"cli-config.cjs")).installSqliteWriteRecovery(this))}catch(s){try{this.db.close()}catch{}throw s}}static async openStartup(t={},n={}){let o=new e(t,nxr);try{return await Ewr(o.db,o.dbPath,n),o.db.exec("pragma busy_timeout = 10000"),require(require("node:path").join(__dirname,"cli-config.cjs")).installSqliteWriteRecovery(o),o}catch(s){try{o.close()}catch{}throw s}}getDatabasePath(){return this.dbPath}close(){this.db.close()}throwBeforeWrite(){xb({operation:"sqliteRun",path:this.dbPath})}maybeThrowForkCommitFault(t){if(this.forkCommitFaultAt===t)throw new Error(`injected fork commit fault: ${t}`)}async createSession(t){return this.throwBeforeWrite(),fRe(this.db,t)}async createForkedSessionWithMetadata(t,n){if(this.throwBeforeWrite(),!t.parentID||String(t.parentID)!==n.parentSessionId)throw new Error("Fork child metadata parent does not match session parentID");let o=n.forkTarget.orderedMessageIds,s=n.forkTarget.boundaryMessageId.trim().length>0&&(o.length===0||o.at(-1)===n.forkTarget.boundaryMessageId);if(!n.sourceCommandId.trim()||!s)throw new Error("Fork child metadata is invalid");let a=`v4_command_fact:child:${n.parentSessionId}:${n.sourceCommandId}`;this.db.exec("begin immediate");try{let l=uH(this.db,{sessionID:t.parentID,type:"v4/command_fact"}).find(g=>g.id===a);if(l){let g=txr(l);if(!g)throw new Error(`Fork child command fact is corrupt: ${a}`);let _=Vte(this.db,g);if(!_)throw new Error(`Fork child session is missing: ${g}`);return this.db.exec("commit"),_}let u=fRe(this.db,t),f=Date.now();return tM(this.db,{id:a,sessionID:t.parentID,type:"v4/command_fact",time:{created:f,updated:f},data:{source:"child",ack:{commandId:n.sourceCommandId,status:"accepted",revisionAtDecision:0,result:{type:"forkAssistant",sessionId:String(u.id)}},metadata:n}}),this.db.exec("commit"),u}catch(l){throw this.db.exec("rollback"),l}}async commitForkBundle(t){this.throwBeforeWrite();let{child:n,commandFact:o,initialInput:s}=t;if(!n.parentID||String(n.parentID)!==o.parentSessionId||s&&String(s.sessionID)!==String(n.id)||o.ack.commandId!==o.sourceCommandId)throw new Error("Fork commit bundle identity is invalid");let a=`v4_command_fact:child:${o.parentSessionId}:${o.sourceCommandId}`;this.db.exec("begin immediate");try{let l=uH(this.db,{sessionID:n.parentID,type:"v4/command_fact"}).find(g=>g.id===a);if(l){let g=txr(l),_=g?Vte(this.db,g):null;if(!_)throw new Error(`Fork bundle command fact is corrupt: ${a}`);return this.db.exec("commit"),_}aas(t);let u=fRe(this.db,n);this.maybeThrowForkCommitFault("afterChild");for(let g of t.messages){let _=t.copySources?.messages[g.info.id];await pH(this.db,g.info,_?{sessionID:n.parentID,id:_}:void 0);for(let b of g.parts){let w=t.copySources?.parts[b.id];await pme(this.db,b,w?{sessionID:n.parentID,id:w}:void 0)}}this.maybeThrowForkCommitFault("afterMessages"),t.goal&&DQt(this.db,{source:t.goal.source,sessionID:n.id,status:t.goal.status}),this.maybeThrowForkCommitFault("afterGoal");for(let g of t.entries)tM(this.db,g);this.maybeThrowForkCommitFault("afterEntries"),s&&await ZQt(this.db,s),this.maybeThrowForkCommitFault("afterInput");let f=Date.now();return tM(this.db,{id:a,sessionID:n.parentID,type:"v4/command_fact",time:{created:f,updated:f},data:{source:"child",ack:o.ack,metadata:o.metadata}}),this.maybeThrowForkCommitFault("afterCommandFact"),this.maybeThrowForkCommitFault("beforeCommit"),this.db.exec("commit"),u}catch(l){throw this.db.exec("rollback"),l}}async commitSharedContextImportBundle(t){this.throwBeforeWrite();let{session:n,contextMessage:o,provenance:s}=t;if(String(o.info.sessionID)!==String(n.id)||String(s.sessionID)!==String(n.id)||!s.id.includes(String(n.id))||o.info.role!=="user"||o.info.visibility!=="model-only"||o.info.source!=="shared_context")throw new Error("Shared context import bundle identity is invalid");this.db.exec("begin immediate");try{let a=Vte(this.db,n.id);if(a){if(!uH(this.db,{sessionID:n.id,type:s.type}).find(f=>f.id===s.id))throw new Error("Shared context import session is incomplete");return this.db.exec("commit"),a}let l=fRe(this.db,n);await pH(this.db,o.info);for(let u of o.parts)await pme(this.db,u);return tM(this.db,s),this.db.exec("commit"),l}catch(a){throw this.db.exec("rollback"),a}}async transitionSharedContextImport(t){this.throwBeforeWrite(),this.db.exec("begin immediate");try{let n=uH(this.db,{sessionID:t.sessionID,type:"v4/shared_context_import"}).find(l=>{let u=l.data;return!!(u&&typeof u=="object"&&!Array.isArray(u)&&u.contextId===t.contextId)});if(!n)return this.db.exec("rollback"),!1;let o=n.data;if(!(Array.isArray(t.expectedStatus)?t.expectedStatus:[t.expectedStatus]).includes(o.status))return this.db.exec("rollback"),!1;tM(this.db,{...n,time:{...n.time,updated:Date.now()},data:{...o,status:t.status,...t.sourceId?{sourceId:t.sourceId}:{}}});let a=(await hRe(this.db,{sessionID:t.sessionID})).find(l=>{let u=l.info.metadata;return!!(u&&typeof u=="object"&&u.contextId===t.contextId)});return a&&await pH(this.db,{...a.info,metadata:{...a.info.metadata??{},sharedContextStatus:t.status}}),this.db.exec("commit"),!0}catch(n){throw this.db.exec("rollback"),n}}async updateSession(t){return this.throwBeforeWrite(),Xet(this.db,t)}async getSession(t){return Vte(this.db,t)}async listSessions(t={}){return qSr(this.db,t)}async claimLegacySessionWorkspace(t){return this.throwBeforeWrite(),WSr(this.db,t)}async repairLegacyRemoteSessionWorkspace(t){return this.throwBeforeWrite(),VSr(this.db,t)}async repairRemoteSessionPaths(t){return this.throwBeforeWrite(),HSr(this.db,t)}async saveMessage(t,n){return this.throwBeforeWrite(),pH(this.db,t,n)}async removeMessage(t){return this.throwBeforeWrite(),mkr(this.db,t)}async savePart(t,n){return this.throwBeforeWrite(),pme(this.db,t,n)}async removePart(t){return this.throwBeforeWrite(),gkr(this.db,t)}async messageWithParts(t){return _kr(this.db,t)}async messages(t){return hRe(this.db,t)}async saveSessionEntry(t){return this.throwBeforeWrite(),tM(this.db,t)}async sessionEntries(t){return uH(this.db,t)}async saveSessionInput(t){return this.throwBeforeWrite(),ZQt(this.db,t)}async commitPermissionFullAccess(t){return this.throwBeforeWrite(),YSr(this.db,t)}async updateSessionInputs(t){return this.throwBeforeWrite(),Fkr(this.db,t)}async promoteSessionInput(t){return this.throwBeforeWrite(),jkr(this.db,t)}async markSessionInputPromoted(t){return this.throwBeforeWrite(),Bkr(this.db,t)}async settleSessionInput(t){return this.throwBeforeWrite(),Ukr(this.db,t)}async listSessionInputs(t){return zkr(this.db,t)}async getSessionInputById(t){return $kr(this.db,t)}async readTodos(t){return Vkr(this.db,t)}async updateTodos(t){return this.throwBeforeWrite(),Hkr(this.db,t)}async readTarget(t){return JR(this.db,t)}async setTarget(t){return ewr(this.db,{objective:t.objective,sessionID:t.sessionID,status:t.status??"active",tokenBudget:t.tokenBudget})}async cloneTargetForFork(t){return this.throwBeforeWrite(),DQt(this.db,{source:t.source,sessionID:t.sessionID,status:t.status??t.source.status})}async createTarget(t){return twr(this.db,t)}async updateTargetStatus(t){return nwr(this.db,t)}async startTargetRun(t){return rwr(this.db,t)}async heartbeatTargetRun(t){return owr(this.db,t)}async finishTargetRun(t){return iwr(this.db,t)}async recoverInterruptedTargetRun(t){return swr(this.db,t)}async accountTargetUsage(t){return awr(this.db,t)}async updateTargetSummaryTitle(t){return cwr(this.db,t)}async clearTarget(t){return lwr(this.db,t)}async recordModelUsage(t){return Kkr(this.db,t)}async upsertTurnUsage(t){return Zkr(this.db,t)}async upsertToolUsage(t){return Ykr(this.db,t)}async pruneUsage(t){return gRe(this.db,t)}async queryAppUsage(t){return Xkr(this.db,t)}async queryTaskUsage(t){return Qkr(this.db,t)}async recordInputHistory(t){return okr(this.db,t)}async recallPreviousInputHistory(t){return qQt(this.db,t)}async getProjectPermission(t){return VQt(this.db,t)}async saveProjectPermission(t){return akr(this.db,t)}getProjectPermissionMode(t){return ckr(this.db,t)}saveProjectPermissionMode(t){return lkr(this.db,t)}async setRevert(t){return GSr(this.db,t)}async clearRevert(t){return JSr(this.db,t)}async upsertScriptWorkflowDefinition(t){return Pkr(this.db,t)}async createScriptWorkflowRun(t){return Rkr(this.db,t)}async updateScriptWorkflowRun(t){return Dkr(this.db,t)}async getScriptWorkflowRun(t){return utt(this.db,t)}async listScriptWorkflowRuns(t){return Okr(this.db,t)}async createScriptWorkflowActivity(t){return bkr(this.db,t)}async updateScriptWorkflowActivity(t){return Skr(this.db,t)}async findCachedScriptWorkflowActivity(t){return wkr(this.db,t)}async listScriptWorkflowActivities(t){return kkr(this.db,t)}async appendScriptWorkflowEvent(t){return xkr(this.db,t)}async listScriptWorkflowEvents(t){return Tkr(this.db,t)}async createSessionTaskLink(t){return Ikr(this.db,t)}workflowJournalStore(){return this.dwfJournalStore??=zQt(this.db),this.dwfJournalStore}debugMigrationIds(){return Bwr(this.db)}debugCounts(t){return Uwr(this.db,t)}};r(dtt,"openStartupSqliteSessionStore")});var ixr=Y(()=>{"use strict";oxr();$Qt();ett()});async function gas(e,t){await e.writeFile(t,"utf8")}function pxr(){return YQt===void 0&&(YQt=Math.round(Date.now()-(0,yRe.uptime)()*1e3)),YQt}async function _as(e){if(e===process.pid)return pxr();try{if(process.platform==="linux"){let t=await(0,J0.readFile)(`/proc/${e}/stat`,"utf8"),n=t.lastIndexOf(")");if(n<0)return null;let o=t.slice(n+2).split(" "),s=Number(o[19]);if(!Number.isFinite(s))return null;let a=Date.now()-(0,yRe.uptime)()*1e3;return Math.round(a+s*1e3/has)}if(process.platform==="darwin"){let{stdout:t}=await sxr("ps",["-o","lstart=","-p",String(e)]),n=Date.parse(t.trim());return Number.isFinite(n)?n:null}if(process.platform==="win32"){let{stdout:t}=await sxr("powershell.exe",["-NoProfile","-Command",`[DateTimeOffset]::new((Get-Process -Id ${e}).StartTime).ToUnixTimeMilliseconds()`]),n=Number(t.trim());return Number.isFinite(n)?n:null}return null}catch{return null}}async function yas(e={}){let t=(0,hw.resolve)(e.homeDir??(0,yRe.homedir)()),n=(0,hw.resolve)(e.userConfigPath??(process.env.ZCODE_CLI_SETTINGS_FILE?.trim()||(0,hw.join)(t,".zcode","cli","config.json"))),o=await was(n),s=fxr(o.storage)?o.storage:{},a=typeof s.dir=="string"?s.dir.trim():"",l=a?kas(a,t):(0,hw.join)(t,".zcode");return(0,hw.join)(l,pas,fas)}async function mme(e={}){return vas({...e,filePath:await yas(e)})}function vas(e){return new XQt(e)}async function bas(e,t,n,o){for(let s=0;;s+=1)try{await e(t,n);return}catch(a){let l=o[s];if(l===void 0||!Sas(a))throw a;await(0,dxr.setTimeout)(l)}}function Sas(e){if(!(e instanceof Error)||!("code"in e))return!1;let t=e.code;return t==="EPERM"||t==="EBUSY"||t==="EACCES"}async function was(e){try{let t=JSON.parse(await(0,J0.readFile)(e,"utf8"));return fxr(t)?t:{}}catch(t){if(_Re(t,"ENOENT"))return{};throw new Error(`Unable to read trusted user config for Workspace Hook Trust store: ${e}`,{cause:t})}}function kas(e,t){return e.startsWith("~/")?(0,hw.join)(t,e.slice(2)):(0,hw.isAbsolute)(e)?(0,hw.resolve)(e):(0,hw.resolve)(t,e)}function fme(e){return`${e.workspaceIdentity}\0${e.hookDeclarationDigest}`}function axr(e){return Date.parse(e.lastUsedAt??e.grantedAt)}function fxr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _Re(e,t){return e instanceof Error&&"code"in e&&e.code===t}function xas(e){return new Promise(t=>setTimeout(t,e))}var J0,cxr,lxr,uxr,yRe,hw,dxr,cas,las,uas,das,pas,fas,mas,has,sxr,YQt,XQt,mxr=Y(()=>{"use strict";J0=require("node:fs/promises"),cxr=require("node:child_process"),lxr=require("node:util"),uxr=require("node:crypto"),yRe=require("node:os"),hw=require("node:path"),dxr=require("node:timers/promises");nr();cas=5e3,las=3e4,uas=10,das=[50,100,200,400,800],pas="security",fas="workspace-hook-trust-v1.json",mas=2e3,has=100,sxr=(0,lxr.promisify)(cxr.execFile);r(gas,"defaultWriteLockOwnerMetadata");r(pxr,"currentProcessStartTimeMs");r(_as,"probeProcessStartTimeDefault");r(yas,"resolveWorkspaceHookTrustStorePath");r(mme,"createDefaultFileWorkspaceHookTrustStore");r(vas,"createFileWorkspaceHookTrustStore");XQt=class{static{r(this,"FileWorkspaceHookTrustStore")}filePath;lockPath;now;lockTimeoutMs;staleLockMs;beforeRename;renameFile;renameRetryDelaysMs;probeProcessStartTime;writeLockOwnerMetadata;mutationQueue=Promise.resolve();constructor(t){this.filePath=(0,hw.resolve)(t.filePath),this.lockPath=`${this.filePath}.lock`,this.now=t.now??Date.now,this.lockTimeoutMs=t.lockTimeoutMs??cas,this.staleLockMs=t.staleLockMs??las,this.beforeRename=t.beforeRename,this.renameFile=t.renameFile??J0.rename,this.renameRetryDelaysMs=t.renameRetryDelaysMs??das,this.probeProcessStartTime=t.probeProcessStartTime??_as,this.writeLockOwnerMetadata=t.writeLockOwnerMetadata??gas}load(){return this.enqueue(async()=>(await this.ensureSecurityDirectory(),this.withLock(()=>this.readCurrent(!0))))}grant(t){let n=t.map(o=>QV.parse(o));return this.mutate(o=>{let s=new Map(o.records.map(a=>[fme(a),a]));for(let a of n)s.set(fme(a),a);return{schemaVersion:XV,records:[...s.values()]}})}revoke(t){if(t.hookDeclarationDigests?.length===0)return Promise.reject(new Error("hookDeclarationDigests must be undefined or non-empty"));let n=t.hookDeclarationDigests?new Set(t.hookDeclarationDigests):void 0;return this.mutate(o=>({schemaVersion:XV,records:o.records.filter(s=>s.workspaceIdentity!==t.workspaceIdentity||n!==void 0&&!n.has(s.hookDeclarationDigest))}))}touch(t){let n=new Set(t.hookDeclarationDigests),o=t.usedAt??new Date(this.now()).toISOString();return this.mutate(s=>({schemaVersion:XV,records:s.records.map(a=>a.workspaceIdentity===t.workspaceIdentity&&n.has(a.hookDeclarationDigest)?{...a,lastUsedAt:o}:a)}))}compact(t){if(!Number.isFinite(t.maxAgeMs)||t.maxAgeMs<0)throw new Error("maxAgeMs must be a nonnegative finite number");if(!Number.isInteger(t.maxRecords)||t.maxRecords<1)throw new Error("maxRecords must be a positive integer");let n=t.now??this.now(),o=new Set(t.current.map(s=>fme({workspaceIdentity:s.workspaceIdentity,hookDeclarationDigest:s.hookDeclarationDigest})));return this.mutate(s=>{let a=s.records.filter(g=>{if(o.has(fme(g)))return!0;let _=Date.parse(g.lastUsedAt??g.grantedAt);return Number.isFinite(_)&&n-_<=t.maxAgeMs}),l=a.filter(g=>o.has(fme(g))),u=a.filter(g=>!o.has(fme(g))).sort((g,_)=>axr(_)-axr(g)),f=Math.max(0,t.maxRecords-l.length);return{schemaVersion:XV,records:[...l,...u.slice(0,f)]}})}mutate(t){return this.enqueue(async()=>(await this.ensureSecurityDirectory(),this.withLock(async()=>{let n=await this.readCurrent(!0),o={schemaVersion:XV,records:n.status==="ok"?n.records:[]},s=$Qe.parse(t(o));return await this.atomicWrite(s),s})))}enqueue(t){let n=this.mutationQueue.then(t,t);return this.mutationQueue=n.then(()=>{},()=>{}),n}async withLock(t){let{handle:n,token:o}=await this.acquireLock();try{return await t()}finally{await n.close().catch(()=>{}),await this.releaseLockIfOwned(o)}}async acquireLock(){let t=Date.now();for(;;){let n;try{n=await(0,J0.open)(this.lockPath,"wx",384);let o=(0,uxr.randomUUID)(),s=`${JSON.stringify({pid:process.pid,startTime:pxr(),token:o})}
|
|
1897
1897
|
`;return await this.writeLockOwnerMetadata(n,s),{handle:n,token:o}}catch(o){if(n&&(await n.close().catch(()=>{}),await(0,J0.unlink)(this.lockPath).catch(()=>{})),!_Re(o,"EEXIST"))throw o;if(await this.removeStaleLock(),Date.now()-t>=this.lockTimeoutMs)throw new Error(`Timed out acquiring Workspace Hook Trust store lock: ${this.lockPath}`);await xas(uas)}}}async releaseLockIfOwned(t){let n=await this.readLockOwner();!n||n.token!==t||await(0,J0.unlink)(this.lockPath).catch(()=>{})}async readLockOwner(){try{let t=JSON.parse(await(0,J0.readFile)(this.lockPath,"utf8"));return t&&typeof t=="object"&&typeof t.pid=="number"&&typeof t.token=="string"?{pid:t.pid,token:t.token,startTime:typeof t.startTime=="number"?t.startTime:void 0}:null}catch{return null}}isProcessAlive(t){if(t===process.pid)return!0;try{return process.kill(t,0),!0}catch(n){return _Re(n,"EPERM")}}async removeStaleLock(){try{let t=await(0,J0.stat)(this.lockPath);if(Date.now()-t.mtimeMs<=this.staleLockMs)return;let n=await this.readLockOwner();if(!n){await(0,J0.rm)(this.lockPath,{force:!0});return}if(n.pid===process.pid)return;if(!this.isProcessAlive(n.pid)){await(0,J0.rm)(this.lockPath,{force:!0});return}let o=await this.probeProcessStartTime(n.pid);if(o===null||n.startTime===void 0)return;Math.abs(o-n.startTime)>mas&&await(0,J0.rm)(this.lockPath,{force:!0})}catch(t){if(!_Re(t,"ENOENT"))throw t}}async ensureSecurityDirectory(){let t=(0,hw.dirname)(this.filePath);await(0,J0.mkdir)(t,{recursive:!0,mode:448}),await(0,J0.chmod)(t,448)}async readCurrent(t){let n;try{n=await(0,J0.readFile)(this.filePath,"utf8")}catch(o){if(_Re(o,"ENOENT"))return{status:"missing",records:[]};throw o}try{let o=$Qe.parse(JSON.parse(n));return await(0,J0.chmod)(this.filePath,384).catch(()=>{}),{status:"ok",records:o.records}}catch(o){if(!t)throw o;let s=`${this.filePath}.corrupt-${this.now()}`;try{await(0,J0.rename)(this.filePath,s),await(0,J0.chmod)(s,384).catch(()=>{})}catch{}return{status:"corrupt",records:[],recoveredCorruptPath:s}}}async atomicWrite(t){let n=(0,hw.dirname)(this.filePath),o=(0,hw.join)(n,`.${(0,hw.basename)(this.filePath)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`),s;try{s=await(0,J0.open)(o,"wx",384),await s.writeFile(`${JSON.stringify(t,null,2)}
|
|
1898
1898
|
`,"utf8"),await s.sync(),await s.close(),s=void 0,await this.beforeRename?.(),await bas(this.renameFile,o,this.filePath,this.renameRetryDelaysMs),await(0,J0.chmod)(this.filePath,384)}catch(a){throw await s?.close().catch(()=>{}),await(0,J0.rm)(o,{force:!0}).catch(()=>{}),a}}};r(bas,"renameWithRetry");r(Sas,"isRetryableRenameError");r(was,"readUserConfig");r(kas,"resolveTrustedUserPath");r(fme,"trustKey");r(axr,"recordTimestamp");r(fxr,"isRecord");r(_Re,"isNodeError");r(xas,"delay")});function yxr(e){return new QQt(e)}function Kte(e){return e.replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,120)||"unknown"}function vxr(e){switch(e.split(";")[0]?.trim().toLowerCase()??""){case"text/plain":return".txt";case"text/markdown":return".md";case"application/json":return".json";case"image/png":return".png";case"image/jpeg":case"image/jpg":return".jpg";case"image/gif":return".gif";case"image/webp":return".webp";case"application/pdf":return".pdf";default:return".json"}}function Tas(e){let t=vxr(e);return t===".json"&&!e.toLowerCase().includes("json")?".bin":t}function Ias(e){let n=(e.startsWith(".")?e:`.${e}`).replace(/[^a-zA-Z0-9.]/g,"").slice(0,16).toLowerCase();return/^\.[a-z0-9]+$/.test(n)?n:".bin"}function hxr(e){let t=e.toLowerCase();return t.endsWith(".txt")?"text/plain":t.endsWith(".md")?"text/markdown":t.endsWith(".png")?"image/png":t.endsWith(".jpg")||t.endsWith(".jpeg")?"image/jpeg":t.endsWith(".gif")?"image/gif":t.endsWith(".webp")?"image/webp":t.endsWith(".pdf")?"application/pdf":t.endsWith(".bin")?"application/octet-stream":t.endsWith(".html")||t.endsWith(".htm")?"text/html":t.endsWith(".csv")?"text/csv":t.endsWith(".svg")?"image/svg+xml":t.endsWith(".json")?"application/json":"application/octet-stream"}function Cas(e){return e==="application/json"||e.startsWith("text/")}function Eas(e){return e.byteLength>=5&&e[0]===37&&e[1]===80&&e[2]===68&&e[3]===70&&e[4]===45}function gxr(e,t,n,o,s){let{sessionId:a}=een(o),l=ptt(s),u=Aas(s);if(!l||!u)return;let f=l==="image"?e:l==="video"?n:t,g=(0,ftt.createHash)("sha256").update(o).digest("hex").slice(0,32);return(0,SA.join)(f,Kte(a),`${l}-${g}${u}`)}function ptt(e){let t=e.split(";")[0]?.trim().toLowerCase()??"";if(t.startsWith("image/"))return"image";if(t.startsWith("video/"))return"video";if(t==="application/pdf")return"pdf"}function Aas(e){switch(e.split(";")[0]?.trim().toLowerCase()){case"image/png":return".png";case"image/jpeg":case"image/jpg":return".jpg";case"image/gif":return".gif";case"image/webp":return".webp";case"video/mp4":return".mp4";case"video/quicktime":return".mov";case"video/webm":return".webm";case"video/x-matroska":return".mkv";case"video/x-m4v":return".m4v";case"video/x-msvideo":return".avi";case"application/pdf":return".pdf";default:return}}function Pas(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();if(ptt(a??"")!==n||s.at(-1)?.trim().toLowerCase()!=="base64"||o<0)throw new Error(`Media attachment artifact is not a base64 ${n} data URL: ${t}`);let l=Buffer.from(e.slice(o+1),"base64");if(l.byteLength===0)throw new Error(`Media attachment artifact is empty: ${t}`);return{bytes:l,mediaType:a}}async function _xr(e){try{return(await(0,dS.stat)(e)).isFile()}catch(t){if(t.code==="ENOENT")return!1;throw t}}function een(e){let t;try{t=new URL(e)}catch(s){throw new Error(`Invalid tool artifact URI: ${e}`,{cause:s instanceof Error?s:void 0})}if(t.protocol!=="zcode-artifact:")throw new Error(`Unsupported tool artifact URI: ${e}`);let n=decodeURIComponent(t.hostname),o=decodeURIComponent(t.pathname.replace(/^\/+/,""));if(!n||!o)throw new Error(`Invalid tool artifact URI: ${e}`);return{artifactId:o,sessionId:n}}var ftt,dS,SA,QQt,f3=Y(()=>{"use strict";ftt=require("node:crypto"),dS=require("node:fs/promises"),SA=require("node:path");gfe();ixr();nr();mxr();QQt=class{static{r(this,"NodeToolArtifactStore")}imageCacheRootDir;pdfCacheRootDir;rootDir;videoCacheRootDir;mediaAttachmentPathFlights=new Map;constructor(t){this.imageCacheRootDir=t.imageCacheRootDir,this.rootDir=t.rootDir,this.pdfCacheRootDir=t.pdfCacheRootDir??(0,SA.join)((0,SA.dirname)(t.rootDir),"pdf-cache"),this.videoCacheRootDir=t.videoCacheRootDir}async writeToolResultArtifact(t,n){if(n?.signal?.aborted)throw n.signal.reason instanceof Error?n.signal.reason:new Error("Tool artifact write cancelled");let o=`tool-result-${crypto.randomUUID()}`,s=t.contentType??"application/json",a=vxr(s),l=(0,SA.join)(this.rootDir,Kte(t.sessionId)),u=`${Kte(String(t.toolCallId))}-${o}${a}`,f=(0,SA.join)(l,u);return xb({operation:"mkdir",path:l}),await(0,dS.mkdir)(l,{recursive:!0}),xb({operation:"writeFile",path:f}),await(0,dS.writeFile)(f,t.content,"utf8"),{id:o,uri:`zcode-artifact://${encodeURIComponent(t.sessionId)}/${encodeURIComponent(o)}`,path:f,bytes:Buffer.byteLength(t.content,"utf8"),contentType:s,createdAt:new Date}}async writeToolResultBinaryArtifact(t,n){if(n?.signal?.aborted)throw n.signal.reason instanceof Error?n.signal.reason:new Error("Tool binary artifact write cancelled");let o=`tool-result-${crypto.randomUUID()}`,s=Ias(t.extension??Tas(t.contentType)),a=(0,SA.join)(this.rootDir,Kte(t.sessionId)),l=`${Kte(String(t.toolCallId))}-${o}${s}`,u=(0,SA.join)(a,l),f=Buffer.from(t.content);return xb({operation:"mkdir",path:a}),await(0,dS.mkdir)(a,{recursive:!0}),xb({operation:"writeFile",path:u}),await(0,dS.writeFile)(u,f),{id:o,uri:`zcode-artifact://${encodeURIComponent(t.sessionId)}/${encodeURIComponent(o)}`,path:u,bytes:f.byteLength,contentType:t.contentType,createdAt:new Date}}async readToolResultArtifact(t,n){if(n?.signal?.aborted)throw n.signal.reason instanceof Error?n.signal.reason:new Error("Tool artifact read cancelled");let{path:o,contentType:s,bytes:a}=await this.readArtifactFile(t.uri),l=Cas(s)?a.toString("utf8"):a.toString("base64");return{uri:t.uri,path:o,content:l,bytes:a.byteLength,contentType:s}}async readToolResultBinaryArtifact(t,n){if(n?.signal?.aborted)throw n.signal.reason instanceof Error?n.signal.reason:new Error("Tool artifact read cancelled");let{path:o,contentType:s,bytes:a}=await this.readArtifactFile(t.uri);return{uri:t.uri,path:o,bytes:new Uint8Array(a),contentType:s}}async readArtifactFile(t){let{artifactId:n,sessionId:o}=een(t),s=(0,SA.join)(this.rootDir,Kte(o)),l=(await(0,dS.readdir)(s)).find(f=>f.includes(n));if(!l)throw new Error(`Tool artifact not found: ${t}`);let u=(0,SA.join)(s,l);return{path:u,contentType:hxr(l),bytes:await(0,dS.readFile)(u)}}async statToolResultArtifact(t,n){if(n?.signal?.aborted)throw n.signal.reason instanceof Error?n.signal.reason:new Error("Tool artifact stat cancelled");let{artifactId:o,sessionId:s}=een(t.uri),a=(0,SA.join)(this.rootDir,Kte(s)),u=(await(0,dS.readdir)(a)).find(_=>_.includes(o));if(!u)throw new Error(`Tool artifact not found: ${t.uri}`);let f=(0,SA.join)(a,u),g=await(0,dS.stat)(f);return{uri:t.uri,bytes:g.size,contentType:hxr(u),path:f,mtimeMs:g.mtimeMs}}primeImageAttachmentPath(t){return this.primeMediaAttachmentPath(t)}primeMediaAttachmentPath(t){return this.runMediaAttachmentPathFlight(t.uri,()=>this.writeDerivedMediaAttachment(t.uri,t.mediaType,Buffer.from(t.bytes)))}ensureMediaAttachmentPath(t){return this.runMediaAttachmentPathFlight(t.uri,async()=>{let n=gxr(this.imageCacheRootDir,this.pdfCacheRootDir,this.videoCacheRootDir,t.uri,t.mediaType);if(!n)return{status:"unsupported"};if(await _xr(n))return{status:"ready",path:n};let o=await this.readToolResultArtifact({uri:t.uri}),s=Pas(o.content,t.uri,ptt(t.mediaType));if(ptt(s.mediaType)==="pdf"&&!Eas(s.bytes))throw new Error(`Media attachment artifact is not a PDF: ${t.uri}`);return this.writeDerivedMediaAttachment(t.uri,s.mediaType,s.bytes)})}runMediaAttachmentPathFlight(t,n){let o=this.mediaAttachmentPathFlights.get(t);if(o)return o;let s;return s=n().finally(()=>{this.mediaAttachmentPathFlights.get(t)===s&&this.mediaAttachmentPathFlights.delete(t)}),this.mediaAttachmentPathFlights.set(t,s),s}async writeDerivedMediaAttachment(t,n,o){let s=gxr(this.imageCacheRootDir,this.pdfCacheRootDir,this.videoCacheRootDir,t,n);if(!s)return{status:"unsupported"};if(await _xr(s))return{status:"ready",path:s};let a=(0,SA.dirname)(s),l=`${s}.tmp-${(0,ftt.randomUUID)()}`;xb({operation:"mkdir",path:a}),await(0,dS.mkdir)(a,{recursive:!0});try{xb({operation:"writeFile",path:l}),await(0,dS.writeFile)(l,o),xb({operation:"rename",path:s}),await(0,dS.rename)(l,s)}catch(u){throw await(0,dS.unlink)(l).catch(()=>{}),u}return{status:"ready",path:s}}};r(yxr,"createNodeToolArtifactStore");r(Kte,"sanitizePathSegment");r(vxr,"extensionForContentType");r(Tas,"extensionForBinaryContentType");r(Ias,"normalizeArtifactExtension");r(hxr,"contentTypeForFileName");r(Cas,"isTextArtifactContentType");r(Eas,"isPdfBytes");r(gxr,"derivedMediaAttachmentPath");r(ptt,"mediaKindForContentType");r(Aas,"extensionForDerivedMediaContentType");r(Pas,"decodeMediaDataUrlArtifact");r(_xr,"isRegularFile");r(een,"parseArtifactUri")});var Zz=At((wBc,bxr)=>{"use strict";var mtt=require("buffer"),hme=mtt.Buffer,nM={},rM;for(rM in mtt)mtt.hasOwnProperty(rM)&&(rM==="SlowBuffer"||rM==="Buffer"||(nM[rM]=mtt[rM]));var gme=nM.Buffer={};for(rM in hme)hme.hasOwnProperty(rM)&&(rM==="allocUnsafe"||rM==="allocUnsafeSlow"||(gme[rM]=hme[rM]));nM.Buffer.prototype=hme.prototype;(!gme.from||gme.from===Uint8Array.from)&&(gme.from=function(e,t,n){if(typeof e=="number")throw new TypeError('The "value" argument must not be of type number. Received type '+typeof e);if(e&&typeof e.length>"u")throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);return hme(e,t,n)});gme.alloc||(gme.alloc=function(e,t,n){if(typeof e!="number")throw new TypeError('The "size" argument must be of type number. Received type '+typeof e);if(e<0||e>=2*(1<<30))throw new RangeError('The value "'+e+'" is invalid for option "size"');var o=hme(e);return!t||t.length===0?o.fill(0):typeof n=="string"?o.fill(t,n):o.fill(t),o});if(!nM.kStringMaxLength)try{nM.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch{}nM.constants||(nM.constants={MAX_LENGTH:nM.kMaxLength},nM.kStringMaxLength&&(nM.constants.MAX_STRING_LENGTH=nM.kStringMaxLength));bxr.exports=nM});var wxr=At(ren=>{"use strict";var Sxr="\uFEFF";ren.PrependBOM=ten;function ten(e,t){this.encoder=e,this.addBOM=!0}r(ten,"PrependBOMWrapper");ten.prototype.write=function(e){return this.addBOM&&(e=Sxr+e,this.addBOM=!1),this.encoder.write(e)};ten.prototype.end=function(){return this.encoder.end()};ren.StripBOM=nen;function nen(e,t){this.decoder=e,this.pass=!1,this.options=t||{}}r(nen,"StripBOMWrapper");nen.prototype.write=function(e){var t=this.decoder.write(e);return this.pass||!t||(t[0]===Sxr&&(t=t.slice(1),typeof this.options.stripBOM=="function"&&this.options.stripBOM()),this.pass=!0),t};nen.prototype.end=function(){return this.decoder.end()}});var oen=At((TBc,kxr)=>{"use strict";var Ras=typeof Object.hasOwn>"u"?Function.call.bind(Object.prototype.hasOwnProperty):Object.hasOwn;function Das(e,t){for(var n in t)Ras(t,n)&&(e[n]=t[n])}r(Das,"mergeModules");kxr.exports=Das});var Txr=At((CBc,xxr)=>{"use strict";var Yz=Zz().Buffer;xxr.exports={utf8:{type:"_internal",bomAware:!0},cesu8:{type:"_internal",bomAware:!0},unicode11utf8:"utf8",ucs2:{type:"_internal",bomAware:!0},utf16le:"ucs2",binary:{type:"_internal"},base64:{type:"_internal"},hex:{type:"_internal"},_internal:ien};function ien(e,t){this.enc=e.encodingName,this.bomAware=e.bomAware,this.enc==="base64"?this.encoder=cen:this.enc==="utf8"?this.encoder=den:this.enc==="cesu8"&&(this.enc="utf8",this.encoder=len,Yz.from("eda0bdedb2a9","hex").toString()!=="\u{1F4A9}"&&(this.decoder=uen,this.defaultCharUnicode=t.defaultCharUnicode))}r(ien,"InternalCodec");ien.prototype.encoder=aen;ien.prototype.decoder=sen;var Oas=require("string_decoder").StringDecoder;function sen(e,t){this.decoder=new Oas(t.enc)}r(sen,"InternalDecoder");sen.prototype.write=function(e){return Yz.isBuffer(e)||(e=Yz.from(e)),this.decoder.write(e)};sen.prototype.end=function(){return this.decoder.end()};function aen(e,t){this.enc=t.enc}r(aen,"InternalEncoder");aen.prototype.write=function(e){return Yz.from(e,this.enc)};aen.prototype.end=function(){};function cen(e,t){this.prevStr=""}r(cen,"InternalEncoderBase64");cen.prototype.write=function(e){e=this.prevStr+e;var t=e.length-e.length%4;return this.prevStr=e.slice(t),e=e.slice(0,t),Yz.from(e,"base64")};cen.prototype.end=function(){return Yz.from(this.prevStr,"base64")};function len(e,t){}r(len,"InternalEncoderCesu8");len.prototype.write=function(e){for(var t=Yz.alloc(e.length*3),n=0,o=0;o<e.length;o++){var s=e.charCodeAt(o);s<128?t[n++]=s:s<2048?(t[n++]=192+(s>>>6),t[n++]=128+(s&63)):(t[n++]=224+(s>>>12),t[n++]=128+(s>>>6&63),t[n++]=128+(s&63))}return t.slice(0,n)};len.prototype.end=function(){};function uen(e,t){this.acc=0,this.contBytes=0,this.accBytes=0,this.defaultCharUnicode=t.defaultCharUnicode}r(uen,"InternalDecoderCesu8");uen.prototype.write=function(e){for(var t=this.acc,n=this.contBytes,o=this.accBytes,s="",a=0;a<e.length;a++){var l=e[a];(l&192)!==128?(n>0&&(s+=this.defaultCharUnicode,n=0),l<128?s+=String.fromCharCode(l):l<224?(t=l&31,n=1,o=1):l<240?(t=l&15,n=2,o=1):s+=this.defaultCharUnicode):n>0?(t=t<<6|l&63,n--,o++,n===0&&(o===2&&t<128&&t>0?s+=this.defaultCharUnicode:o===3&&t<2048?s+=this.defaultCharUnicode:s+=String.fromCharCode(t))):s+=this.defaultCharUnicode}return this.acc=t,this.contBytes=n,this.accBytes=o,s};uen.prototype.end=function(){var e=0;return this.contBytes>0&&(e+=this.defaultCharUnicode),e};function den(e,t){this.highSurrogate=""}r(den,"InternalEncoderUtf8");den.prototype.write=function(e){if(this.highSurrogate&&(e=this.highSurrogate+e,this.highSurrogate=""),e.length>0){var t=e.charCodeAt(e.length-1);t>=55296&&t<56320&&(this.highSurrogate=e[e.length-1],e=e.slice(0,e.length-1))}return Yz.from(e,this.enc)};den.prototype.end=function(){if(this.highSurrogate){var e=this.highSurrogate;return this.highSurrogate="",Yz.from(e,this.enc)}}});var Exr=At(mH=>{"use strict";var htt=Zz().Buffer;mH._utf32=pen;function pen(e,t){this.iconv=t,this.bomAware=!0,this.isLE=e.isLE}r(pen,"Utf32Codec");mH.utf32le={type:"_utf32",isLE:!0};mH.utf32be={type:"_utf32",isLE:!1};mH.ucs4le="utf32le";mH.ucs4be="utf32be";pen.prototype.encoder=fen;pen.prototype.decoder=men;function fen(e,t){this.isLE=t.isLE,this.highSurrogate=0}r(fen,"Utf32Encoder");fen.prototype.write=function(e){for(var t=htt.from(e,"ucs2"),n=htt.alloc(t.length*2),o=this.isLE?n.writeUInt32LE:n.writeUInt32BE,s=0,a=0;a<t.length;a+=2){var l=t.readUInt16LE(a),u=l>=55296&&l<56320,f=l>=56320&&l<57344;if(this.highSurrogate)if(u||!f)o.call(n,this.highSurrogate,s),s+=4;else{var g=(this.highSurrogate-55296<<10|l-56320)+65536;o.call(n,g,s),s+=4,this.highSurrogate=0;continue}u?this.highSurrogate=l:(o.call(n,l,s),s+=4,this.highSurrogate=0)}return s<n.length&&(n=n.slice(0,s)),n};fen.prototype.end=function(){if(this.highSurrogate){var e=htt.alloc(4);return this.isLE?e.writeUInt32LE(this.highSurrogate,0):e.writeUInt32BE(this.highSurrogate,0),this.highSurrogate=0,e}};function men(e,t){this.isLE=t.isLE,this.badChar=t.iconv.defaultCharUnicode.charCodeAt(0),this.overflow=[]}r(men,"Utf32Decoder");men.prototype.write=function(e){if(e.length===0)return"";var t=0,n=0,o=htt.alloc(e.length+4),s=0,a=this.isLE,l=this.overflow,u=this.badChar;if(l.length>0){for(;t<e.length&&l.length<4;t++)l.push(e[t]);l.length===4&&(a?n=l[t]|l[t+1]<<8|l[t+2]<<16|l[t+3]<<24:n=l[t+3]|l[t+2]<<8|l[t+1]<<16|l[t]<<24,l.length=0,s=Ixr(o,s,n,u))}for(;t<e.length-3;t+=4)a?n=e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24:n=e[t+3]|e[t+2]<<8|e[t+1]<<16|e[t]<<24,s=Ixr(o,s,n,u);for(;t<e.length;t++)l.push(e[t]);return o.slice(0,s).toString("ucs2")};function Ixr(e,t,n,o){if((n<0||n>1114111)&&(n=o),n>=65536){n-=65536;var s=55296|n>>10;e[t++]=s&255,e[t++]=s>>8;var n=56320|n&1023}return e[t++]=n&255,e[t++]=n>>8,t}r(Ixr,"_writeCodepoint");men.prototype.end=function(){this.overflow.length=0};mH.utf32=hen;mH.ucs4="utf32";function hen(e,t){this.iconv=t}r(hen,"Utf32AutoCodec");hen.prototype.encoder=gen;hen.prototype.decoder=_en;function gen(e,t){e=e||{},e.addBOM===void 0&&(e.addBOM=!0),this.encoder=t.iconv.getEncoder(e.defaultEncoding||"utf-32le",e)}r(gen,"Utf32AutoEncoder");gen.prototype.write=function(e){return this.encoder.write(e)};gen.prototype.end=function(){return this.encoder.end()};function _en(e,t){this.decoder=null,this.initialBufs=[],this.initialBufsLen=0,this.options=e||{},this.iconv=t.iconv}r(_en,"Utf32AutoDecoder");_en.prototype.write=function(e){if(!this.decoder){if(this.initialBufs.push(e),this.initialBufsLen+=e.length,this.initialBufsLen<32)return"";var t=Cxr(this.initialBufs,this.options.defaultEncoding);this.decoder=this.iconv.getDecoder(t,this.options);for(var n="",o=0;o<this.initialBufs.length;o++)n+=this.decoder.write(this.initialBufs[o]);return this.initialBufs.length=this.initialBufsLen=0,n}return this.decoder.write(e)};_en.prototype.end=function(){if(!this.decoder){var e=Cxr(this.initialBufs,this.options.defaultEncoding);this.decoder=this.iconv.getDecoder(e,this.options);for(var t="",n=0;n<this.initialBufs.length;n++)t+=this.decoder.write(this.initialBufs[n]);var o=this.decoder.end();return o&&(t+=o),this.initialBufs.length=this.initialBufsLen=0,t}return this.decoder.end()};function Cxr(e,t){var n=[],o=0,s=0,a=0,l=0,u=0;e:for(var f=0;f<e.length;f++)for(var g=e[f],_=0;_<g.length;_++)if(n.push(g[_]),n.length===4){if(o===0){if(n[0]===255&&n[1]===254&&n[2]===0&&n[3]===0)return"utf-32le";if(n[0]===0&&n[1]===0&&n[2]===254&&n[3]===255)return"utf-32be"}if((n[0]!==0||n[1]>16)&&a++,(n[3]!==0||n[2]>16)&&s++,n[0]===0&&n[1]===0&&(n[2]!==0||n[3]!==0)&&u++,(n[0]!==0||n[1]!==0)&&n[2]===0&&n[3]===0&&l++,n.length=0,o++,o>=100)break e}return u-a>l-s?"utf-32be":u-a<l-s?"utf-32le":t||"utf-32le"}r(Cxr,"detectEncoding")});var Rxr=At(ken=>{"use strict";var Axr=Zz().Buffer;ken.utf16be=gtt;function gtt(){}r(gtt,"Utf16BECodec");gtt.prototype.encoder=yen;gtt.prototype.decoder=ven;gtt.prototype.bomAware=!0;function yen(){}r(yen,"Utf16BEEncoder");yen.prototype.write=function(e){for(var t=Axr.from(e,"ucs2"),n=0;n<t.length;n+=2){var o=t[n];t[n]=t[n+1],t[n+1]=o}return t};yen.prototype.end=function(){};function ven(){this.overflowByte=-1}r(ven,"Utf16BEDecoder");ven.prototype.write=function(e){if(e.length==0)return"";var t=Axr.alloc(e.length+1),n=0,o=0;for(this.overflowByte!==-1&&(t[0]=e[0],t[1]=this.overflowByte,n=1,o=2);n<e.length-1;n+=2,o+=2)t[o]=e[n+1],t[o+1]=e[n];return this.overflowByte=n==e.length-1?e[e.length-1]:-1,t.slice(0,o).toString("ucs2")};ven.prototype.end=function(){this.overflowByte=-1};ken.utf16=ben;function ben(e,t){this.iconv=t}r(ben,"Utf16Codec");ben.prototype.encoder=Sen;ben.prototype.decoder=wen;function Sen(e,t){e=e||{},e.addBOM===void 0&&(e.addBOM=!0),this.encoder=t.iconv.getEncoder("utf-16le",e)}r(Sen,"Utf16Encoder");Sen.prototype.write=function(e){return this.encoder.write(e)};Sen.prototype.end=function(){return this.encoder.end()};function wen(e,t){this.decoder=null,this.initialBufs=[],this.initialBufsLen=0,this.options=e||{},this.iconv=t.iconv}r(wen,"Utf16Decoder");wen.prototype.write=function(e){if(!this.decoder){if(this.initialBufs.push(e),this.initialBufsLen+=e.length,this.initialBufsLen<16)return"";var t=Pxr(this.initialBufs,this.options.defaultEncoding);this.decoder=this.iconv.getDecoder(t,this.options);for(var n="",o=0;o<this.initialBufs.length;o++)n+=this.decoder.write(this.initialBufs[o]);return this.initialBufs.length=this.initialBufsLen=0,n}return this.decoder.write(e)};wen.prototype.end=function(){if(!this.decoder){var e=Pxr(this.initialBufs,this.options.defaultEncoding);this.decoder=this.iconv.getDecoder(e,this.options);for(var t="",n=0;n<this.initialBufs.length;n++)t+=this.decoder.write(this.initialBufs[n]);var o=this.decoder.end();return o&&(t+=o),this.initialBufs.length=this.initialBufsLen=0,t}return this.decoder.end()};function Pxr(e,t){var n=[],o=0,s=0,a=0;e:for(var l=0;l<e.length;l++)for(var u=e[l],f=0;f<u.length;f++)if(n.push(u[f]),n.length===2){if(o===0){if(n[0]===255&&n[1]===254)return"utf-16le";if(n[0]===254&&n[1]===255)return"utf-16be"}if(n[0]===0&&n[1]!==0&&a++,n[0]!==0&&n[1]===0&&s++,n.length=0,o++,o>=100)break e}return a>s?"utf-16be":a<s?"utf-16le":t||"utf-16le"}r(Pxr,"detectEncoding")});var Oxr=At(vtt=>{"use strict";var m3=Zz().Buffer;vtt.utf7=_tt;vtt.unicode11utf7="utf7";function _tt(e,t){this.iconv=t}r(_tt,"Utf7Codec");_tt.prototype.encoder=Ten;_tt.prototype.decoder=Ien;_tt.prototype.bomAware=!0;var Mas=/[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g;function Ten(e,t){this.iconv=t.iconv}r(Ten,"Utf7Encoder");Ten.prototype.write=function(e){return m3.from(e.replace(Mas,function(t){return"+"+(t==="+"?"":this.iconv.encode(t,"utf16-be").toString("base64").replace(/=+$/,""))+"-"}.bind(this)))};Ten.prototype.end=function(){};function Ien(e,t){this.iconv=t.iconv,this.inBase64=!1,this.base64Accum=""}r(Ien,"Utf7Decoder");var Nas=/[A-Za-z0-9\/+]/,Cen=[];for(vRe=0;vRe<256;vRe++)Cen[vRe]=Nas.test(String.fromCharCode(vRe));var vRe,Las=43,Zte=45,xen=38;Ien.prototype.write=function(e){for(var t="",n=0,o=this.inBase64,s=this.base64Accum,a=0;a<e.length;a++)if(!o)e[a]==Las&&(t+=this.iconv.decode(e.slice(n,a),"ascii"),n=a+1,o=!0);else if(!Cen[e[a]]){if(a==n&&e[a]==Zte)t+="+";else{var l=s+this.iconv.decode(e.slice(n,a),"ascii");t+=this.iconv.decode(m3.from(l,"base64"),"utf16-be")}e[a]!=Zte&&a--,n=a+1,o=!1,s=""}if(!o)t+=this.iconv.decode(e.slice(n),"ascii");else{var l=s+this.iconv.decode(e.slice(n),"ascii"),u=l.length-l.length%8;s=l.slice(u),l=l.slice(0,u),t+=this.iconv.decode(m3.from(l,"base64"),"utf16-be")}return this.inBase64=o,this.base64Accum=s,t};Ien.prototype.end=function(){var e="";return this.inBase64&&this.base64Accum.length>0&&(e=this.iconv.decode(m3.from(this.base64Accum,"base64"),"utf16-be")),this.inBase64=!1,this.base64Accum="",e};vtt.utf7imap=ytt;function ytt(e,t){this.iconv=t}r(ytt,"Utf7IMAPCodec");ytt.prototype.encoder=Een;ytt.prototype.decoder=Aen;ytt.prototype.bomAware=!0;function Een(e,t){this.iconv=t.iconv,this.inBase64=!1,this.base64Accum=m3.alloc(6),this.base64AccumIdx=0}r(Een,"Utf7IMAPEncoder");Een.prototype.write=function(e){for(var t=this.inBase64,n=this.base64Accum,o=this.base64AccumIdx,s=m3.alloc(e.length*5+10),a=0,l=0;l<e.length;l++){var u=e.charCodeAt(l);u>=32&&u<=126?(t&&(o>0&&(a+=s.write(n.slice(0,o).toString("base64").replace(/\//g,",").replace(/=+$/,""),a),o=0),s[a++]=Zte,t=!1),t||(s[a++]=u,u===xen&&(s[a++]=Zte))):(t||(s[a++]=xen,t=!0),t&&(n[o++]=u>>8,n[o++]=u&255,o==n.length&&(a+=s.write(n.toString("base64").replace(/\//g,","),a),o=0)))}return this.inBase64=t,this.base64AccumIdx=o,s.slice(0,a)};Een.prototype.end=function(){var e=m3.alloc(10),t=0;return this.inBase64&&(this.base64AccumIdx>0&&(t+=e.write(this.base64Accum.slice(0,this.base64AccumIdx).toString("base64").replace(/\//g,",").replace(/=+$/,""),t),this.base64AccumIdx=0),e[t++]=Zte,this.inBase64=!1),e.slice(0,t)};function Aen(e,t){this.iconv=t.iconv,this.inBase64=!1,this.base64Accum=""}r(Aen,"Utf7IMAPDecoder");var Dxr=Cen.slice();Dxr[44]=!0;Aen.prototype.write=function(e){for(var t="",n=0,o=this.inBase64,s=this.base64Accum,a=0;a<e.length;a++)if(!o)e[a]==xen&&(t+=this.iconv.decode(e.slice(n,a),"ascii"),n=a+1,o=!0);else if(!Dxr[e[a]]){if(a==n&&e[a]==Zte)t+="&";else{var l=s+this.iconv.decode(e.slice(n,a),"ascii").replace(/,/g,"/");t+=this.iconv.decode(m3.from(l,"base64"),"utf16-be")}e[a]!=Zte&&a--,n=a+1,o=!1,s=""}if(!o)t+=this.iconv.decode(e.slice(n),"ascii");else{var l=s+this.iconv.decode(e.slice(n),"ascii").replace(/,/g,"/"),u=l.length-l.length%8;s=l.slice(u),l=l.slice(0,u),t+=this.iconv.decode(m3.from(l,"base64"),"utf16-be")}return this.inBase64=o,this.base64Accum=s,t};Aen.prototype.end=function(){var e="";return this.inBase64&&this.base64Accum.length>0&&(e=this.iconv.decode(m3.from(this.base64Accum,"base64"),"utf16-be")),this.inBase64=!1,this.base64Accum="",e}});var Nxr=At(Mxr=>{"use strict";var btt=Zz().Buffer;Mxr._sbcs=Pen;function Pen(e,t){if(!e)throw new Error("SBCS codec is called without the data.");if(!e.chars||e.chars.length!==128&&e.chars.length!==256)throw new Error("Encoding '"+e.type+"' has incorrect 'chars' (must be of len 128 or 256)");if(e.chars.length===128){for(var n="",o=0;o<128;o++)n+=String.fromCharCode(o);e.chars=n+e.chars}this.decodeBuf=btt.from(e.chars,"ucs2");for(var s=btt.alloc(65536,t.defaultCharSingleByte.charCodeAt(0)),o=0;o<e.chars.length;o++)s[e.chars.charCodeAt(o)]=o;this.encodeBuf=s}r(Pen,"SBCSCodec");Pen.prototype.encoder=Ren;Pen.prototype.decoder=Den;function Ren(e,t){this.encodeBuf=t.encodeBuf}r(Ren,"SBCSEncoder");Ren.prototype.write=function(e){for(var t=btt.alloc(e.length),n=0;n<e.length;n++)t[n]=this.encodeBuf[e.charCodeAt(n)];return t};Ren.prototype.end=function(){};function Den(e,t){this.decodeBuf=t.decodeBuf}r(Den,"SBCSDecoder");Den.prototype.write=function(e){for(var t=this.decodeBuf,n=btt.alloc(e.length*2),o=0,s=0,a=0;a<e.length;a++)o=e[a]*2,s=a*2,n[s]=t[o],n[s+1]=t[o+1];return n.toString("ucs2")};Den.prototype.end=function(){}});var Fxr=At((FBc,Lxr)=>{"use strict";Lxr.exports={10029:"maccenteuro",maccenteuro:{type:"_sbcs",chars:"\xC4\u0100\u0101\xC9\u0104\xD6\xDC\xE1\u0105\u010C\xE4\u010D\u0106\u0107\xE9\u0179\u017A\u010E\xED\u010F\u0112\u0113\u0116\xF3\u0117\xF4\xF6\xF5\xFA\u011A\u011B\xFC\u2020\xB0\u0118\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\u0119\xA8\u2260\u0123\u012E\u012F\u012A\u2264\u2265\u012B\u0136\u2202\u2211\u0142\u013B\u013C\u013D\u013E\u0139\u013A\u0145\u0146\u0143\xAC\u221A\u0144\u0147\u2206\xAB\xBB\u2026\xA0\u0148\u0150\xD5\u0151\u014C\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\u014D\u0154\u0155\u0158\u2039\u203A\u0159\u0156\u0157\u0160\u201A\u201E\u0161\u015A\u015B\xC1\u0164\u0165\xCD\u017D\u017E\u016A\xD3\xD4\u016B\u016E\xDA\u016F\u0170\u0171\u0172\u0173\xDD\xFD\u0137\u017B\u0141\u017C\u0122\u02C7"},808:"cp808",ibm808:"cp808",cp808:{type:"_sbcs",chars:"\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u0401\u0451\u0404\u0454\u0407\u0457\u040E\u045E\xB0\u2219\xB7\u221A\u2116\u20AC\u25A0\xA0"},mik:{type:"_sbcs",chars:"\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u2514\u2534\u252C\u251C\u2500\u253C\u2563\u2551\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2510\u2591\u2592\u2593\u2502\u2524\u2116\xA7\u2557\u255D\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"},cp720:{type:"_sbcs",chars:"\x80\x81\xE9\xE2\x84\xE0\x86\xE7\xEA\xEB\xE8\xEF\xEE\x8D\x8E\x8F\x90\u0651\u0652\xF4\xA4\u0640\xFB\xF9\u0621\u0622\u0623\u0624\xA3\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u0636\u0637\u0638\u0639\u063A\u0641\xB5\u0642\u0643\u0644\u0645\u0646\u0647\u0648\u0649\u064A\u2261\u064B\u064C\u064D\u064E\u064F\u0650\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"},ascii8bit:"ascii",usascii:"ascii",ansix34:"ascii",ansix341968:"ascii",ansix341986:"ascii",csascii:"ascii",cp367:"ascii",ibm367:"ascii",isoir6:"ascii",iso646us:"ascii",iso646irv:"ascii",us:"ascii",latin1:"iso88591",latin2:"iso88592",latin3:"iso88593",latin4:"iso88594",latin5:"iso88599",latin6:"iso885910",latin7:"iso885913",latin8:"iso885914",latin9:"iso885915",latin10:"iso885916",csisolatin1:"iso88591",csisolatin2:"iso88592",csisolatin3:"iso88593",csisolatin4:"iso88594",csisolatincyrillic:"iso88595",csisolatinarabic:"iso88596",csisolatingreek:"iso88597",csisolatinhebrew:"iso88598",csisolatin5:"iso88599",csisolatin6:"iso885910",l1:"iso88591",l2:"iso88592",l3:"iso88593",l4:"iso88594",l5:"iso88599",l6:"iso885910",l7:"iso885913",l8:"iso885914",l9:"iso885915",l10:"iso885916",isoir14:"iso646jp",isoir57:"iso646cn",isoir100:"iso88591",isoir101:"iso88592",isoir109:"iso88593",isoir110:"iso88594",isoir144:"iso88595",isoir127:"iso88596",isoir126:"iso88597",isoir138:"iso88598",isoir148:"iso88599",isoir157:"iso885910",isoir166:"tis620",isoir179:"iso885913",isoir199:"iso885914",isoir203:"iso885915",isoir226:"iso885916",cp819:"iso88591",ibm819:"iso88591",cyrillic:"iso88595",arabic:"iso88596",arabic8:"iso88596",ecma114:"iso88596",asmo708:"iso88596",greek:"iso88597",greek8:"iso88597",ecma118:"iso88597",elot928:"iso88597",hebrew:"iso88598",hebrew8:"iso88598",turkish:"iso88599",turkish8:"iso88599",thai:"iso885911",thai8:"iso885911",celtic:"iso885914",celtic8:"iso885914",isoceltic:"iso885914",tis6200:"tis620",tis62025291:"tis620",tis62025330:"tis620",1e4:"macroman",10006:"macgreek",10007:"maccyrillic",10079:"maciceland",10081:"macturkish",cspc8codepage437:"cp437",cspc775baltic:"cp775",cspc850multilingual:"cp850",cspcp852:"cp852",cspc862latinhebrew:"cp862",cpgr:"cp869",msee:"cp1250",mscyrl:"cp1251",msansi:"cp1252",msgreek:"cp1253",msturk:"cp1254",mshebr:"cp1255",msarab:"cp1256",winbaltrim:"cp1257",cp20866:"koi8r",20866:"koi8r",ibm878:"koi8r",cskoi8r:"koi8r",cp21866:"koi8u",21866:"koi8u",ibm1168:"koi8u",strk10482002:"rk1048",tcvn5712:"tcvn",tcvn57121:"tcvn",gb198880:"iso646cn",cn:"iso646cn",csiso14jisc6220ro:"iso646jp",jisc62201969ro:"iso646jp",jp:"iso646jp",cshproman8:"hproman8",r8:"hproman8",roman8:"hproman8",xroman8:"hproman8",ibm1051:"hproman8",mac:"macintosh",csmacintosh:"macintosh"}});var Bxr=At((jBc,jxr)=>{"use strict";jxr.exports={437:"cp437",737:"cp737",775:"cp775",850:"cp850",852:"cp852",855:"cp855",856:"cp856",857:"cp857",858:"cp858",860:"cp860",861:"cp861",862:"cp862",863:"cp863",864:"cp864",865:"cp865",866:"cp866",869:"cp869",874:"windows874",922:"cp922",1046:"cp1046",1124:"cp1124",1125:"cp1125",1129:"cp1129",1133:"cp1133",1161:"cp1161",1162:"cp1162",1163:"cp1163",1250:"windows1250",1251:"windows1251",1252:"windows1252",1253:"windows1253",1254:"windows1254",1255:"windows1255",1256:"windows1256",1257:"windows1257",1258:"windows1258",28591:"iso88591",28592:"iso88592",28593:"iso88593",28594:"iso88594",28595:"iso88595",28596:"iso88596",28597:"iso88597",28598:"iso88598",28599:"iso88599",28600:"iso885910",28601:"iso885911",28603:"iso885913",28604:"iso885914",28605:"iso885915",28606:"iso885916",windows874:{type:"_sbcs",chars:"\u20AC\uFFFD\uFFFD\uFFFD\uFFFD\u2026\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\xA0\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFFFD\uFFFD\uFFFD\uFFFD\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\uFFFD\uFFFD\uFFFD\uFFFD"},win874:"windows874",cp874:"windows874",windows1250:{type:"_sbcs",chars:"\u20AC\uFFFD\u201A\uFFFD\u201E\u2026\u2020\u2021\uFFFD\u2030\u0160\u2039\u015A\u0164\u017D\u0179\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\u0161\u203A\u015B\u0165\u017E\u017A\xA0\u02C7\u02D8\u0141\xA4\u0104\xA6\xA7\xA8\xA9\u015E\xAB\xAC\xAD\xAE\u017B\xB0\xB1\u02DB\u0142\xB4\xB5\xB6\xB7\xB8\u0105\u015F\xBB\u013D\u02DD\u013E\u017C\u0154\xC1\xC2\u0102\xC4\u0139\u0106\xC7\u010C\xC9\u0118\xCB\u011A\xCD\xCE\u010E\u0110\u0143\u0147\xD3\xD4\u0150\xD6\xD7\u0158\u016E\xDA\u0170\xDC\xDD\u0162\xDF\u0155\xE1\xE2\u0103\xE4\u013A\u0107\xE7\u010D\xE9\u0119\xEB\u011B\xED\xEE\u010F\u0111\u0144\u0148\xF3\xF4\u0151\xF6\xF7\u0159\u016F\xFA\u0171\xFC\xFD\u0163\u02D9"},win1250:"windows1250",cp1250:"windows1250",windows1251:{type:"_sbcs",chars:"\u0402\u0403\u201A\u0453\u201E\u2026\u2020\u2021\u20AC\u2030\u0409\u2039\u040A\u040C\u040B\u040F\u0452\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\u0459\u203A\u045A\u045C\u045B\u045F\xA0\u040E\u045E\u0408\xA4\u0490\xA6\xA7\u0401\xA9\u0404\xAB\xAC\xAD\xAE\u0407\xB0\xB1\u0406\u0456\u0491\xB5\xB6\xB7\u0451\u2116\u0454\xBB\u0458\u0405\u0455\u0457\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F"},win1251:"windows1251",cp1251:"windows1251",windows1252:{type:"_sbcs",chars:"\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0160\u2039\u0152\uFFFD\u017D\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\u0161\u203A\u0153\uFFFD\u017E\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"},win1252:"windows1252",cp1252:"windows1252",windows1253:{type:"_sbcs",chars:"\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\uFFFD\u2030\uFFFD\u2039\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\uFFFD\u203A\uFFFD\uFFFD\uFFFD\uFFFD\xA0\u0385\u0386\xA3\xA4\xA5\xA6\xA7\xA8\xA9\uFFFD\xAB\xAC\xAD\xAE\u2015\xB0\xB1\xB2\xB3\u0384\xB5\xB6\xB7\u0388\u0389\u038A\xBB\u038C\xBD\u038E\u038F\u0390\u0391\u0392\u0393\u0394\u0395\u0396\u0397\u0398\u0399\u039A\u039B\u039C\u039D\u039E\u039F\u03A0\u03A1\uFFFD\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03AA\u03AB\u03AC\u03AD\u03AE\u03AF\u03B0\u03B1\u03B2\u03B3\u03B4\u03B5\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C2\u03C3\u03C4\u03C5\u03C6\u03C7\u03C8\u03C9\u03CA\u03CB\u03CC\u03CD\u03CE\uFFFD"},win1253:"windows1253",cp1253:"windows1253",windows1254:{type:"_sbcs",chars:"\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0160\u2039\u0152\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\u0161\u203A\u0153\uFFFD\uFFFD\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u011E\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u0130\u015E\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u011F\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u0131\u015F\xFF"},win1254:"windows1254",cp1254:"windows1254",windows1255:{type:"_sbcs",chars:"\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\uFFFD\u2039\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\uFFFD\u203A\uFFFD\uFFFD\uFFFD\uFFFD\xA0\xA1\xA2\xA3\u20AA\xA5\xA6\xA7\xA8\xA9\xD7\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xF7\xBB\xBC\xBD\xBE\xBF\u05B0\u05B1\u05B2\u05B3\u05B4\u05B5\u05B6\u05B7\u05B8\u05B9\u05BA\u05BB\u05BC\u05BD\u05BE\u05BF\u05C0\u05C1\u05C2\u05C3\u05F0\u05F1\u05F2\u05F3\u05F4\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\uFFFD\uFFFD\u200E\u200F\uFFFD"},win1255:"windows1255",cp1255:"windows1255",windows1256:{type:"_sbcs",chars:"\u20AC\u067E\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\u0679\u2039\u0152\u0686\u0698\u0688\u06AF\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u06A9\u2122\u0691\u203A\u0153\u200C\u200D\u06BA\xA0\u060C\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\u06BE\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\u061B\xBB\xBC\xBD\xBE\u061F\u06C1\u0621\u0622\u0623\u0624\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\u0636\xD7\u0637\u0638\u0639\u063A\u0640\u0641\u0642\u0643\xE0\u0644\xE2\u0645\u0646\u0647\u0648\xE7\xE8\xE9\xEA\xEB\u0649\u064A\xEE\xEF\u064B\u064C\u064D\u064E\xF4\u064F\u0650\xF7\u0651\xF9\u0652\xFB\xFC\u200E\u200F\u06D2"},win1256:"windows1256",cp1256:"windows1256",windows1257:{type:"_sbcs",chars:"\u20AC\uFFFD\u201A\uFFFD\u201E\u2026\u2020\u2021\uFFFD\u2030\uFFFD\u2039\uFFFD\xA8\u02C7\xB8\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\uFFFD\u203A\uFFFD\xAF\u02DB\uFFFD\xA0\uFFFD\xA2\xA3\xA4\uFFFD\xA6\xA7\xD8\xA9\u0156\xAB\xAC\xAD\xAE\xC6\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xF8\xB9\u0157\xBB\xBC\xBD\xBE\xE6\u0104\u012E\u0100\u0106\xC4\xC5\u0118\u0112\u010C\xC9\u0179\u0116\u0122\u0136\u012A\u013B\u0160\u0143\u0145\xD3\u014C\xD5\xD6\xD7\u0172\u0141\u015A\u016A\xDC\u017B\u017D\xDF\u0105\u012F\u0101\u0107\xE4\xE5\u0119\u0113\u010D\xE9\u017A\u0117\u0123\u0137\u012B\u013C\u0161\u0144\u0146\xF3\u014D\xF5\xF6\xF7\u0173\u0142\u015B\u016B\xFC\u017C\u017E\u02D9"},win1257:"windows1257",cp1257:"windows1257",windows1258:{type:"_sbcs",chars:"\u20AC\uFFFD\u201A\u0192\u201E\u2026\u2020\u2021\u02C6\u2030\uFFFD\u2039\u0152\uFFFD\uFFFD\uFFFD\uFFFD\u2018\u2019\u201C\u201D\u2022\u2013\u2014\u02DC\u2122\uFFFD\u203A\u0153\uFFFD\uFFFD\u0178\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\u0102\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\u0300\xCD\xCE\xCF\u0110\xD1\u0309\xD3\xD4\u01A0\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u01AF\u0303\xDF\xE0\xE1\xE2\u0103\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\u0301\xED\xEE\xEF\u0111\xF1\u0323\xF3\xF4\u01A1\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u01B0\u20AB\xFF"},win1258:"windows1258",cp1258:"windows1258",iso88591:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"},cp28591:"iso88591",iso88592:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0104\u02D8\u0141\xA4\u013D\u015A\xA7\xA8\u0160\u015E\u0164\u0179\xAD\u017D\u017B\xB0\u0105\u02DB\u0142\xB4\u013E\u015B\u02C7\xB8\u0161\u015F\u0165\u017A\u02DD\u017E\u017C\u0154\xC1\xC2\u0102\xC4\u0139\u0106\xC7\u010C\xC9\u0118\xCB\u011A\xCD\xCE\u010E\u0110\u0143\u0147\xD3\xD4\u0150\xD6\xD7\u0158\u016E\xDA\u0170\xDC\xDD\u0162\xDF\u0155\xE1\xE2\u0103\xE4\u013A\u0107\xE7\u010D\xE9\u0119\xEB\u011B\xED\xEE\u010F\u0111\u0144\u0148\xF3\xF4\u0151\xF6\xF7\u0159\u016F\xFA\u0171\xFC\xFD\u0163\u02D9"},cp28592:"iso88592",iso88593:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0126\u02D8\xA3\xA4\uFFFD\u0124\xA7\xA8\u0130\u015E\u011E\u0134\xAD\uFFFD\u017B\xB0\u0127\xB2\xB3\xB4\xB5\u0125\xB7\xB8\u0131\u015F\u011F\u0135\xBD\uFFFD\u017C\xC0\xC1\xC2\uFFFD\xC4\u010A\u0108\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\uFFFD\xD1\xD2\xD3\xD4\u0120\xD6\xD7\u011C\xD9\xDA\xDB\xDC\u016C\u015C\xDF\xE0\xE1\xE2\uFFFD\xE4\u010B\u0109\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\uFFFD\xF1\xF2\xF3\xF4\u0121\xF6\xF7\u011D\xF9\xFA\xFB\xFC\u016D\u015D\u02D9"},cp28593:"iso88593",iso88594:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0104\u0138\u0156\xA4\u0128\u013B\xA7\xA8\u0160\u0112\u0122\u0166\xAD\u017D\xAF\xB0\u0105\u02DB\u0157\xB4\u0129\u013C\u02C7\xB8\u0161\u0113\u0123\u0167\u014A\u017E\u014B\u0100\xC1\xC2\xC3\xC4\xC5\xC6\u012E\u010C\xC9\u0118\xCB\u0116\xCD\xCE\u012A\u0110\u0145\u014C\u0136\xD4\xD5\xD6\xD7\xD8\u0172\xDA\xDB\xDC\u0168\u016A\xDF\u0101\xE1\xE2\xE3\xE4\xE5\xE6\u012F\u010D\xE9\u0119\xEB\u0117\xED\xEE\u012B\u0111\u0146\u014D\u0137\xF4\xF5\xF6\xF7\xF8\u0173\xFA\xFB\xFC\u0169\u016B\u02D9"},cp28594:"iso88594",iso88595:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0401\u0402\u0403\u0404\u0405\u0406\u0407\u0408\u0409\u040A\u040B\u040C\xAD\u040E\u040F\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u2116\u0451\u0452\u0453\u0454\u0455\u0456\u0457\u0458\u0459\u045A\u045B\u045C\xA7\u045E\u045F"},cp28595:"iso88595",iso88596:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\uFFFD\uFFFD\uFFFD\xA4\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u060C\xAD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u061B\uFFFD\uFFFD\uFFFD\u061F\uFFFD\u0621\u0622\u0623\u0624\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\u0636\u0637\u0638\u0639\u063A\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0640\u0641\u0642\u0643\u0644\u0645\u0646\u0647\u0648\u0649\u064A\u064B\u064C\u064D\u064E\u064F\u0650\u0651\u0652\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"},cp28596:"iso88596",iso88597:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u2018\u2019\xA3\u20AC\u20AF\xA6\xA7\xA8\xA9\u037A\xAB\xAC\xAD\uFFFD\u2015\xB0\xB1\xB2\xB3\u0384\u0385\u0386\xB7\u0388\u0389\u038A\xBB\u038C\xBD\u038E\u038F\u0390\u0391\u0392\u0393\u0394\u0395\u0396\u0397\u0398\u0399\u039A\u039B\u039C\u039D\u039E\u039F\u03A0\u03A1\uFFFD\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03AA\u03AB\u03AC\u03AD\u03AE\u03AF\u03B0\u03B1\u03B2\u03B3\u03B4\u03B5\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C2\u03C3\u03C4\u03C5\u03C6\u03C7\u03C8\u03C9\u03CA\u03CB\u03CC\u03CD\u03CE\uFFFD"},cp28597:"iso88597",iso88598:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\uFFFD\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xD7\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xF7\xBB\xBC\xBD\xBE\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2017\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\uFFFD\uFFFD\u200E\u200F\uFFFD"},cp28598:"iso88598",iso88599:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u011E\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u0130\u015E\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u011F\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u0131\u015F\xFF"},cp28599:"iso88599",iso885910:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0104\u0112\u0122\u012A\u0128\u0136\xA7\u013B\u0110\u0160\u0166\u017D\xAD\u016A\u014A\xB0\u0105\u0113\u0123\u012B\u0129\u0137\xB7\u013C\u0111\u0161\u0167\u017E\u2015\u016B\u014B\u0100\xC1\xC2\xC3\xC4\xC5\xC6\u012E\u010C\xC9\u0118\xCB\u0116\xCD\xCE\xCF\xD0\u0145\u014C\xD3\xD4\xD5\xD6\u0168\xD8\u0172\xDA\xDB\xDC\xDD\xDE\xDF\u0101\xE1\xE2\xE3\xE4\xE5\xE6\u012F\u010D\xE9\u0119\xEB\u0117\xED\xEE\xEF\xF0\u0146\u014D\xF3\xF4\xF5\xF6\u0169\xF8\u0173\xFA\xFB\xFC\xFD\xFE\u0138"},cp28600:"iso885910",iso885911:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFFFD\uFFFD\uFFFD\uFFFD\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\uFFFD\uFFFD\uFFFD\uFFFD"},cp28601:"iso885911",iso885913:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u201D\xA2\xA3\xA4\u201E\xA6\xA7\xD8\xA9\u0156\xAB\xAC\xAD\xAE\xC6\xB0\xB1\xB2\xB3\u201C\xB5\xB6\xB7\xF8\xB9\u0157\xBB\xBC\xBD\xBE\xE6\u0104\u012E\u0100\u0106\xC4\xC5\u0118\u0112\u010C\xC9\u0179\u0116\u0122\u0136\u012A\u013B\u0160\u0143\u0145\xD3\u014C\xD5\xD6\xD7\u0172\u0141\u015A\u016A\xDC\u017B\u017D\xDF\u0105\u012F\u0101\u0107\xE4\xE5\u0119\u0113\u010D\xE9\u017A\u0117\u0123\u0137\u012B\u013C\u0161\u0144\u0146\xF3\u014D\xF5\xF6\xF7\u0173\u0142\u015B\u016B\xFC\u017C\u017E\u2019"},cp28603:"iso885913",iso885914:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u1E02\u1E03\xA3\u010A\u010B\u1E0A\xA7\u1E80\xA9\u1E82\u1E0B\u1EF2\xAD\xAE\u0178\u1E1E\u1E1F\u0120\u0121\u1E40\u1E41\xB6\u1E56\u1E81\u1E57\u1E83\u1E60\u1EF3\u1E84\u1E85\u1E61\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u0174\xD1\xD2\xD3\xD4\xD5\xD6\u1E6A\xD8\xD9\xDA\xDB\xDC\xDD\u0176\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u0175\xF1\xF2\xF3\xF4\xF5\xF6\u1E6B\xF8\xF9\xFA\xFB\xFC\xFD\u0177\xFF"},cp28604:"iso885914",iso885915:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\u20AC\xA5\u0160\xA7\u0161\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\u017D\xB5\xB6\xB7\u017E\xB9\xBA\xBB\u0152\u0153\u0178\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"},cp28605:"iso885915",iso885916:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0104\u0105\u0141\u20AC\u201E\u0160\xA7\u0161\xA9\u0218\xAB\u0179\xAD\u017A\u017B\xB0\xB1\u010C\u0142\u017D\u201D\xB6\xB7\u017E\u010D\u0219\xBB\u0152\u0153\u0178\u017C\xC0\xC1\xC2\u0102\xC4\u0106\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u0110\u0143\xD2\xD3\xD4\u0150\xD6\u015A\u0170\xD9\xDA\xDB\xDC\u0118\u021A\xDF\xE0\xE1\xE2\u0103\xE4\u0107\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u0111\u0144\xF2\xF3\xF4\u0151\xF6\u015B\u0171\xF9\xFA\xFB\xFC\u0119\u021B\xFF"},cp28606:"iso885916",cp437:{type:"_sbcs",chars:"\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"},ibm437:"cp437",csibm437:"cp437",cp737:{type:"_sbcs",chars:"\u0391\u0392\u0393\u0394\u0395\u0396\u0397\u0398\u0399\u039A\u039B\u039C\u039D\u039E\u039F\u03A0\u03A1\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03B1\u03B2\u03B3\u03B4\u03B5\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C3\u03C2\u03C4\u03C5\u03C6\u03C7\u03C8\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03C9\u03AC\u03AD\u03AE\u03CA\u03AF\u03CC\u03CD\u03CB\u03CE\u0386\u0388\u0389\u038A\u038C\u038E\u038F\xB1\u2265\u2264\u03AA\u03AB\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"},ibm737:"cp737",csibm737:"cp737",cp775:{type:"_sbcs",chars:"\u0106\xFC\xE9\u0101\xE4\u0123\xE5\u0107\u0142\u0113\u0156\u0157\u012B\u0179\xC4\xC5\xC9\xE6\xC6\u014D\xF6\u0122\xA2\u015A\u015B\xD6\xDC\xF8\xA3\xD8\xD7\xA4\u0100\u012A\xF3\u017B\u017C\u017A\u201D\xA6\xA9\xAE\xAC\xBD\xBC\u0141\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u0104\u010C\u0118\u0116\u2563\u2551\u2557\u255D\u012E\u0160\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u0172\u016A\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u017D\u0105\u010D\u0119\u0117\u012F\u0161\u0173\u016B\u017E\u2518\u250C\u2588\u2584\u258C\u2590\u2580\xD3\xDF\u014C\u0143\xF5\xD5\xB5\u0144\u0136\u0137\u013B\u013C\u0146\u0112\u0145\u2019\xAD\xB1\u201C\xBE\xB6\xA7\xF7\u201E\xB0\u2219\xB7\xB9\xB3\xB2\u25A0\xA0"},ibm775:"cp775",csibm775:"cp775",cp850:{type:"_sbcs",chars:"\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xF8\xA3\xD8\xD7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\xAE\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\xC1\xC2\xC0\xA9\u2563\u2551\u2557\u255D\xA2\xA5\u2510\u2514\u2534\u252C\u251C\u2500\u253C\xE3\xC3\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\xF0\xD0\xCA\xCB\xC8\u0131\xCD\xCE\xCF\u2518\u250C\u2588\u2584\xA6\xCC\u2580\xD3\xDF\xD4\xD2\xF5\xD5\xB5\xFE\xDE\xDA\xDB\xD9\xFD\xDD\xAF\xB4\xAD\xB1\u2017\xBE\xB6\xA7\xF7\xB8\xB0\xA8\xB7\xB9\xB3\xB2\u25A0\xA0"},ibm850:"cp850",csibm850:"cp850",cp852:{type:"_sbcs",chars:"\xC7\xFC\xE9\xE2\xE4\u016F\u0107\xE7\u0142\xEB\u0150\u0151\xEE\u0179\xC4\u0106\xC9\u0139\u013A\xF4\xF6\u013D\u013E\u015A\u015B\xD6\xDC\u0164\u0165\u0141\xD7\u010D\xE1\xED\xF3\xFA\u0104\u0105\u017D\u017E\u0118\u0119\xAC\u017A\u010C\u015F\xAB\xBB\u2591\u2592\u2593\u2502\u2524\xC1\xC2\u011A\u015E\u2563\u2551\u2557\u255D\u017B\u017C\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u0102\u0103\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\u0111\u0110\u010E\xCB\u010F\u0147\xCD\xCE\u011B\u2518\u250C\u2588\u2584\u0162\u016E\u2580\xD3\xDF\xD4\u0143\u0144\u0148\u0160\u0161\u0154\xDA\u0155\u0170\xFD\xDD\u0163\xB4\xAD\u02DD\u02DB\u02C7\u02D8\xA7\xF7\xB8\xB0\xA8\u02D9\u0171\u0158\u0159\u25A0\xA0"},ibm852:"cp852",csibm852:"cp852",cp855:{type:"_sbcs",chars:"\u0452\u0402\u0453\u0403\u0451\u0401\u0454\u0404\u0455\u0405\u0456\u0406\u0457\u0407\u0458\u0408\u0459\u0409\u045A\u040A\u045B\u040B\u045C\u040C\u045E\u040E\u045F\u040F\u044E\u042E\u044A\u042A\u0430\u0410\u0431\u0411\u0446\u0426\u0434\u0414\u0435\u0415\u0444\u0424\u0433\u0413\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u0445\u0425\u0438\u0418\u2563\u2551\u2557\u255D\u0439\u0419\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u043A\u041A\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\u043B\u041B\u043C\u041C\u043D\u041D\u043E\u041E\u043F\u2518\u250C\u2588\u2584\u041F\u044F\u2580\u042F\u0440\u0420\u0441\u0421\u0442\u0422\u0443\u0423\u0436\u0416\u0432\u0412\u044C\u042C\u2116\xAD\u044B\u042B\u0437\u0417\u0448\u0428\u044D\u042D\u0449\u0429\u0447\u0427\xA7\u25A0\xA0"},ibm855:"cp855",csibm855:"cp855",cp856:{type:"_sbcs",chars:"\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\uFFFD\xA3\uFFFD\xD7\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\xAE\xAC\xBD\xBC\uFFFD\xAB\xBB\u2591\u2592\u2593\u2502\u2524\uFFFD\uFFFD\uFFFD\xA9\u2563\u2551\u2557\u255D\xA2\xA5\u2510\u2514\u2534\u252C\u251C\u2500\u253C\uFFFD\uFFFD\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2518\u250C\u2588\u2584\xA6\uFFFD\u2580\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\xB5\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\xAF\xB4\xAD\xB1\u2017\xBE\xB6\xA7\xF7\xB8\xB0\xA8\xB7\xB9\xB3\xB2\u25A0\xA0"},ibm856:"cp856",csibm856:"cp856",cp857:{type:"_sbcs",chars:"\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\u0131\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\u0130\xD6\xDC\xF8\xA3\xD8\u015E\u015F\xE1\xED\xF3\xFA\xF1\xD1\u011E\u011F\xBF\xAE\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\xC1\xC2\xC0\xA9\u2563\u2551\u2557\u255D\xA2\xA5\u2510\u2514\u2534\u252C\u251C\u2500\u253C\xE3\xC3\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\xBA\xAA\xCA\xCB\xC8\uFFFD\xCD\xCE\xCF\u2518\u250C\u2588\u2584\xA6\xCC\u2580\xD3\xDF\xD4\xD2\xF5\xD5\xB5\uFFFD\xD7\xDA\xDB\xD9\xEC\xFF\xAF\xB4\xAD\xB1\uFFFD\xBE\xB6\xA7\xF7\xB8\xB0\xA8\xB7\xB9\xB3\xB2\u25A0\xA0"},ibm857:"cp857",csibm857:"cp857",cp858:{type:"_sbcs",chars:"\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xF8\xA3\xD8\xD7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\xAE\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\xC1\xC2\xC0\xA9\u2563\u2551\u2557\u255D\xA2\xA5\u2510\u2514\u2534\u252C\u251C\u2500\u253C\xE3\xC3\u255A\u2554\u2569\u2566\u2560\u2550\u256C\xA4\xF0\xD0\xCA\xCB\xC8\u20AC\xCD\xCE\xCF\u2518\u250C\u2588\u2584\xA6\xCC\u2580\xD3\xDF\xD4\xD2\xF5\xD5\xB5\xFE\xDE\xDA\xDB\xD9\xFD\xDD\xAF\xB4\xAD\xB1\u2017\xBE\xB6\xA7\xF7\xB8\xB0\xA8\xB7\xB9\xB3\xB2\u25A0\xA0"},ibm858:"cp858",csibm858:"cp858",cp860:{type:"_sbcs",chars:"\xC7\xFC\xE9\xE2\xE3\xE0\xC1\xE7\xEA\xCA\xE8\xCD\xD4\xEC\xC3\xC2\xC9\xC0\xC8\xF4\xF5\xF2\xDA\xF9\xCC\xD5\xDC\xA2\xA3\xD9\u20A7\xD3\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\xD2\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"},ibm860:"cp860",csibm860:"cp860",cp861:{type:"_sbcs",chars:"\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xD0\xF0\xDE\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xFE\xFB\xDD\xFD\xD6\xDC\xF8\xA3\xD8\u20A7\u0192\xE1\xED\xF3\xFA\xC1\xCD\xD3\xDA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"},ibm861:"cp861",csibm861:"cp861",cp862:{type:"_sbcs",chars:"\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"},ibm862:"cp862",csibm862:"cp862",cp863:{type:"_sbcs",chars:"\xC7\xFC\xE9\xE2\xC2\xE0\xB6\xE7\xEA\xEB\xE8\xEF\xEE\u2017\xC0\xA7\xC9\xC8\xCA\xF4\xCB\xCF\xFB\xF9\xA4\xD4\xDC\xA2\xA3\xD9\xDB\u0192\xA6\xB4\xF3\xFA\xA8\xB8\xB3\xAF\xCE\u2310\xAC\xBD\xBC\xBE\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"},ibm863:"cp863",csibm863:"cp863",cp864:{type:"_sbcs",chars:`\0\x07\b
|
|
1899
1899
|
\v\f\r\x1B !"#$\u066A&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~\x7F\xB0\xB7\u2219\u221A\u2592\u2500\u2502\u253C\u2524\u252C\u251C\u2534\u2510\u250C\u2514\u2518\u03B2\u221E\u03C6\xB1\xBD\xBC\u2248\xAB\xBB\uFEF7\uFEF8\uFFFD\uFFFD\uFEFB\uFEFC\uFFFD\xA0\xAD\uFE82\xA3\xA4\uFE84\uFFFD\uFFFD\uFE8E\uFE8F\uFE95\uFE99\u060C\uFE9D\uFEA1\uFEA5\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\uFED1\u061B\uFEB1\uFEB5\uFEB9\u061F\xA2\uFE80\uFE81\uFE83\uFE85\uFECA\uFE8B\uFE8D\uFE91\uFE93\uFE97\uFE9B\uFE9F\uFEA3\uFEA7\uFEA9\uFEAB\uFEAD\uFEAF\uFEB3\uFEB7\uFEBB\uFEBF\uFEC1\uFEC5\uFECB\uFECF\xA6\xAC\xF7\xD7\uFEC9\u0640\uFED3\uFED7\uFEDB\uFEDF\uFEE3\uFEE7\uFEEB\uFEED\uFEEF\uFEF3\uFEBD\uFECC\uFECE\uFECD\uFEE1\uFE7D\u0651\uFEE5\uFEE9\uFEEC\uFEF0\uFEF2\uFED0\uFED5\uFEF5\uFEF6\uFEDD\uFED9\uFEF1\u25A0\uFFFD`},ibm864:"cp864",csibm864:"cp864",cp865:{type:"_sbcs",chars:"\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xF8\xA3\xD8\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xA4\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0"},ibm865:"cp865",csibm865:"cp865",cp866:{type:"_sbcs",chars:"\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u0401\u0451\u0404\u0454\u0407\u0457\u040E\u045E\xB0\u2219\xB7\u221A\u2116\xA4\u25A0\xA0"},ibm866:"cp866",csibm866:"cp866",cp869:{type:"_sbcs",chars:"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0386\uFFFD\xB7\xAC\xA6\u2018\u2019\u0388\u2015\u0389\u038A\u03AA\u038C\uFFFD\uFFFD\u038E\u03AB\xA9\u038F\xB2\xB3\u03AC\xA3\u03AD\u03AE\u03AF\u03CA\u0390\u03CC\u03CD\u0391\u0392\u0393\u0394\u0395\u0396\u0397\xBD\u0398\u0399\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u039A\u039B\u039C\u039D\u2563\u2551\u2557\u255D\u039E\u039F\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u03A0\u03A1\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u03A3\u03A4\u03A5\u03A6\u03A7\u03A8\u03A9\u03B1\u03B2\u03B3\u2518\u250C\u2588\u2584\u03B4\u03B5\u2580\u03B6\u03B7\u03B8\u03B9\u03BA\u03BB\u03BC\u03BD\u03BE\u03BF\u03C0\u03C1\u03C3\u03C2\u03C4\u0384\xAD\xB1\u03C5\u03C6\u03C7\xA7\u03C8\u0385\xB0\xA8\u03C9\u03CB\u03B0\u03CE\u25A0\xA0"},ibm869:"cp869",csibm869:"cp869",cp922:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\u203E\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\u0160\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\u017D\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\u0161\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\u017E\xFF"},ibm922:"cp922",csibm922:"cp922",cp1046:{type:"_sbcs",chars:"\uFE88\xD7\xF7\uF8F6\uF8F5\uF8F4\uF8F7\uFE71\x88\u25A0\u2502\u2500\u2510\u250C\u2514\u2518\uFE79\uFE7B\uFE7D\uFE7F\uFE77\uFE8A\uFEF0\uFEF3\uFEF2\uFECE\uFECF\uFED0\uFEF6\uFEF8\uFEFA\uFEFC\xA0\uF8FA\uF8F9\uF8F8\xA4\uF8FB\uFE8B\uFE91\uFE97\uFE9B\uFE9F\uFEA3\u060C\xAD\uFEA7\uFEB3\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\uFEB7\u061B\uFEBB\uFEBF\uFECA\u061F\uFECB\u0621\u0622\u0623\u0624\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\u0636\u0637\uFEC7\u0639\u063A\uFECC\uFE82\uFE84\uFE8E\uFED3\u0640\u0641\u0642\u0643\u0644\u0645\u0646\u0647\u0648\u0649\u064A\u064B\u064C\u064D\u064E\u064F\u0650\u0651\u0652\uFED7\uFEDB\uFEDF\uF8FC\uFEF5\uFEF7\uFEF9\uFEFB\uFEE3\uFEE7\uFEEC\uFEE9\uFFFD"},ibm1046:"cp1046",csibm1046:"cp1046",cp1124:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0401\u0402\u0490\u0404\u0405\u0406\u0407\u0408\u0409\u040A\u040B\u040C\xAD\u040E\u040F\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u2116\u0451\u0452\u0491\u0454\u0455\u0456\u0457\u0458\u0459\u045A\u045B\u045C\xA7\u045E\u045F"},ibm1124:"cp1124",csibm1124:"cp1124",cp1125:{type:"_sbcs",chars:"\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u0401\u0451\u0490\u0491\u0404\u0454\u0406\u0456\u0407\u0457\xB7\u221A\u2116\xA4\u25A0\xA0"},ibm1125:"cp1125",csibm1125:"cp1125",cp1129:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\u0153\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\u0178\xB5\xB6\xB7\u0152\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\u0102\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\u0300\xCD\xCE\xCF\u0110\xD1\u0309\xD3\xD4\u01A0\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u01AF\u0303\xDF\xE0\xE1\xE2\u0103\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\u0301\xED\xEE\xEF\u0111\xF1\u0323\xF3\xF4\u01A1\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u01B0\u20AB\xFF"},ibm1129:"cp1129",csibm1129:"cp1129",cp1133:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0E81\u0E82\u0E84\u0E87\u0E88\u0EAA\u0E8A\u0E8D\u0E94\u0E95\u0E96\u0E97\u0E99\u0E9A\u0E9B\u0E9C\u0E9D\u0E9E\u0E9F\u0EA1\u0EA2\u0EA3\u0EA5\u0EA7\u0EAB\u0EAD\u0EAE\uFFFD\uFFFD\uFFFD\u0EAF\u0EB0\u0EB2\u0EB3\u0EB4\u0EB5\u0EB6\u0EB7\u0EB8\u0EB9\u0EBC\u0EB1\u0EBB\u0EBD\uFFFD\uFFFD\uFFFD\u0EC0\u0EC1\u0EC2\u0EC3\u0EC4\u0EC8\u0EC9\u0ECA\u0ECB\u0ECC\u0ECD\u0EC6\uFFFD\u0EDC\u0EDD\u20AD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0ED0\u0ED1\u0ED2\u0ED3\u0ED4\u0ED5\u0ED6\u0ED7\u0ED8\u0ED9\uFFFD\uFFFD\xA2\xAC\xA6\uFFFD"},ibm1133:"cp1133",csibm1133:"cp1133",cp1161:{type:"_sbcs",chars:"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0E48\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\u0E49\u0E4A\u0E4B\u20AC\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\xA2\xAC\xA6\xA0"},ibm1161:"cp1161",csibm1161:"cp1161",cp1162:{type:"_sbcs",chars:"\u20AC\x81\x82\x83\x84\u2026\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\u2018\u2019\u201C\u201D\u2022\u2013\u2014\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFFFD\uFFFD\uFFFD\uFFFD\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u0E4E\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\u0E5A\u0E5B\uFFFD\uFFFD\uFFFD\uFFFD"},ibm1162:"cp1162",csibm1162:"cp1162",cp1163:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\u20AC\xA5\xA6\xA7\u0153\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\u0178\xB5\xB6\xB7\u0152\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\u0102\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\u0300\xCD\xCE\xCF\u0110\xD1\u0309\xD3\xD4\u01A0\xD6\xD7\xD8\xD9\xDA\xDB\xDC\u01AF\u0303\xDF\xE0\xE1\xE2\u0103\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\u0301\xED\xEE\xEF\u0111\xF1\u0323\xF3\xF4\u01A1\xF6\xF7\xF8\xF9\xFA\xFB\xFC\u01B0\u20AB\xFF"},ibm1163:"cp1163",csibm1163:"cp1163",maccroatian:{type:"_sbcs",chars:"\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\u0160\u2122\xB4\xA8\u2260\u017D\xD8\u221E\xB1\u2264\u2265\u2206\xB5\u2202\u2211\u220F\u0161\u222B\xAA\xBA\u2126\u017E\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u0106\xAB\u010C\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u0110\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\uFFFD\xA9\u2044\xA4\u2039\u203A\xC6\xBB\u2013\xB7\u201A\u201E\u2030\xC2\u0107\xC1\u010D\xC8\xCD\xCE\xCF\xCC\xD3\xD4\u0111\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u03C0\xCB\u02DA\xB8\xCA\xE6\u02C7"},maccyrillic:{type:"_sbcs",chars:"\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u2020\xB0\xA2\xA3\xA7\u2022\xB6\u0406\xAE\xA9\u2122\u0402\u0452\u2260\u0403\u0453\u221E\xB1\u2264\u2265\u0456\xB5\u2202\u0408\u0404\u0454\u0407\u0457\u0409\u0459\u040A\u045A\u0458\u0405\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\u040B\u045B\u040C\u045C\u0455\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u201E\u040E\u045E\u040F\u045F\u2116\u0401\u0451\u044F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\xA4"},macgreek:{type:"_sbcs",chars:"\xC4\xB9\xB2\xC9\xB3\xD6\xDC\u0385\xE0\xE2\xE4\u0384\xA8\xE7\xE9\xE8\xEA\xEB\xA3\u2122\xEE\xEF\u2022\xBD\u2030\xF4\xF6\xA6\xAD\xF9\xFB\xFC\u2020\u0393\u0394\u0398\u039B\u039E\u03A0\xDF\xAE\xA9\u03A3\u03AA\xA7\u2260\xB0\u0387\u0391\xB1\u2264\u2265\xA5\u0392\u0395\u0396\u0397\u0399\u039A\u039C\u03A6\u03AB\u03A8\u03A9\u03AC\u039D\xAC\u039F\u03A1\u2248\u03A4\xAB\xBB\u2026\xA0\u03A5\u03A7\u0386\u0388\u0153\u2013\u2015\u201C\u201D\u2018\u2019\xF7\u0389\u038A\u038C\u038E\u03AD\u03AE\u03AF\u03CC\u038F\u03CD\u03B1\u03B2\u03C8\u03B4\u03B5\u03C6\u03B3\u03B7\u03B9\u03BE\u03BA\u03BB\u03BC\u03BD\u03BF\u03C0\u03CE\u03C1\u03C3\u03C4\u03B8\u03C9\u03C2\u03C7\u03C5\u03B6\u03CA\u03CB\u0390\u03B0\uFFFD"},maciceland:{type:"_sbcs",chars:"\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\xDD\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\xE6\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\xA4\xD0\xF0\xDE\xFE\xFD\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7"},macroman:{type:"_sbcs",chars:"\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\xE6\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\xA4\u2039\u203A\uFB01\uFB02\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7"},macromania:{type:"_sbcs",chars:"\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\u0102\u015E\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\u0103\u015F\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u2044\xA4\u2039\u203A\u0162\u0163\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\u0131\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7"},macthai:{type:"_sbcs",chars:"\xAB\xBB\u2026\uF88C\uF88F\uF892\uF895\uF898\uF88B\uF88E\uF891\uF894\uF897\u201C\u201D\uF899\uFFFD\u2022\uF884\uF889\uF885\uF886\uF887\uF888\uF88A\uF88D\uF890\uF893\uF896\u2018\u2019\uFFFD\xA0\u0E01\u0E02\u0E03\u0E04\u0E05\u0E06\u0E07\u0E08\u0E09\u0E0A\u0E0B\u0E0C\u0E0D\u0E0E\u0E0F\u0E10\u0E11\u0E12\u0E13\u0E14\u0E15\u0E16\u0E17\u0E18\u0E19\u0E1A\u0E1B\u0E1C\u0E1D\u0E1E\u0E1F\u0E20\u0E21\u0E22\u0E23\u0E24\u0E25\u0E26\u0E27\u0E28\u0E29\u0E2A\u0E2B\u0E2C\u0E2D\u0E2E\u0E2F\u0E30\u0E31\u0E32\u0E33\u0E34\u0E35\u0E36\u0E37\u0E38\u0E39\u0E3A\uFEFF\u200B\u2013\u2014\u0E3F\u0E40\u0E41\u0E42\u0E43\u0E44\u0E45\u0E46\u0E47\u0E48\u0E49\u0E4A\u0E4B\u0E4C\u0E4D\u2122\u0E4F\u0E50\u0E51\u0E52\u0E53\u0E54\u0E55\u0E56\u0E57\u0E58\u0E59\xAE\xA9\uFFFD\uFFFD\uFFFD\uFFFD"},macturkish:{type:"_sbcs",chars:"\xC4\xC5\xC7\xC9\xD1\xD6\xDC\xE1\xE0\xE2\xE4\xE3\xE5\xE7\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF1\xF3\xF2\xF4\xF6\xF5\xFA\xF9\xFB\xFC\u2020\xB0\xA2\xA3\xA7\u2022\xB6\xDF\xAE\xA9\u2122\xB4\xA8\u2260\xC6\xD8\u221E\xB1\u2264\u2265\xA5\xB5\u2202\u2211\u220F\u03C0\u222B\xAA\xBA\u2126\xE6\xF8\xBF\xA1\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\xC0\xC3\xD5\u0152\u0153\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u25CA\xFF\u0178\u011E\u011F\u0130\u0131\u015E\u015F\u2021\xB7\u201A\u201E\u2030\xC2\xCA\xC1\xCB\xC8\xCD\xCE\xCF\xCC\xD3\xD4\uFFFD\xD2\xDA\xDB\xD9\uFFFD\u02C6\u02DC\xAF\u02D8\u02D9\u02DA\xB8\u02DD\u02DB\u02C7"},macukraine:{type:"_sbcs",chars:"\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u2020\xB0\u0490\xA3\xA7\u2022\xB6\u0406\xAE\xA9\u2122\u0402\u0452\u2260\u0403\u0453\u221E\xB1\u2264\u2265\u0456\xB5\u0491\u0408\u0404\u0454\u0407\u0457\u0409\u0459\u040A\u045A\u0458\u0405\xAC\u221A\u0192\u2248\u2206\xAB\xBB\u2026\xA0\u040B\u045B\u040C\u045C\u0455\u2013\u2014\u201C\u201D\u2018\u2019\xF7\u201E\u040E\u045E\u040F\u045F\u2116\u0401\u0451\u044F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\xA4"},koi8r:{type:"_sbcs",chars:"\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2580\u2584\u2588\u258C\u2590\u2591\u2592\u2593\u2320\u25A0\u2219\u221A\u2248\u2264\u2265\xA0\u2321\xB0\xB2\xB7\xF7\u2550\u2551\u2552\u0451\u2553\u2554\u2555\u2556\u2557\u2558\u2559\u255A\u255B\u255C\u255D\u255E\u255F\u2560\u2561\u0401\u2562\u2563\u2564\u2565\u2566\u2567\u2568\u2569\u256A\u256B\u256C\xA9\u044E\u0430\u0431\u0446\u0434\u0435\u0444\u0433\u0445\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u044F\u0440\u0441\u0442\u0443\u0436\u0432\u044C\u044B\u0437\u0448\u044D\u0449\u0447\u044A\u042E\u0410\u0411\u0426\u0414\u0415\u0424\u0413\u0425\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u042F\u0420\u0421\u0422\u0423\u0416\u0412\u042C\u042B\u0417\u0428\u042D\u0429\u0427\u042A"},koi8u:{type:"_sbcs",chars:"\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2580\u2584\u2588\u258C\u2590\u2591\u2592\u2593\u2320\u25A0\u2219\u221A\u2248\u2264\u2265\xA0\u2321\xB0\xB2\xB7\xF7\u2550\u2551\u2552\u0451\u0454\u2554\u0456\u0457\u2557\u2558\u2559\u255A\u255B\u0491\u255D\u255E\u255F\u2560\u2561\u0401\u0404\u2563\u0406\u0407\u2566\u2567\u2568\u2569\u256A\u0490\u256C\xA9\u044E\u0430\u0431\u0446\u0434\u0435\u0444\u0433\u0445\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u044F\u0440\u0441\u0442\u0443\u0436\u0432\u044C\u044B\u0437\u0448\u044D\u0449\u0447\u044A\u042E\u0410\u0411\u0426\u0414\u0415\u0424\u0413\u0425\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u042F\u0420\u0421\u0422\u0423\u0416\u0412\u042C\u042B\u0417\u0428\u042D\u0429\u0427\u042A"},koi8ru:{type:"_sbcs",chars:"\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2580\u2584\u2588\u258C\u2590\u2591\u2592\u2593\u2320\u25A0\u2219\u221A\u2248\u2264\u2265\xA0\u2321\xB0\xB2\xB7\xF7\u2550\u2551\u2552\u0451\u0454\u2554\u0456\u0457\u2557\u2558\u2559\u255A\u255B\u0491\u045E\u255E\u255F\u2560\u2561\u0401\u0404\u2563\u0406\u0407\u2566\u2567\u2568\u2569\u256A\u0490\u040E\xA9\u044E\u0430\u0431\u0446\u0434\u0435\u0444\u0433\u0445\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u044F\u0440\u0441\u0442\u0443\u0436\u0432\u044C\u044B\u0437\u0448\u044D\u0449\u0447\u044A\u042E\u0410\u0411\u0426\u0414\u0415\u0424\u0413\u0425\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u042F\u0420\u0421\u0422\u0423\u0416\u0412\u042C\u042B\u0417\u0428\u042D\u0429\u0427\u042A"},koi8t:{type:"_sbcs",chars:"\u049B\u0493\u201A\u0492\u201E\u2026\u2020\u2021\uFFFD\u2030\u04B3\u2039\u04B2\u04B7\u04B6\uFFFD\u049A\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\uFFFD\u203A\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u04EF\u04EE\u0451\xA4\u04E3\xA6\xA7\uFFFD\uFFFD\uFFFD\xAB\xAC\xAD\xAE\uFFFD\xB0\xB1\xB2\u0401\uFFFD\u04E2\xB6\xB7\uFFFD\u2116\uFFFD\xBB\uFFFD\uFFFD\uFFFD\xA9\u044E\u0430\u0431\u0446\u0434\u0435\u0444\u0433\u0445\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u044F\u0440\u0441\u0442\u0443\u0436\u0432\u044C\u044B\u0437\u0448\u044D\u0449\u0447\u044A\u042E\u0410\u0411\u0426\u0414\u0415\u0424\u0413\u0425\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u042F\u0420\u0421\u0422\u0423\u0416\u0412\u042C\u042B\u0417\u0428\u042D\u0429\u0427\u042A"},armscii8:{type:"_sbcs",chars:"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\uFFFD\u0587\u0589)(\xBB\xAB\u2014.\u055D,-\u058A\u2026\u055C\u055B\u055E\u0531\u0561\u0532\u0562\u0533\u0563\u0534\u0564\u0535\u0565\u0536\u0566\u0537\u0567\u0538\u0568\u0539\u0569\u053A\u056A\u053B\u056B\u053C\u056C\u053D\u056D\u053E\u056E\u053F\u056F\u0540\u0570\u0541\u0571\u0542\u0572\u0543\u0573\u0544\u0574\u0545\u0575\u0546\u0576\u0547\u0577\u0548\u0578\u0549\u0579\u054A\u057A\u054B\u057B\u054C\u057C\u054D\u057D\u054E\u057E\u054F\u057F\u0550\u0580\u0551\u0581\u0552\u0582\u0553\u0583\u0554\u0584\u0555\u0585\u0556\u0586\u055A\uFFFD"},rk1048:{type:"_sbcs",chars:"\u0402\u0403\u201A\u0453\u201E\u2026\u2020\u2021\u20AC\u2030\u0409\u2039\u040A\u049A\u04BA\u040F\u0452\u2018\u2019\u201C\u201D\u2022\u2013\u2014\uFFFD\u2122\u0459\u203A\u045A\u049B\u04BB\u045F\xA0\u04B0\u04B1\u04D8\xA4\u04E8\xA6\xA7\u0401\xA9\u0492\xAB\xAC\xAD\xAE\u04AE\xB0\xB1\u0406\u0456\u04E9\xB5\xB6\xB7\u0451\u2116\u0493\xBB\u04D9\u04A2\u04A3\u04AF\u0410\u0411\u0412\u0413\u0414\u0415\u0416\u0417\u0418\u0419\u041A\u041B\u041C\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0430\u0431\u0432\u0433\u0434\u0435\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F"},tcvn:{type:"_sbcs",chars:`\0\xDA\u1EE4\u1EEA\u1EEC\u1EEE\x07\b
|
|
@@ -2111,8 +2111,8 @@ Learn more: \x1B[34m${n}\x1B[0m
|
|
|
2111
2111
|
`;T?(0,C1.writeFileSync)(g,U,"utf8"):(0,C1.appendFileSync)(g,U,"utf8"),Jst.set(g,qWr(I))}catch{}}function XFs(e,t){let n;try{n=(0,C1.readdirSync)(e).filter(a=>a.startsWith("model-io-")&&a.endsWith(".jsonl"))}catch{return}let o=n.length-t;if(o<=0)return;let s=n.map(a=>{try{return{name:a,mtimeMs:(0,C1.statSync)((0,cOe.join)(e,a)).mtimeMs}}catch{return{name:a,mtimeMs:0}}}).sort((a,l)=>a.mtimeMs-l.mtimeMs).map(a=>a.name);for(let a of s){if(o<=0)break;let l=(0,cOe.join)(e,a);try{(0,C1.rmSync)(l,{force:!0}),Jst.delete(l),o-=1}catch{}}}function QFs(e){return e?e.replace(/[^a-zA-Z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80):""}function e4s(e){return(0,cOe.join)((0,WWr.homedir)(),".zcode","cli",e?"debug":"rollout")}function $Wr(e){return JSON.stringify(e)}function t4s(e){try{return(0,C1.statSync)(e).size}catch{return 0}}function n4s(e,t){if(t)return e;let n=rre(e.request),o=rre(e.response);return{...e,request:n&&r4s(n,!!e.error),response:o&&o4s(o)}}function r4s(e,t){let n={...e};delete n.sdkMessages;let o=rre(n.body);if(o&&!t){let s={...o};delete s.messages,n.body=s}return n}function o4s(e){let t={...e};return delete t.body,t}function i4s(e,t,n){let o=rre(e.request);return o?{...e,request:s4s(o,t?.request,n)}:e}function s4s(e,t,n){let o={...e};Cln(o,t?.messages,{collectionKey:"messages",countKey:"messageCount",kindKey:"messagesKind",offsetKey:"messageOffset"},n),Cln(o,t?.sdkMessages,{collectionKey:"sdkMessages",countKey:"sdkMessageCount",kindKey:"sdkMessagesKind",offsetKey:"sdkMessageOffset"},n);let s=rre(o.body);if(s){let a={...s},l={collectionKey:"messages",countKey:"bodyMessageCount",kindKey:"bodyMessagesKind",offsetKey:"bodyMessageOffset"};n.preserveFullBodyMessages&&Array.isArray(a.messages)?(o[l.countKey]=a.messages.length,o[l.kindKey]="full",o[l.offsetKey]=0):Cln(a,t?.bodyMessages,l,n,o),o.body=a}return o}function Cln(e,t,n,o,s=e){let a=e[n.collectionKey];if(!Array.isArray(a))return;if(s[n.countKey]=a.length,a4s(a,t)){e[n.collectionKey]=a.slice(t.count),s[n.kindKey]="delta",s[n.offsetKey]=t.count;return}let l=Math.max(1,o.maxBaselineMessages);if(a.length>l){let u=a.length-l;e[n.collectionKey]=a.slice(u),s[n.kindKey]="tail",s[n.offsetKey]=u;return}s[n.kindKey]="full",s[n.offsetKey]=0}function a4s(e,t){if(!t||t.count<=0||e.length<t.count)return!1;let n=uG(e[0]),o=uG(e[t.count-1]);return n===t.firstFingerprint&&o===t.lastFingerprint&&l4s(e,t)}function qWr(e){let t=rre(e.request);return t?{request:c4s(t)}:{}}function c4s(e){let t=rre(e.body);return{bodyMessages:Eln(t?.messages),messages:Eln(e.messages),sdkMessages:Eln(e.sdkMessages)}}function Eln(e){if(Array.isArray(e))return{count:e.length,firstFingerprint:uG(e[0]),lastFingerprint:uG(e[e.length-1]),sampleFingerprints:KWr(e)}}function l4s(e,t){let n=t.sampleFingerprints;if(!n)return!0;let o=KWr(e,t.count);return o.length===n.length&&o.every((s,a)=>s===n[a])}function KWr(e,t=e.length){if(t<=0)return[];let n=t-1;return[...new Set([0,Math.floor(n*.25),Math.floor(n*.5),Math.floor(n*.75),n])].map(s=>uG(e[s]))}function uG(e,t=0){if(e==null)return String(e);if(typeof e=="string")return["string",String(e.length),e.slice(0,BWr),e.slice(-BWr)].join(":");if(typeof e!="object")return`${typeof e}:${String(e)}`;if(t>=3)return Array.isArray(e)?`array:${e.length}`:"object";if(Array.isArray(e))return["array",String(e.length),uG(e[0],t+1),uG(e[e.length-1],t+1)].join(":");let n=e,o=Object.keys(n).sort(),s=o.slice(0,12);return["object",String(o.length),...s.map(a=>`${a}=${uG(n[a],t+1)}`)].join(":")}function rre(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function u4s(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function ZWr(e){return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{name:"UnknownError",message:String(e)}}var C1,WWr,cOe,VFs,HFs,GFs,JFs,KFs,BWr,Jst,UWr,Rln=Y(()=>{"use strict";C1=require("node:fs"),WWr=require("node:os"),cOe=require("node:path");ms();Dst();DWr();Gst();B0e();O0e();VFs=3,HFs=64*1024*1024,GFs=256*1024*1024,JFs=64,KFs=256,BWr=512,Jst=new Map;r(Kst,"shouldRecordModelIO");r(Zst,"isDevelopmentModelIOEnv");r(Aln,"recordGenerateTextDebug");r(Pln,"recordStreamTextDebug");r(VWr,"buildFallbackRequestBodyFromOptions");r(ZFs,"resolveStreamModelIOAggregate");r(HWr,"modelIOReasoningText");UWr=1e3;r(YFs,"resolveFailedStreamModelIOAggregate");r(BF,"settleModelIOValue");r(zWr,"settleModelIOValueWithTimeout");r(GWr,"normalizeRuntimeEnv");r(JWr,"writeModelIODebugRecord");r(XFs,"rotateModelIOFiles");r(QFs,"sanitizeFileSegment");r(e4s,"getModelIOBaseDir");r($Wr,"stringifyDebugRecord");r(t4s,"readFileSize");r(n4s,"prepareModelIORecordForWrite");r(r4s,"prepareProductionRequestRecord");r(o4s,"prepareProductionResponseRecord");r(i4s,"compactModelIORecord");r(s4s,"compactModelIORequest");r(Cln,"compactMessageCollection");r(a4s,"canStoreDeltaFromState");r(qWr,"buildModelIOCompactionState");r(c4s,"buildRequestCompactionState");r(Eln,"buildCollectionState");r(l4s,"hasSameSampleFingerprints");r(KWr,"fingerprintCollectionSamples");r(uG,"fingerprintValue");r(rre,"asRecord");r(u4s,"removeUndefined");r(ZWr,"serializeError")});function XWr(e){if(!e||typeof e!="object")return;let t=e.context;if(!t||typeof t!="object")return;let n=t.errorPhase;return typeof n=="string"&&YWr.has(n)?n:void 0}function QWr(e,t,n){return{...typeof n=="string"&&YWr.has(n)?{errorPhase:n}:{},exceptionKind:d4s(e,t)}}function d4s(e,t){if(t.reason===_s.NetworkError||t.reason===_s.ProxyError||t.reason===_s.StaleConnection||t.reason===_s.StreamIdleTimeout||t.reason===_s.Timeout||t.reason===_s.TlsError)return"transport";if(X3(e))return"provider_business";if(Nd.isInstance(e))return"api_call";let o=p4s(e);return o==="AiSdkModelAdapterError"||o==="ModelProtocolError"?"protocol":o==="TypeError"?"type_error":o&&/validation|zod|parseerror|jsonparse/iu.test(o)?"validation":"generic"}function p4s(e){if(e instanceof Error)return e.name||e.constructor.name;if(!e||typeof e!="object")return;let t=e.name;return typeof t=="string"&&t.trim()?t.trim():void 0}function j7(e,t,n){return{errorCode:t.code,errorPhase:n,exceptionType:f4s(e),retryAfterMs:t.retryAfterMs,...iG(e)}}function Yst(e){for(let t of["x-request-id","request-id","x-amzn-requestid","x-amz-request-id","cf-ray"]){let n=Object.entries(e).find(([o])=>o.toLowerCase()===t)?.[1];if(n?.trim())return n.trim().slice(0,256)}}function f4s(e){if(e instanceof Error)return e.name||e.constructor.name;if(e&&typeof e=="object"){let t=e.name;if(typeof t=="string"&&t.trim())return t.trim().slice(0,128)}}var YWr,Xst=Y(()=>{"use strict";nr();P0e();nre();YWr=new Set(["prepare","configuration","connect","response","stream","parse","validation","unhandled"]);r(XWr,"readModelFailureErrorPhase");r(QWr,"modelFailureAttributionFields");r(d4s,"classifyModelFailureExceptionKind");r(p4s,"errorName");r(j7,"modelFailureStatusFields");r(Yst,"providerRequestIdFromHeaders");r(f4s,"exceptionType")});function ire(e,t,n){let o=e.baseDelayMs*e.backoffFactor**Math.max(0,t-1),s=Math.min(o,e.maxDelayMs);return y4s(n,o)?n:!e.jitter||s===0?s:Math.round(s*(.5+Math.random()*.5))}async function sre(e,t){if(e<=0){if(t?.aborted)throw Dln(t);return}await new Promise((n,o)=>{if(t?.aborted){o(Dln(t));return}let s=setTimeout(n,e),a=r(()=>{clearTimeout(s),o(Dln(t))},"onAbort");t?.addEventListener("abort",a,{once:!0})})}function tB(e){e.logger?.warn("Model retry delay decision inspected",{...sG(e.statusContext,e.attempt),canRetry:e.canRetry,delayMs:e.delayMs,event:"model.retry.delay.resolved",nextAttempt:e.canRetry?e.attempt+1:void 0,reason:e.failure.reason,retryAfterHeader:z0e(e.responseHeaders,"retry-after"),retryAfterMs:e.failure.retryAfterMs,retryAfterMsHeader:z0e(e.responseHeaders,"retry-after-ms"),retryAfterSource:v4s(e.failure.retryAfterMs,e.responseHeaders),retryReason:e.failure.retryReason,status:e.canRetry?"waiting":"failed",statusCode:e.failure.statusCode,xShouldRetryHeader:z0e(e.responseHeaders,"x-should-retry")})}function NM(e,t,n,o,s){let a=D_(e),l=X3(a)??JDe(a),u={attempt:o,maxAttempts:n.maxAttempts,modelId:n.modelId,...QWr(a,t,s?.errorPhase),...b4s(l),providerId:n.providerId,providerKind:n.providerKind,reason:t.reason,requestId:n.requestId,retryable:t.retryable,...t.retryAfterMs===void 0?{}:{retryAfterMs:t.retryAfterMs},source:_4s(l??e,t,s),statusCode:t.statusCode,traceId:n.traceId,transport:n.transport};return e instanceof w1?e.enrichContext({...e.context,...u,...s,...g4s(e.context)}):new w1(t.code,t.message,{cause:e,context:{...u,...s}})}function g4s(e){return e?Object.fromEntries(h4s.flatMap(t=>e[t]===void 0?[]:[[t,e[t]]])):{}}function _4s(e,t,n){let o=t.reason;return o===_s.Cancelled?GH.Runtime:o===_s.NetworkError||o===_s.ProxyError||o===_s.StaleConnection||o===_s.StreamIdleTimeout||o===_s.Timeout||o===_s.TlsError?GH.Network:t.statusCode!==void 0||tG(e)?GH.Provider:t.code===Cs.InvalidModelResponse?GH.Provider:n?.streamFailurePhase==="response_body"||n?.errorPhase==="response"||n?.errorPhase==="stream"||n?.errorPhase==="parse"?GH.Provider:o===_s.InvalidRequest||o===_s.ProviderNotConfigured||o===_s.Unknown?GH.Runtime:GH.Provider}function y4s(e,t){return e!==void 0&&Number.isFinite(e)&&e>=0&&(e<=m4s||e<t)}function v4s(e,t){let n=z0e(t,"x-should-retry")?.trim().toLowerCase();return n==="false"||n==="0"?"blocked_by_x_should_retry":e!==void 0?"provider_header":z0e(t,"retry-after-ms")!==void 0||z0e(t,"retry-after")?"header_unparsed_or_ignored":"missing"}function z0e(e,t){let n=t.toLowerCase();return Object.entries(e).find(([o])=>o.toLowerCase()===n)?.[1]}function Dln(e){let t=e?.reason;if(t instanceof Error)return t;let n=new Error("The model request was cancelled.");return n.name="AbortError",n}function b4s(e){if(tG(e))return{providerCode:e.providerCode,providerRequestId:e.providerRequestId,responseBodySummary:e.responseBodySummary,responseStatus:e.responseStatus}}var m4s,h4s,ore,Qst=Y(()=>{"use strict";nr();P7();nre();Zcn();O7();zne();aG();Xst();m4s=5*6e4,h4s=["errorPhase","exceptionKind","providerCode","providerRequestId","reason","responseBodySummary","responseStatus","retryable","source","statusCode"],ore=class extends Error{static{r(this,"TerminalStreamChunkError")}adapterError;constructor(t){super(t.message),this.adapterError=t,this.name="TerminalStreamChunkError",this.cause=t.cause??t}};r(ire,"calculateRetryDelay");r(sre,"sleep");r(tB,"logRetryDelayDecision");r(NM,"toAdapterError");r(g4s,"existingReliableAttributionContext");r(_4s,"modelFailureSource");r(y4s,"isReasonableRetryAfterMs");r(v4s,"retryAfterSource");r(z0e,"readHeader");r(Dln,"createAbortError");r(b4s,"providerBusinessErrorContext")});function k4s(){return{code:Cs.InvalidModelResponse,message:w4s,reason:_s.Unknown,retryReason:Qc.ServerError,retryable:!0}}function lOe(e){return!e.abortSignal?.aborted&&e.retryCount<S4s&&e.attempt<e.maxAttempts}async function eat(e){let t=k4s();await zv({...e.statusContext,attempt:e.attempt,durationMs:e.completedAt-e.startedAt,errorCode:t.code,errorPhase:e.errorPhase,message:t.message,reason:t.reason,requestHeaderCount:Object.keys(e.requestHeaders).length,requestHeaders:e.requestHeaders,responseHeaderCount:Object.keys(e.responseHeaders).length,responseHeaders:e.responseHeaders,retryable:!0,...e.streamOutputCommitted!==void 0?{streamOutputCommitted:e.streamOutputCommitted}:{},timestamp:new Date(e.completedAt).toISOString(),type:"model_request_failed"},{logger:e.logger,requestStatusSink:e.requestStatusSink,statusSink:e.statusSink});let n=ire(e.retry,e.retryBudgetAttempt);tB({attempt:e.attempt,canRetry:!0,delayMs:n,failure:t,logger:e.logger,responseHeaders:e.responseHeaders,statusContext:e.statusContext}),await zv({...e.statusContext,attempt:e.attempt,delayMs:n,errorCode:t.code,message:t.message,nextAttempt:e.attempt+1,reason:t.retryReason,requestHeaderCount:Object.keys(e.requestHeaders).length,requestHeaders:e.requestHeaders,responseHeaderCount:Object.keys(e.responseHeaders).length,responseHeaders:e.responseHeaders,retryAfterMs:t.retryAfterMs,timestamp:new Date().toISOString(),type:"model_retry_scheduled"},{logger:e.logger,requestStatusSink:e.requestStatusSink,statusSink:e.statusSink}),await sre(n,e.abortSignal)}var S4s,w4s,Oln=Y(()=>{"use strict";nr();Qst();aG();S4s=1,w4s="Model returned no text, no tool calls, and no usage before completing the turn.";r(k4s,"createEmptyCompletionFailure");r(lOe,"canRetryEmptyCompletion");r(eat,"scheduleEmptyCompletionRetry")});function uOe(e){return iG(e).providerErrorCode===x4s}var x4s,$0e,Mln=Y(()=>{"use strict";nre();x4s="3007";r(uOe,"isCaptchaRejection");$0e=class{static{r(this,"CaptchaRequestRetry")}request;model;used=!1;pending=!1;constructor(t,n){this.request=t,this.model=n}get extraAttempts(){return Number(this.used)}takeReason(){let t=this.pending?"captcha-retry":"model-request";return this.pending=!1,t}claim(t,n=!1){return n||this.used||this.request.abortSignal?.aborted||!this.request.refreshRuntimeHeadersBeforeAttempt||this.model.accountAccess?.mode!=="start-plan"||!uOe(t)?!1:(this.used=!0,this.pending=!0,!0)}}});async function tat(e){let t=e.request.abortSignal;t?.throwIfAborted();let n=e.resolveModel();if(!e.request.refreshRuntimeHeadersBeforeAttempt)return n;try{let o=await T4s(()=>e.request.refreshRuntimeHeadersBeforeAttempt({attempt:e.attempt,reason:e.reason??"model-request",abortSignal:t,providerId:String(n.providerId),modelId:String(n.modelId),traceContext:e.request.traceContext}),t);if(t?.throwIfAborted(),!o.headersApplied||!o.requestAuth)throw new Error("Provider request auth was not returned before model request attempt.");return e.resolveModel(o.requestAuth)}catch(o){throw t?.aborted||o instanceof Tb&&o.code===Cs.ModelRequestAuthMissing?o:new are(o)}}async function T4s(e,t){return t?(t.throwIfAborted(),new Promise((n,o)=>{let s=r(()=>o(t.reason),"onAbort");t.addEventListener("abort",s,{once:!0}),Promise.resolve().then(()=>(t.throwIfAborted(),e())).then(n,o).finally(()=>t.removeEventListener("abort",s))})):e()}var are,Nln=Y(()=>{"use strict";nr();are=class extends Error{static{r(this,"RuntimeHeadersRefreshError")}constructor(t){super(t instanceof Error?t.message:String(t),{cause:t}),this.name="RuntimeHeadersRefreshError"}};r(tat,"resolveModelForAttempt");r(T4s,"waitForHeaders")});function tVr(e,t){return e.reason===_s.Cancelled?{decision:"cancelled"}:t!==void 0&&I4s.has(t)?{decision:"stop",kind:"quota"}:e.reason===_s.AuthFailed?{decision:"stop",kind:"auth"}:e.reason===_s.ProviderNotConfigured||C4s.has(e.code)?{decision:"stop",kind:"not_configured"}:e.code===Cs.ModelNotFound?{decision:"stop",kind:"model_unavailable"}:e.reason===_s.ContextExceeded?{decision:"context_exceeded"}:e.reason===_s.InvalidRequest&&e.code!==Cs.InvalidModelResponse?{decision:"stop",kind:"invalid_request"}:{decision:"retry"}}function rat(e,t,n){return XDe(t)?tVr(e,n).decision==="retry":gqr(e)}function nVr(e){let n=eVr(e)??eVr(e?.cause??void 0);if(n===void 0)return;let{context:o,code:s,message:a}=n,l=nat(o.reason);if(l===void 0)return;let u=E4s(o.providerCode),f=tVr({code:s,reason:l,retryable:o.retryable===!0},u),g=o.retryAfterMs,_={policy:f,reason:l};u!==void 0&&(_.providerCode=u);let b=nat(o.providerId);b!==void 0&&(_.providerId=b);let w=nat(o.modelId);return w!==void 0&&(_.modelId=w),a.length>0&&(_.rawMessage=a),f.decision==="stop"&&f.kind==="quota"&&typeof g=="number"&&Number.isFinite(g)&&g>0&&(_.resetAt=Date.now()+g),_}function eVr(e){if(typeof e!="object"||e===null)return;let t=e;return t.name!=="AiSdkModelAdapterError"?void 0:{context:typeof t.context=="object"&&t.context!==null?t.context:{},code:typeof t.code=="string"?t.code:"",message:typeof t.message=="string"?t.message:""}}function nat(e){return typeof e=="string"&&e.length>0?e:void 0}function E4s(e){return typeof e=="number"&&Number.isFinite(e)?String(Math.trunc(e)):nat(e)}var I4s,C4s,oat=Y(()=>{"use strict";nr();nre();eOe();I4s=new Set(["1005","1308","1310","1313","1316","1317","1318","1319","1320","1321","2056","20097","insufficient_quota","credit_balance_exhausted","organization_spend_limit_exceeded","project_spend_limit_exceeded","organization_usage_limit_exceeded","exceeded_current_quota_error"]),C4s=new Set([Cs.ProviderNotFound,Cs.ProviderNotConfigured,Cs.ModelConfigMissing,Cs.InvalidModelSelection,Cs.ModelRequestAuthMissing]);r(tVr,"resolveWorkflowModelFailurePolicy");r(rat,"retryAllowedByFailurePolicy");r(nVr,"inspectWorkflowModelFailure");r(eVr,"readAdapterError");r(nat,"stringValue");r(E4s,"codeValue")});function sVr(e,t){let n=O4s(e,t),o=N4s(n),s=L4s(o),a=F4s(s);return j4s(a)}function R4s(e){let t=aVr(e,cVr);if(t===e)return e;let n=t.slice();for(let o=0;o<t.length;o+=1){if(t[o]===e[o])continue;let s=t[o];if(s.role!=="assistant"||!Array.isArray(s.content))continue;let a=s.content.filter(l=>l.type!=="text"||l.text.trim().length>0);!sat(s)&&a.every(l=>l.type==="reasoning")&&(a=[...a,{type:"text",text:A4s}]),n[o]={...s,content:a}}return n}function iat(e,t){if(!D4s(t))return;let n=R4s(e);return n===e?void 0:n}function D4s(e){let t=D_(e);if(R0e(t)!==400)return!1;let n=q4s(t).toLowerCase();if(n.includes("signature in thinking block"))return!0;let o=n.includes("thinking block")||n.includes("`thinking`")||n.includes("redacted_thinking"),s=n.includes("cannot be modified")||n.includes("invalid signature");return o&&s}function O4s(e,t){return t?aVr(e,(n,o)=>!o.providerId||!o.modelId||o.modelId===t.modelId&&M4s(o.providerId,t.providerId)?!1:cVr(n)):e}function M4s(e,t){return e===t||P4s.some(n=>n.includes(e)&&n.includes(t))}function aVr(e,t){let n;for(let o=0;o<e.length;o+=1){let s=e[o];if(s.role!=="assistant"||!Array.isArray(s.content))continue;let a=s.content.filter(l=>l.type!=="reasoning"||!t(l,s));a.length!==s.content.length&&(n??=e.slice(),n[o]={...s,content:a})}return n??e}function N4s(e){let t=e.filter(n=>n.role!=="assistant"||sat(n)||!Array.isArray(n.content)||n.content.length===0?!0:!n.content.every(o=>o.type==="reasoning"));return t.length===e.length?e:t}function L4s(e){let t=e.at(-1);if(t?.role!=="assistant"||!Array.isArray(t.content))return e;let n=t.content.length;for(;n>0&&t.content[n-1]?.type==="reasoning";)n-=1;if(n===t.content.length)return e;let o=e.slice();return o[o.length-1]={...t,content:t.content.slice(0,n)},o}function F4s(e){let t=e.filter(n=>n.role!=="assistant"||sat(n)||!Array.isArray(n.content)||n.content.length===0?!0:!n.content.every(o=>o.type==="text"&&(o.text.trim().length===0||o.text.trim()===iVr)));return t.length===e.length?e:B4s(t)}function j4s(e){let t;for(let n=0;n<e.length-1;n+=1){let o=e[n];o.role!=="assistant"||!Array.isArray(o.content)||o.content.length>0||sat(o)||(t??=e.slice(),t[n]={...o,content:[{type:"text",text:iVr}]})}return t??e}function B4s(e){let t=[];for(let n of e){let o=t.at(-1);if(!U4s(o,n)){t.push(n);continue}let s={role:"user",content:z4s(o.content,n.content)},a=n.cacheControl??o.cacheControl;a&&(s.cacheControl={...a}),t[t.length-1]=s}return t}function U4s(e,t){return e?.role!=="user"||t.role!=="user"?!1:!rVr(e)&&!rVr(t)}function rVr(e){return e.role==="user"&&!!(e.toolCallId||e.toolName)}function z4s(e,t){let n=oVr(e),o=oVr(t),s=n.at(-1),a=o[0];return s?.type==="text"&&a?.type==="text"&&(n[n.length-1]={...s,text:`${s.text}
|
|
2112
2112
|
`}),[...n,...o]}function oVr(e){return typeof e=="string"?[{type:"text",text:e}]:[...e]}function cVr(e){let t=$4s(e.providerOptions);return typeof t.signature=="string"&&t.signature.length>0||typeof t.redactedData=="string"}function sat(e){return(e.toolCalls?.length??0)>0}function $4s(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e.anthropic;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function q4s(e){return e instanceof Error?e.message:e&&typeof e=="object"&&"message"in e?String(e.message??""):String(e??"")}var iVr,A4s,P4s,aat=Y(()=>{"use strict";ms();O7();iVr="(no content)",A4s="[Thinking removed]",P4s=[["builtin:zai-coding-plan",rm.zaiIndividualCodingPlan,rm.zaiTeamCodingPlan],["builtin:bigmodel-coding-plan",rm.bigmodelIndividualCodingPlan,rm.bigmodelTeamCodingPlan]];r(sVr,"normalizeReasoningHistory");r(R4s,"removeRejectedReasoning");r(iat,"repairReasoningHistoryAfterSignatureRejection");r(D4s,"isThinkingSignatureRejection");r(O4s,"removeCrossModelReasoning");r(M4s,"areReasoningProvidersCompatible");r(aVr,"filterReasoningBlocks");r(N4s,"removeReasoningOnlyAssistants");r(L4s,"removeTrailingReasoning");r(F4s,"removeWhitespaceOnlyAssistants");r(j4s,"repairEmptyAssistantContent");r(B4s,"mergeAdjacentUserMessages");r(U4s,"canMergeAdjacentUserMessages");r(rVr,"isToolResultUserMessage");r(z4s,"mergeUserContent");r(oVr,"contentAsBlocks");r(cVr,"isSignedOrRedactedReasoning");r(sat,"hasToolCalls");r($4s,"anthropicOptions");r(q4s,"errorMessage")});async function cat(e){if(e.admission===void 0)return W4s;let t=typeof e.admission.tryAcquire=="function",n=t?e.admission.tryAcquire({model:e.model}):void 0;if(n===void 0){let s=Date.now();t&&await e.onQueued?.(),n=await e.admission.acquire({model:e.model,...e.signal===void 0?{}:{signal:e.signal}}),t&&await e.onAdmitted?.(Date.now()-s)}let o=!1;return{ticket:n,release(){o||(o=!0,n.release())}}}var W4s,Lln=Y(()=>{"use strict";W4s={release(){}};r(cat,"admitAttempt")});async function lVr(e){let t=e.request.modelRetryBudget,n=r(_=>QDe(t,e.retry.maxAttempts+_),"statusMaxAttempts"),o=Ist({maxAttempts:n(0),request:e.request,resolved:e.resolved,transport:WV.Http}),s=e.request.metadata?.skipTranscript!==!0&&Kst(e.env),a=Zst(e.env),l=e.request.messages,u=!1,f=new $0e(e.request,e.resolved),g=0;for(let _=1;kst(t,_,e.retry.maxAttempts+Number(u)+f.extraAttempts);_+=1){let b=_-Number(u)-f.extraAttempts,w={...e.request,messages:l},T=Date.now(),I=e.resolved,E=Cst({...o,maxAttempts:n(Number(u)+f.extraAttempts)},_),R,L=!1,U={},B=0,z;try{z=await cat({admission:e.request.modelRequestAdmission,model:{providerId:String(I.providerId),modelId:String(I.modelId)},signal:e.request.abortSignal,...Est(E,_,cre(e))})}catch($){let J=DM($,e.request.abortSignal);throw await zv({...E,attempt:_,message:J.message,reason:J.reason,requestHeaderCount:B,requestHeaders:U,retryable:!1,statusCode:J.statusCode,...j7($,J,"connect"),timestamp:new Date().toISOString(),type:"model_request_failed"},{...cre(e),failureError:D_($)}),NM($,J,E,_,{errorPhase:"connect"})}try{I=await tat({attempt:_,reason:f.takeReason(),request:w,resolveModel:e.resolveModel});let $=await Pst({env:e.env,providerKind:I.providerKind,sessionId:E.sessionId});R=gWr({anthropicMetadataUserId:$,env:e.env,includeModelIO:s,request:w,resolved:I,statusContext:E}),U=MM(R.headers),B=Object.keys(U).length,await zv({...E,attempt:_,requestHeaderCount:B,requestHeaders:U,timestamp:new Date(T).toISOString(),type:"model_request_started"},cre(e,z));let J=e.runtime.generateText(R);L=!0;let q=await H4s(J,e.request.abortSignal),ie=MM(q?.response?.headers),ae=lG({providerId:String(I.providerId),providerKind:I.providerKind,source:{finishReason:q.finishReason,providerMetadata:q.providerMetadata,rawFinishReason:q.providerMetadata?.rawFinishReason,response:q.response}});if(ae)throw ae;let Ce=F7(q.totalUsage??q.usage),pe=CWr(q,e.logger),ze=iOe(q,pe),rt=sOe(q),Pe=e.request.responseJsonSchema?V4s(q):q.text,Tt=qst(q.reasoning),Ye=(Tt??[]).reduce((St,kt)=>St+kt.text.length,0);if(e.request.preserveProviderStreamBoundaries!==!0&&aOe({finishReason:q.finishReason,reasoningLength:Ye,textLength:Pe.length,toolCallCount:pe?.length??0,usage:Ce})&&lOe({abortSignal:e.request.abortSignal,attempt:_,maxAttempts:e.retry.maxAttempts,retryCount:g})){let St=Date.now();xln({attempt:_,completedAt:St,logger:e.logger,result:q,startedAt:T,statusContext:E,toolCallCount:pe?.length??0,usage:Ce}),g+=1,await eat({abortSignal:e.request.abortSignal,attempt:_,completedAt:St,errorPhase:"response",logger:e.logger,requestHeaders:U,requestStatusSink:e.request.statusSink,responseHeaders:ie,retry:e.retry,retryBudgetAttempt:b,startedAt:T,statusContext:E,statusSink:e.statusSink});continue}let Fe=Date.now();return Aln({modelIoFullRetentionEnabled:e.modelIoFullRetentionEnabled,attempt:_,debugDir:e.debugDir,isDev:a,normalizedToolCalls:pe,options:R,recordModelIO:s,request:w,requestId:E.requestId,resolved:I,result:q,startedAt:T}),xln({attempt:_,completedAt:Fe,logger:e.logger,result:q,statusContext:E,startedAt:T,toolCallCount:pe?.length??0,usage:Ce}),await zv({...E,attempt:_,durationMs:Fe-T,finishReason:q.finishReason,requestHeaderCount:B,requestHeaders:U,responseHeaderCount:Object.keys(ie).length,responseHeaders:ie,providerRequestId:Yst(ie),timestamp:new Date(Fe).toISOString(),type:"model_request_completed",usage:Ce},cre(e,z)),{text:Pe,finishReason:q.finishReason,usage:Ce,reasoning:Tt,toolCalls:pe,toolResults:ze,sources:rt,providerMetadata:q.providerMetadata}}catch($){if($ instanceof Tb&&$.code===Cs.ModelRequestAuthMissing)throw $;let J=Date.now(),q=DM($,e.request.abortSignal);$ instanceof are&&(q.message=$.message,q.retryable=!1);let ie=KDe({offPeak:I.accountAccess?.mode==="off-peak",failure:q,error:D_($)}),ae=ie?.kind==="ticketExpired"?{...q,retryable:!1,message:ZDe(q.message)}:ie?.kind==="queued"?{...q,retryable:!0,retryReason:Qc.OffpeakQueued}:q,Ce=MM(RM(D_($))),pe=!u&&I.providerKind==="anthropic"?iat(l,$):void 0,ze=pe!==void 0;pe&&(u=!0,l=pe,E={...E,maxAttempts:n(1+f.extraAttempts)});let rt=ie?.kind==="queued"?!0:wst(t,b,e.retry.maxAttempts)&&rat(ae,t,iG($).providerErrorCode),Pe=f.claim($,R===void 0);Pe&&(E={...E,maxAttempts:n(Number(u)+f.extraAttempts)});let Tt=Pe||ze||rt;if(R&&Aln({modelIoFullRetentionEnabled:e.modelIoFullRetentionEnabled,attempt:_,debugDir:e.debugDir,error:$,isDev:a,normalizedToolCalls:void 0,options:R,recordModelIO:s,request:w,requestId:E.requestId,resolved:I,startedAt:T}),await zv({...E,attempt:_,durationMs:J-T,message:ae.message,reason:ae.reason,requestHeaderCount:B,requestHeaders:U,responseHeaderCount:Object.keys(Ce).length,responseHeaders:Ce,retryable:Tt,statusCode:ae.statusCode,...j7($,ae,R?"response":"prepare"),timestamp:new Date(J).toISOString(),type:"model_request_failed"},{...cre(e,z),failureError:D_($)}),!Tt)throw tB({attempt:_,canRetry:Tt,failure:ae,logger:e.logger,responseHeaders:Ce,statusContext:E}),NM($,ae,E,_,{errorPhase:L?"response":"prepare"});if(Pe){await Fln(e,E,_,0,{...ae,retryReason:Qc.AuthRefresh},U,Ce);continue}if(ze){e.logger?.warn("Retrying model request after thinking signature rejection",{attempt:_,event:"model.reasoning_signature_repair.retry",maxAttempts:E.maxAttempts,nextAttempt:_+1,requestId:E.requestId,status:"waiting"}),await Fln(e,E,_,0,{...ae,retryReason:Qc.ReasoningSignatureRepair},U,Ce,z);continue}let Ye=ie?.kind==="queued"?ie.delayMs:ire(e.retry,b,ae.retryAfterMs);tB({attempt:_,canRetry:Tt,delayMs:Ye,failure:ae,logger:e.logger,responseHeaders:Ce,statusContext:E}),await Fln(e,E,_,Ye,ae,U,Ce,z),z.release();try{await sre(Ye,e.request.abortSignal)}catch(Fe){let St=DM(Fe,e.request.abortSignal),kt=MM(RM(D_(Fe)));throw await zv({...E,attempt:_,message:St.message,reason:St.reason,requestHeaderCount:B,requestHeaders:U,responseHeaderCount:Object.keys(kt).length,responseHeaders:kt,retryable:!1,statusCode:St.statusCode,...j7(Fe,St,"connect"),timestamp:new Date().toISOString(),type:"model_request_failed"},{...cre(e),failureError:D_(Fe)}),NM(Fe,St,E,_,{errorPhase:"connect"})}ie?.kind==="queued"&&(_-=1)}finally{z.release()}}throw new w1(Cs.ModelRequestFailed,"Model request failed before an attempt could complete",{context:{requestId:o.requestId}})}function V4s(e){let t=e.output;if(t===void 0)throw new Error("Structured output is unavailable");let n=JSON.stringify(t);if(n===void 0)throw new Error("Structured output is unavailable");return n}function H4s(e,t){return t?new Promise((n,o)=>{let s=r(()=>{t.removeEventListener("abort",a)},"cleanup"),a=r(()=>{s(),o(t.reason instanceof Error?t.reason:new Error("Model request was cancelled."))},"onAbort");if(t.aborted){a();return}t.addEventListener("abort",a,{once:!0}),e.then(l=>{s(),n(l)},l=>{s(),o(l)})}):e}function cre(e,t){return{clientSigningObservations:e.resolved?.clientSigningObservations,logger:e.logger,requestStatusSink:e.request.statusSink,statusSink:e.statusSink,...t?.ticket===void 0?{}:{admissionTicket:t.ticket}}}async function Fln(e,t,n,o,s,a,l,u){await zv({...t,attempt:n,delayMs:o,message:s.message,nextAttempt:n+1,reason:s.retryReason,requestHeaderCount:Object.keys(a).length,requestHeaders:a,responseHeaderCount:Object.keys(l).length,responseHeaders:l,statusCode:s.statusCode,errorCode:s.code,retryAfterMs:s.retryAfterMs,timestamp:new Date().toISOString(),type:"model_retry_scheduled"},cre(e,u))}var uVr=Y(()=>{"use strict";nr();nre();O7();Qcn();zne();Dst();yln();zst();B0e();Rln();Gst();Vst();Oln();Qst();aG();Mln();Nln();oat();Xst();aat();Lln();eOe();r(lVr,"runGenerateText");r(V4s,"serializeStructuredOutput");r(H4s,"waitForGenerateTextOrAbort");r(cre,"statusPublishOptions");r(Fln,"publishRetryScheduledStatus")});function dVr(e){return e.type==="reasoning_delta"||e.type==="text_delta"?e.text.length===0:G4s.has(e.type)}var G4s,pVr=Y(()=>{"use strict";G4s=new Set(["start","text_start","text_end","reasoning_start","reasoning_end","tool_input_start","tool_input_delta","tool_input_end"]);r(dVr,"isRetrySafePreludeStreamEvent")});function mVr(e){if(!e)return;let n=Object.entries(e).find(([o])=>o.toLowerCase()===J4s)?.[1]?.trim();return n&&n.length>0?n:void 0}var J4s,fVr,jln=Y(()=>{"use strict";J4s="x-aliyun-captcha-verify-param",fVr="Captcha verification failed or the verify token was rejected.";r(mVr,"readCaptchaVerifyParam")});function hVr(e){if(!(e.providerKind!=="openai-compatible"||!e.captcha)&&mVr(e.headers))return new S2({providerCode:"3007",providerId:e.providerId,providerKind:e.providerKind,providerMessage:fVr,responseStatus:200,statusCode:403})}var gVr=Y(()=>{"use strict";jln();P7();r(hVr,"createZcodePlanCaptchaEmptyStreamBusinessError")});var lat,_Vr=Y(()=>{"use strict";vln();bln();lat=class{static{r(this,"StreamingToolCallAssembler")}completedStreamingInputIds=new Set;logger;normalizedToolCalls=new Map;providerExecutedById=new Map;streamingInputIds=new Set;constructor(t={}){this.logger=t.logger}snapshotNormalizedToolCalls(){return Array.from(this.normalizedToolCalls.values(),t=>({...t}))}handle(t){switch(t.type){case"tool_input_start":return this.handleToolInputStart(t);case"tool_input_delta":return this.normalizedToolCalls.has(t.id)?[]:[t];case"tool_input_end":return this.handleToolInputEnd(t);case"tool_call":return this.handleToolCall(t.toolCall);case"finish":return[...this.flush(),t];default:return[t]}}flush(){return this.completedStreamingInputIds.clear(),this.providerExecutedById.clear(),this.streamingInputIds.clear(),[]}handleToolInputStart(t){if(this.normalizedToolCalls.has(t.id))return[];let n=j0e(t.toolName,{providerExecuted:t.providerExecuted,source:"streamText",streamEventType:t.type,toolCallId:t.id});return t.providerExecuted!==void 0&&this.providerExecutedById.set(t.id,t.providerExecuted),this.streamingInputIds.add(t.id),[{...t,toolName:n}]}handleToolInputEnd(t){return this.normalizedToolCalls.has(t.id)?[]:(this.completedStreamingInputIds.add(t.id),[t])}handleToolCall(t){if(this.normalizedToolCalls.has(t.id))return[];if(this.streamingInputIds.has(t.id)&&!this.completedStreamingInputIds.has(t.id))return[];let n=t.providerExecuted??this.providerExecutedById.get(t.id),o=j0e(t.name,{providerExecuted:n,source:"streamText",streamEventType:"tool_call",toolCallId:t.id}),s={...t,input:$st(t.input,{logger:this.logger,source:"streamText",toolName:o}),name:o,providerExecuted:n};return this.completedStreamingInputIds.delete(t.id),this.providerExecutedById.delete(t.id),this.streamingInputIds.delete(t.id),this.normalizedToolCalls.set(s.id,s),[{type:"tool_call",toolCall:s}]}}});function $zStreamEofFinishGuard(e){return(e.finishReason===void 0||e.finishReason==="other")&&e.rawFinishReason==null&&(e.textDeltaChars>0||e.toolCallCount>0||e.reasoningDeltaChars>0||(e.chunkCounts?.["tool-input-start"]??0)>0||(e.chunkCounts?.["tool-input-delta"]??0)>0||(e.chunkCounts?.["tool-input-end"]??0)>0)}async function*wVr(e){let t=e.request.modelRetryBudget,n=r(_=>QDe(t,e.retry.maxAttempts+_),"statusMaxAttempts"),o=Ist({maxAttempts:n(0),request:e.request,resolved:e.resolved,transport:WV.Sse}),s=Kst(e.env),a=Zst(e.env),l=e.request.messages,u=!1,f=new $0e(e.request,e.resolved),g=0;for(let _=1;kst(t,_,e.retry.maxAttempts+Number(u)+f.extraAttempts);_+=1){let b=_-Number(u)-f.extraAttempts,w=Date.now(),T=gzr({baseTimeoutMs:e.streamIdleTimeoutMs,retryNumber:(e.request.streamIdleTimeoutRetryNumber??0)+b-1}),I=!1,E=!1,R=!1,L=!1,U=!1,B=[],z=OWr(),$=_zr(e.request.abortSignal),J={...e.request,abortSignal:$.signal,messages:l},q=Cst({...o,maxAttempts:n(Number(u)+f.extraAttempts)},_),ie=new lat({logger:e.logger}),ae,Ce=!1,pe=!1,ze=!1,rt=!1,Pe,Tt,Ye={},Fe=0,St=e.resolved,kt,st,$e,jt=0,Je=0,Xe=!1,_t=r(cn=>{if(u||St.providerKind!=="anthropic")return!1;let Fn=iat(l,cn);return Fn?(u=!0,l=Fn,e.logger?.warn("Retrying model stream after thinking signature rejection",{attempt:_,event:"model.reasoning_signature_repair.retry",maxAttempts:e.retry.maxAttempts+1+f.extraAttempts,nextAttempt:_+1,requestId:q.requestId,status:"waiting"}),!0):!1},"repairThinkingSignatureRejection"),Dt=r(async cn=>{st===void 0&&cn.contentMs!==void 0&&(st=cn.contentMs,await Ast({...q,attempt:_,elapsedMs:cn.contentMs,timestamp:new Date(w+cn.contentMs).toISOString(),type:"model_first_content"},{logger:e.logger,statusSink:e.statusSink})),$e===void 0&&cn.textMs!==void 0&&($e=cn.textMs,await Ast({...q,attempt:_,elapsedMs:cn.textMs,timestamp:new Date(w+cn.textMs).toISOString(),type:"model_first_text"},{logger:e.logger,statusSink:e.statusSink}))},"publishVisibleMilestones"),gn;try{gn=await cat({admission:e.request.modelRequestAdmission,model:{providerId:String(St.providerId),modelId:String(St.modelId)},signal:e.request.abortSignal,...Est(q,_,nB(e))})}catch(cn){$.cleanup();let Fn=DM(cn,e.request.abortSignal);throw await zv({...q,attempt:_,durationMs:Date.now()-w,message:Fn.message,reason:Fn.reason,requestHeaderCount:Fe,requestHeaders:Ye,retryable:!1,statusCode:Fn.statusCode,streamOutputCommitted:Xe,...j7(cn,Fn,"connect"),timestamp:new Date().toISOString(),type:"model_request_failed"},{...nB(e),failureError:D_(cn)}),NM(cn,Fn,q,_,{errorPhase:"connect"})}try{St=await tat({attempt:_,reason:f.takeReason(),request:J,resolveModel:e.resolveModel});let cn=await Pst({env:e.env,providerKind:St.providerKind,sessionId:q.sessionId});Pe=_Wr({anthropicMetadataUserId:cn,env:e.env,includeModelIO:s,request:J,resolved:St,statusContext:q}),Ye=MM(Pe.headers),Fe=Object.keys(Ye).length,await zv({...q,attempt:_,requestHeaderCount:Fe,requestHeaders:Ye,timestamp:new Date(w).toISOString(),type:"model_request_started"},nB(e,gn));let Fn=e.runtime.streamText(Pe);for(Tt=Fn,ae=Fn.fullStream[Symbol.asyncIterator]();;){let dt=await yzr(ae,{abortController:$.controller,onTimeout:r(async Pt=>{Je+=1,jt=Math.max(jt,Pt.idleMs),await zv({...q,attempt:_,idleMs:Pt.idleMs,message:Pt.message,requestHeaderCount:Fe,requestHeaders:Ye,timeoutMs:Pt.timeoutMs,timestamp:new Date().toISOString(),type:"model_stream_stalled"},nB(e,gn))},"onTimeout"),timeoutMs:T});if(dt.done){Ce=!0;break}kt===void 0&&(kt=Date.now()-w,await Ast({...q,attempt:_,elapsedMs:kt,timestamp:new Date(w+kt).toISOString(),type:"model_first_provider_event"},{logger:e.logger,statusSink:e.statusSink}));let we;try{we=await K4s({admission:gn,attempt:_,chunk:dt.value,diagnostics:z,emittedRetryBoundaryEvent:E,input:e,pendingRetrySafeEvents:B,requestHeaderCount:Fe,requestHeaders:Ye,repairThinkingSignatureRejection:_t,retryBudgetAttempt:b,startedAt:w,statusContext:q,toolCallAssembler:ie})}catch(Pt){let ut=X4s(e.request,dt.value);if(ut){E=!0;for(let Mn of B.splice(0))I=!0,yield Mn;I=!0,yield ut}throw Pt}if(!we.emittedError&&we.visibleEvents.some(Pt=>Pt.type==="finish")&&e.request.preserveProviderStreamBoundaries!==!0&&aOe({finishReason:z.finishReason,reasoningLength:z.reasoningDeltaChars,textLength:z.textDeltaChars,toolCallCount:z.toolCallCount,usage:z.usage})&&lOe({abortSignal:e.request.abortSignal,attempt:_,maxAttempts:e.retry.maxAttempts,retryCount:g})&&(we.visibleEvents.length=0),R=R||we.emittedError,I=I||we.emittedEvent,E=E||we.emittedRetryBoundaryEvent,we.retryScheduled){pe=!0,ze=!0,L=!0,U=we.offPeakQueueHold;break}if(we.terminalError)throw we.terminalError;if(we.visibleEvents.length>0)for(let Pt of we.visibleEvents){let ut=Uln(Pt,Date.now()-w);await Dt(ut),Xe=Xe||ut.outputCommitted,yield Pt}}if(L){U&&(_-=1);continue}let on=zln({emittedRetryBoundaryEvent:E,events:ie.flush(),pendingRetrySafeEvents:B,preserveProviderStreamBoundaries:e.request.preserveProviderStreamBoundaries});if(I=I||on.emittedEvent,E=E||on.emittedRetryBoundaryEvent,on.visibleEvents.length>0)for(let dt of on.visibleEvents){let we=Uln(dt,Date.now()-w);await Dt(we),Xe=Xe||we.outputCommitted,yield dt}for(let dt of B.splice(0)){I=!0;let we=Uln(dt,Date.now()-w);await Dt(we),Xe=Xe||we.outputCommitted,yield dt}if(!R){let dt=lG({providerId:String(q.providerId),providerKind:q.providerKind,source:z.lastFinishChunk??{type:"finish",finishReason:z.finishReason,rawFinishReason:z.rawFinishReason}});if(dt){if(uOe(dt))throw dt;let we=DM(dt,e.request.abortSignal);throw new ore(NM(dt,we,q,_,{...$ln(e.request.preserveProviderStreamBoundaries,"response_body"),errorPhase:"stream"}))}if(jWr(z)){let we=lG({providerId:String(q.providerId),providerKind:q.providerKind,source:z.lastErrorChunk??z.lastFinishChunk})??hVr({captcha:St.accountAccess?.mode==="start-plan",headers:St.headers,providerId:String(q.providerId),providerKind:St.providerKind});if(we){if(uOe(we))throw we;let _e=DM(we,e.request.abortSignal);throw new ore(NM(we,_e,q,_,{...$ln(e.request.preserveProviderStreamBoundaries,"response_body"),errorPhase:"stream"}))}if(e.request.preserveProviderStreamBoundaries!==!0&&aOe({finishReason:z.finishReason,reasoningLength:z.reasoningDeltaChars,textLength:z.textDeltaChars,toolCallCount:z.toolCallCount,usage:z.usage})&&lOe({abortSignal:e.request.abortSignal,attempt:_,maxAttempts:e.retry.maxAttempts,retryCount:g})){let _e=await SVr(Fn),Pt=Date.now();Tln({attempt:_,diagnostics:z,durationMs:Pt-w,emittedError:R,emittedEvent:I,logger:e.logger,outboundHeaders:St.headers,statusContext:q}),g+=1,await eat({abortSignal:e.request.abortSignal,attempt:_,completedAt:Pt,errorPhase:"stream",logger:e.logger,requestHeaders:Ye,requestStatusSink:e.request.statusSink,responseHeaders:_e,retry:e.retry,retryBudgetAttempt:b,startedAt:w,statusContext:q,statusSink:e.statusSink,streamOutputCommitted:!1});continue}}}if($zStreamEofFinishGuard(z)&&!R)throw Object.assign(new Error("Model stream ended before a finish reason (EOF)."),{name:"ModelStreamIdleTimeoutError",code:"MODEL_STREAM_IDLE_TIMEOUT",idleMs:0,timeoutMs:0});if(Tln({attempt:_,diagnostics:z,durationMs:Date.now()-w,emittedError:R,emittedEvent:I,logger:e.logger,outboundHeaders:St.headers,statusContext:q}),!R){let dt=Date.now(),we=await SVr(Fn);await zv({...q,attempt:_,durationMs:dt-w,requestHeaderCount:Fe,requestHeaders:Ye,responseHeaderCount:Object.keys(we).length,responseHeaders:we,providerRequestId:Yst(we),finishReason:z.finishReason,usage:z.usage,timeToFirstProviderEventMs:kt,timeToFirstContentMs:st,timeToFirstTextMs:$e,streamMaxIdleMs:jt||void 0,streamStallCount:Je,streamOutputCommitted:Xe,timestamp:new Date(dt).toISOString(),type:"model_request_completed"},nB(e,gn)),rt=!0}s&&Pe&&await Pln({modelIoFullRetentionEnabled:e.modelIoFullRetentionEnabled,attempt:_,debugDir:e.debugDir,isDev:a,normalizedToolCalls:ie.snapshotNormalizedToolCalls(),options:Pe,recordModelIO:s,request:J,requestId:q.requestId,resolved:St,result:Fn,startedAt:w});return}catch(cn){if(pe=!0,s&&Pe&&await Pln({modelIoFullRetentionEnabled:e.modelIoFullRetentionEnabled,attempt:_,debugDir:e.debugDir,error:cn,isDev:a,normalizedToolCalls:ie.snapshotNormalizedToolCalls(),options:Pe,recordModelIO:s,request:J,requestId:q.requestId,resolved:St,result:Tt,startedAt:w}),cn instanceof ore)throw ze=!0,cn.adapterError;if(cn instanceof Tb&&cn.code===Cs.ModelRequestAuthMissing)throw cn;let Fn=Date.now(),on=!E&&_t(cn);on&&(q={...q,maxAttempts:n(1+f.extraAttempts)});let dt=DM(cn,e.request.abortSignal);cn instanceof are&&(dt.message=cn.message,dt.retryable=!1);let we=KDe({offPeak:St.accountAccess?.mode==="off-peak",failure:dt,error:D_(cn)}),_e=we?.kind==="ticketExpired"?{...dt,retryable:!1,message:ZDe(dt.message)}:we?.kind==="queued"?{...dt,retryable:!0,retryReason:Qc.OffpeakQueued}:dt,Pt=XWr(cn)??(ae===void 0?"prepare":"stream");ze=_e.reason!==_s.Cancelled;let ut=MM(RM(D_(cn))),Mn=kVr({attempt:b,emittedRetryBoundaryEvent:E,error:cn,failure:_e,maxAttempts:e.retry.maxAttempts,preserveProviderStreamBoundaries:e.request.preserveProviderStreamBoundaries,responseHeaders:ut,retryBudget:t,streamIteratorCreated:ae!==void 0,streamErrorChunkObserved:!!(z.lastErrorChunk||z.lastFinishChunk)}),Dr=f.claim(cn,Pe===void 0||E||Xe||e.request.preserveProviderStreamBoundaries===!0&&Mn.context?.streamFailurePhase==="response_body");if(Dr&&(Mn.canRetry=!0,q={...q,maxAttempts:n(Number(u)+f.extraAttempts)}),we?.kind==="queued"&&!E&&(Mn.canRetry=!0),on&&(Mn.canRetry=!0),NWr({attempt:_,canRetry:Mn.canRetry,diagnostics:z,durationMs:Fn-w,emittedError:R,emittedEvent:I,emittedRetryBoundaryEvent:E,error:cn,failure:_e,logger:e.logger,statusContext:q}),await zv({...q,attempt:_,durationMs:Fn-w,message:_e.message,reason:_e.reason,requestHeaderCount:Fe,requestHeaders:Ye,responseHeaderCount:Object.keys(ut).length,responseHeaders:ut,retryable:Mn.canRetry,statusCode:_e.statusCode,streamOutputCommitted:Xe,...j7(cn,_e,Pt),timestamp:new Date(Fn).toISOString(),type:"model_request_failed"},{...nB(e,gn),failureError:D_(cn)}),rt=!0,Dr){await pOe(e,q,_,0,{..._e,retryReason:Qc.AuthRefresh},Ye,ut);continue}if(on){await pOe(e,q,_,0,{..._e,retryReason:Qc.ReasoningSignatureRepair},Ye,ut,gn);continue}if(!Mn.canRetry)throw tB({attempt:_,canRetry:Mn.canRetry,failure:_e,logger:e.logger,responseHeaders:ut,statusContext:q}),NM(cn,_e,q,_,{...Mn.context,errorPhase:Pt});let gr=we?.kind==="queued"?we.delayMs:ire(e.retry,b,_e.retryAfterMs);tB({attempt:_,canRetry:Mn.canRetry,delayMs:gr,failure:_e,logger:e.logger,responseHeaders:ut,statusContext:q}),await pOe(e,q,_,gr,_e,Ye,ut,gn),gn.release();try{await sre(gr,e.request.abortSignal)}catch(eo){let to=DM(eo,e.request.abortSignal);throw await zv({...q,attempt:_,durationMs:Date.now()-w,message:to.message,reason:to.reason,requestHeaderCount:Fe,requestHeaders:Ye,retryable:!1,statusCode:to.statusCode,streamOutputCommitted:Xe,...j7(eo,to,"connect"),timestamp:new Date().toISOString(),type:"model_request_failed"},{...nB(e),failureError:D_(eo)}),rt=!0,NM(eo,to,q,_,{errorPhase:"connect"})}we?.kind==="queued"&&(_-=1)}finally{if(!Ce&&(pe||e.request.preserveProviderStreamBoundaries===!0)){if($.signal.aborted||$.controller.abort(new Error("Model stream attempt ended before natural EOF.")),!pe&&!rt&&!R){let cn=Date.now();await zv({...q,attempt:_,durationMs:cn-w,message:"Model stream consumer closed before natural EOF.",reason:_s.Cancelled,requestHeaderCount:Fe,requestHeaders:Ye,retryable:!1,errorCode:"model_request_cancelled",errorPhase:"stream",exceptionType:"AbortError",streamOutputCommitted:Xe,timestamp:new Date(cn).toISOString(),type:"model_request_failed"},nB(e,gn))}pe&&ze?await Bln(ae,{attempt:_,logger:e.logger,result:Tt}):Bln(ae,{attempt:_,logger:e.logger})}else $.signal.aborted&&Bln(ae,{attempt:_,logger:e.logger});$.cleanup(),gn.release()}}}async function Bln(e,t){let n=[];if(e?.return&&n.push({name:"iterator.return",promise:Promise.resolve().then(()=>e.return?.())}),t.result?.consumeStream&&n.push({name:"result.consumeStream",promise:Promise.resolve().then(()=>t.result?.consumeStream())}),n.length===0)return;let o,s=await Promise.race([Promise.allSettled(n.map(l=>l.promise)).then(l=>({results:l,type:"settled"})),new Promise(l=>{o=setTimeout(()=>l({type:"timed_out"}),yVr)})]);if(o!==void 0&&clearTimeout(o),s.type==="timed_out"){t.logger?.warn("Model stream attempt cleanup timed out",{attempt:t.attempt,cleanupOperations:n.map(l=>l.name),event:"model.stream_attempt_cleanup.timeout",status:"waiting",timeoutMs:yVr});return}let a=s.results.flatMap((l,u)=>l.status==="rejected"?[{errorMessage:l.reason instanceof Error?l.reason.message:String(l.reason),operation:n[u]?.name}]:[]);a.length>0&&t.logger?.warn("Model stream attempt cleanup failed",{attempt:t.attempt,event:"model.stream_attempt_cleanup.failed",failures:a,status:"failed"})}async function K4s(e){MWr(e.diagnostics,e.chunk);let t=e.input.request.preserveProviderStreamBoundaries===!0&&Z4s(e.chunk),n=e.input.request.preserveProviderStreamBoundaries?Y4s(e.chunk):void 0,o=e.emittedRetryBoundaryEvent||t,s=lG({providerId:String(e.statusContext.providerId),providerKind:e.statusContext.providerKind,source:e.chunk});if(s)return vVr({...e,emittedRetryBoundaryEvent:o},s);let a=Sln(e.chunk);return a?.type==="error"?vVr({...e,emittedRetryBoundaryEvent:o},a.error):a?zln({emittedRetryBoundaryEvent:e.emittedRetryBoundaryEvent,events:e.toolCallAssembler.handle(a),pendingRetrySafeEvents:e.pendingRetrySafeEvents,providerEventObserved:t,preserveProviderStreamBoundaries:e.input.request.preserveProviderStreamBoundaries}):t?zln({emittedRetryBoundaryEvent:e.emittedRetryBoundaryEvent,events:n?[n]:[],pendingRetrySafeEvents:e.pendingRetrySafeEvents,providerEventObserved:!0,preserveProviderStreamBoundaries:!0}):(LWr({attempt:e.attempt,chunk:e.chunk,logger:e.input.logger,statusContext:e.statusContext}),dOe())}function zln(e){let t=!1,n=e.emittedRetryBoundaryEvent,o=[];e.providerEventObserved&&!n&&(o.push(...e.pendingRetrySafeEvents.splice(0)),n=!0);for(let s of e.events){if(t=!0,dVr(s)&&(!e.preserveProviderStreamBoundaries||s.type==="start")&&!n){e.pendingRetrySafeEvents.push(s);continue}n||o.push(...e.pendingRetrySafeEvents.splice(0)),o.push(s),n=!0}return dOe({emittedEvent:t,emittedRetryBoundaryEvent:n,visibleEvents:o})}function Z4s(e){if(e.type!=="raw")return!1;let t=e.rawValue;return!(t!==null&&typeof t=="object"&&t.type==="ping")}function Y4s(e){if(e.type!=="raw"||e.rawValue===null||typeof e.rawValue!="object")return;let t=e.rawValue;if(t.type==="message_start")return{boundary:"provider_response_start",type:"compact_stream_boundary"};if(t.type==="content_block_start")return{blockType:typeof t.content_block?.type=="string"?t.content_block.type:null,boundary:"provider_content_block_start",index:typeof t.index=="number"?t.index:null,type:"compact_stream_boundary"};if(t.type==="content_block_delta")return{boundary:"provider_content_block_delta",deltaType:typeof t.delta?.type=="string"?t.delta.type:null,index:typeof t.index=="number"?t.index:null,type:"compact_stream_boundary"};if(t.type==="content_block_stop")return{boundary:"provider_content_block_stop",index:typeof t.index=="number"?t.index:null,type:"compact_stream_boundary"};if(t.type==="message_delta")return{boundary:"provider_stop_reason",present:!!t.delta?.stop_reason,type:"compact_stream_boundary"}}function X4s(e,t){if(!(!e.preserveProviderStreamBoundaries||t.type!=="tool-call"))return{boundary:"inferred_content_block_stop",type:"compact_stream_boundary"}}async function vVr(e,t){if(uOe(t))throw t;let n=!e.emittedRetryBoundaryEvent&&e.repairThinkingSignatureRejection(t),o=n?{...e.statusContext,maxAttempts:QDe(e.input.request.modelRetryBudget,e.input.retry.maxAttempts+1)}:e.statusContext,s=DM(t,e.input.request.abortSignal),a=KDe({offPeak:e.input.resolved.accountAccess?.mode==="off-peak",failure:s,error:D_(t)}),l=a?.kind==="ticketExpired"?{...s,retryable:!1,message:ZDe(s.message)}:a?.kind==="queued"?{...s,retryable:!0,retryReason:Qc.OffpeakQueued}:s,u=MM(RM(D_(t))),f=kVr({attempt:e.retryBudgetAttempt,emittedRetryBoundaryEvent:e.emittedRetryBoundaryEvent,error:t,failure:l,maxAttempts:e.input.retry.maxAttempts,preserveProviderStreamBoundaries:e.input.request.preserveProviderStreamBoundaries,responseHeaders:u,retryBudget:e.input.request.modelRetryBudget,streamErrorChunkObserved:!0});if(a?.kind==="queued"&&!e.emittedRetryBoundaryEvent&&(f.canRetry=!0),n&&(f.canRetry=!0),await zv({...o,attempt:e.attempt,durationMs:Date.now()-e.startedAt,message:l.message,reason:l.reason,requestHeaderCount:e.requestHeaderCount,requestHeaders:e.requestHeaders,responseHeaderCount:Object.keys(u).length,responseHeaders:u,retryable:f.canRetry,statusCode:l.statusCode,streamOutputCommitted:e.emittedRetryBoundaryEvent,...j7(t,l,"stream"),timestamp:new Date().toISOString(),type:"model_request_failed"},{...nB(e.input,e.admission),failureError:D_(t)}),n)return await pOe(e.input,o,e.attempt,0,{...l,retryReason:Qc.ReasoningSignatureRepair},e.requestHeaders,u,e.admission),dOe({emittedError:!0,retryScheduled:!0});if(!f.canRetry)return tB({attempt:e.attempt,canRetry:f.canRetry,failure:l,logger:e.input.logger,responseHeaders:u,statusContext:o}),dOe({emittedError:!0,terminalError:new ore(NM(t,l,o,e.attempt,{...f.context,errorPhase:"stream"}))});let g=a?.kind==="queued"?a.delayMs:ire(e.input.retry,e.retryBudgetAttempt,l.retryAfterMs);tB({attempt:e.attempt,canRetry:f.canRetry,delayMs:g,failure:l,logger:e.input.logger,responseHeaders:u,statusContext:o}),await pOe(e.input,o,e.attempt,g,l,e.requestHeaders,u,e.admission),e.admission.release();try{await sre(g,e.input.request.abortSignal)}catch(_){let b=DM(_,e.input.request.abortSignal);throw NM(_,b,o,e.attempt,{errorPhase:"connect"})}return dOe({emittedError:!0,retryScheduled:!0,offPeakQueueHold:a?.kind==="queued"})}function Q4s(e){if(e.streamIteratorCreated===!1)return"request_setup";if(e.emittedRetryBoundaryEvent)return"response_body";let t=e.httpResponseStatus;if(t!==void 0){if(t>=200&&t<300)return"response_body";if(t>=300&&t<600)return"request_setup"}if(e.streamErrorChunkObserved||r6s(e.responseHeaders,"content-type")?.toLowerCase()?.includes("text/event-stream"))return"response_body"}function $ln(e,t,n){if(!(e!==!0||!t))return{...n!==void 0?{httpResponseStatus:n}:{},streamFailurePhase:t}}function kVr(e){let t=e.preserveProviderStreamBoundaries?t6s(e.error):void 0,n=e.preserveProviderStreamBoundaries?Q4s({emittedRetryBoundaryEvent:e.emittedRetryBoundaryEvent,httpResponseStatus:t,responseHeaders:e.responseHeaders,streamErrorChunkObserved:e.streamErrorChunkObserved,streamIteratorCreated:e.streamIteratorCreated}):void 0;return{canRetry:e6s({attempt:e.attempt,emittedRetryBoundaryEvent:e.emittedRetryBoundaryEvent,error:e.error,failure:e.failure,httpResponseStatus:t,maxAttempts:e.maxAttempts,preserveProviderStreamBoundaries:e.preserveProviderStreamBoundaries,retryBudget:e.retryBudget,streamFailurePhase:n}),context:$ln(e.preserveProviderStreamBoundaries,n,t)}}function e6s(e){let t=iG(e.error).providerErrorCode;return e.emittedRetryBoundaryEvent||!wst(e.retryBudget,e.attempt,e.maxAttempts)||e.failure.reason===_s.Cancelled?!1:e.preserveProviderStreamBoundaries===!0&&n6s(e.error,e.httpResponseStatus)?!0:rat(e.failure,e.retryBudget,t)?e.preserveProviderStreamBoundaries!==!0||e.streamFailurePhase!=="response_body":!1}function t6s(e){let t=D_(e);return X3(t)?.responseStatus??dst(t)}function n6s(e,t){let n=D_(e);if(zit(n)||bVr(fst(n))||$zTransportChain(n,new WeakSet))return!0;if(t!==void 0)return!1;let o=X3(n)?.providerCode;return bVr(typeof o=="number"?String(o):o)}function bVr(e){let t=e?.trim().toUpperCase();return t==="ECONNRESET"||t==="EPIPE"||t==="CONNECTIONCLOSED"}function r6s(e,t){let n=t.toLowerCase();return Object.entries(e).find(([o])=>o.toLowerCase()===n)?.[1]}function dOe(e={}){return{emittedError:!1,emittedEvent:!1,emittedRetryBoundaryEvent:!1,retryScheduled:!1,offPeakQueueHold:!1,visibleEvents:[],...e}}function nB(e,t){return{clientSigningObservations:e.resolved?.clientSigningObservations,logger:e.logger,requestStatusSink:e.request.statusSink,statusSink:e.statusSink,...t?.ticket===void 0?{}:{admissionTicket:t.ticket}}}async function pOe(e,t,n,o,s,a,l,u){await zv({...t,attempt:n,delayMs:o,message:s.message,nextAttempt:n+1,reason:s.retryReason,requestHeaderCount:Object.keys(a).length,requestHeaders:a,responseHeaderCount:Object.keys(l).length,responseHeaders:l,statusCode:s.statusCode,errorCode:s.code,retryAfterMs:s.retryAfterMs,timestamp:new Date().toISOString(),type:"model_retry_scheduled"},nB(e,u))}function Uln(e,t){switch(e.type){case"text_delta":return{contentMs:t,textMs:e.text?t:void 0,outputCommitted:!0};case"reasoning_delta":case"tool_input_delta":case"tool_call":return{contentMs:t,outputCommitted:!0};case"text_start":case"reasoning_start":case"tool_input_start":return{contentMs:t,outputCommitted:!1};case"compact_stream_boundary":return{contentMs:e.boundary==="provider_content_block_start"?t:void 0,outputCommitted:e.boundary==="provider_content_block_stop"||e.boundary==="inferred_content_block_stop"};default:return{outputCommitted:!1}}}async function SVr(e){try{let t=await e.response;return MM(t?.headers)}catch{return{}}}var yVr,xVr=Y(()=>{"use strict";nr();nre();Dst();O7();Qcn();pVr();$it();Gst();Oln();yln();Rln();Vst();Lln();eOe();B0e();zst();gVr();Qst();aG();_Vr();Mln();Nln();oat();Xst();aat();yVr=1e3;r(wVr,"runStreamText");r(Bln,"closeStreamIteratorBestEffort");r(K4s,"handleStreamChunk");r(zln,"applyStreamEventsToRetryBoundary");r(Z4s,"isRawProviderRetryBoundaryEvent");r(Y4s,"toProviderStreamBoundaryEvent");r(X4s,"compactDirectToolCallCommitEvent");r(vVr,"handleStreamErrorEvent");r(Q4s,"classifyStreamFailurePhase");r($ln,"compactStreamFailureContext");r(kVr,"resolveStreamFailureDecision");r(e6s,"canRetryStreamFailure");r(t6s,"resolveCompactHttpResponseStatus");r(n6s,"isCompactStaleStreamFailure");r(bVr,"isCompactStaleCode");r(r6s,"readHeader");r(dOe,"streamChunkResult");r(nB,"statusPublishOptions");r(pOe,"publishRetryScheduledStatus");r(Uln,"observeVisibleStreamEvent");r(SVr,"resolveStreamResponseHeaders")});var TVr,IVr=Y(()=>{"use strict";P0e();TVr={generateText:J9r,streamText:X9r}});function CVr(e){return new qln(e)}function o6s(e){return Object.freeze({maxOutputTokens:Object.freeze({...e.maxOutputTokens}),reasoningLevel:Object.freeze({...e.reasoningLevel,values:Object.freeze([...e.reasoningLevel.values])})})}function i6s(e,t){let n=t.maxOutputTokens;if(n===void 0||!Number.isInteger(n)||n<=0||n>e.maxOutputTokens.max)throw B7("maxOutputTokens is outside the model option range",{maxOutputTokens:n,spec:e.maxOutputTokens});let o=t.reasoningLevel,s=e.reasoningLevel;if(o===void 0||!s.values.includes(o))throw B7("reasoningLevel is not supported by the model",{reasoningLevel:o,values:s.values});return{maxOutputTokens:n,reasoningLevel:o}}function s6s(e,t){let n=t.maxOutputTokens;if(n!==void 0&&(!Number.isInteger(n)||n<=0||n>e.maxOutputTokens.max))throw B7("maxOutputTokens is outside the model option range",{maxOutputTokens:n,spec:e.maxOutputTokens});let o=t.reasoningLevel;if(o!==void 0&&!e.reasoningLevel.values.includes(o))throw B7("reasoningLevel is not supported by the model",{reasoningLevel:o,values:e.reasoningLevel.values});return{...t}}function a6s(e,t){if(t.tools&&t.tools.length>0&&!e.supportsToolCall)throw B7("Model does not support tool calls");if(t.responseJsonSchema&&!e.supportsJsonSchemaOutput)throw B7("Model does not support structured output");for(let n of t.messages)if(Array.isArray(n.content))for(let o of n.content){if(o.type==="image"&&!e.inputFormat.supportsImage)throw B7("Model does not support image input");if(o.type==="file"&&o.mediaType.toLowerCase()==="application/pdf"&&!e.inputFormat.supportsPdf)throw B7("Model does not support PDF input");if(o.type==="file"&&o.mediaType.toLowerCase().startsWith("video/")&&!e.inputFormat.supportsVideo)throw B7("Model does not support video input")}}function B7(e,t){return new Tb(Cs.InvalidModelRequest,e,{...t,reason:_s.InvalidRequest,retryable:!1,source:"runtime"})}var qln,Wln=Y(()=>{"use strict";nr();r(CVr,"createModel");qln=class e{static{r(this,"ExecutableModel")}providerId;modelId;displayName;properties;optionSpecs;options;executor;constructor(t){this.providerId=t.providerId,this.modelId=t.modelId,this.displayName=t.displayName,this.properties=Object.freeze({...t.properties}),this.optionSpecs=o6s(t.optionSpecs),this.options=Object.freeze(s6s(this.optionSpecs,t.options??{})),this.executor=t.executor}bind(t){return!t||Object.keys(t).length===0?this:new e({providerId:this.providerId,modelId:this.modelId,displayName:this.displayName,properties:this.properties,optionSpecs:this.optionSpecs,options:{...this.options,...t},executor:this.executor})}async generateText(t){return this.executor.generateText(this.prepareRequest(t))}streamText(t){let n=this.prepareRequest(t);return this.executor.streamText(n)}prepareRequest(t){a6s(this.properties,t);let n=t.options??{};return{messages:t.messages,tools:t.tools,responseJsonSchema:t.responseJsonSchema,abortSignal:t.abortSignal,options:{...i6s(this.optionSpecs,{...this.options,...n})}}}};r(o6s,"freezeOptionSpecs");r(i6s,"validateOptions");r(s6s,"validatePartialOptions");r(a6s,"validateRequestProperties");r(B7,"invalidRequest")});function c6s(e){if(e.maxOutputTokens===void 0)throw new Tb(Cs.InvalidModelRequest,"maxOutputTokens requires an explicit request value");return e.maxOutputTokens}function l6s(e){return e?.apiKey?.trim()?!0:Object.values(e?.headers??{}).some(t=>t.trim().length>0)}function u6s(e,t){if(e.providerId!==t.providerId||e.modelId!==t.modelId)throw new Error("Runtime header refresh changed the bound model identity.");return t}function EVr(e,t){if(t.providerKind!=="anthropic")return e;let n=sVr(e.messages,{providerId:t.providerId,modelId:t.modelId});return n===e.messages?e:{...e,messages:n}}var uat,AVr=Y(()=>{"use strict";nr();P7();Gan();$it();uVr();xVr();aat();IVr();Wln();B0e();uat=class{static{r(this,"AiSdkModelAdapter")}execution;runtime;env;debugDir;logger;retry;statusSink;streamIdleTimeoutMs;modelIoFullRetentionEnabled;constructor(t){this.execution=new Bit({defaultHeaders:t.defaultHeaders,...t.codingPlanSignature?{codingPlanSignature:t.codingPlanSignature}:{},...t.endpointRoutingPort?{endpointRoutingPort:t.endpointRoutingPort}:{},...t.network?{network:t.network}:{},...t.env?{env:t.env}:{}},{...t.clientRequestSigningState?{clientRequestSigningState:t.clientRequestSigningState}:{},...t.logger?{logger:t.logger}:{}}),this.runtime=t.runtime??TVr,this.env=t.env??process.env,this.debugDir=t.debugDir,this.logger=t.logger,this.retry=hzr(t.retry,this.env),this.statusSink=t.statusSink,this.streamIdleTimeoutMs=t.streamIdleTimeoutMs??YV,this.modelIoFullRetentionEnabled=t.modelIoFullRetentionEnabled??!1}setModelIoFullRetentionEnabled(t){this.modelIoFullRetentionEnabled=t}addStatusSink(t){let n=this.statusSink;if(!n||n===t){this.statusSink=t;return}this.statusSink={async publish(o){let a=(await Promise.allSettled([Promise.resolve().then(()=>n.publish(o)),Promise.resolve().then(()=>t.publish(o))])).find(l=>l.status==="rejected");if(a)throw a.reason}}}createModel(t){let n=this.execution.bindModel({providerId:t.providerId,modelId:t.modelId,providerConfig:t.providerConfig,supportsJsonSchemaOutput:t.modelConfig.properties.supportsJsonSchemaOutput,optionSpecs:t.modelConfig.optionSpecs}),o=t.modelConfig.properties,s={...n.resolved,properties:o,...t.providerConfig.access.type==="zhipu-account"?{accountAccess:t.providerConfig.access}:{}},a=t.modelConfig.optionSpecs,l=r(f=>{let g=r3(),{refreshRuntimeHeadersBeforeAttempt:_,...b}=g??{},w=f.options.reasoningLevel!==void 0,T=f.options.reasoningLevel,I=t.requestDependencies?.requestAuth,R=t.providerConfig.access.type==="zhipu-account"&&t.providerConfig.access.mode==="off-peak"?async L=>{let U=await I?.source?.resolve(L);if(!l6s(U))throw new Tb(Cs.ModelRequestAuthMissing,`Model request auth is unavailable: ${s.providerId}/${s.modelId}`);return{headersApplied:!0,requestAuth:U}}:t.providerConfig.access.type==="zhipu-account"?_??(async()=>{throw new Tb(Cs.ModelRequestAuthMissing,`Account model request auth is unavailable: ${s.providerId}/${s.modelId}`)}):void 0;return{messages:f.messages,tools:f.tools,responseJsonSchema:f.responseJsonSchema,abortSignal:f.abortSignal,maxOutputTokens:f.options.maxOutputTokens,...b,...w?{modelCall:{...b.modelCall,reasoning:{...b.modelCall?.reasoning,...T?{requestedLevel:T}:{}}}}:{},...R?{refreshRuntimeHeadersBeforeAttempt:r(L=>R({...L,...t.providerConfig.access.type==="zhipu-account"?{accountAccess:t.providerConfig.access}:{}}),"refreshRuntimeHeadersBeforeAttempt")}:{}}},"toLegacyRequest"),u=r((f,g)=>{let _=c6s(g);return f.refreshRuntimeHeadersBeforeAttempt?b=>({...u6s(s,n.resolveRequest({options:{maxOutputTokens:_,reasoningLevel:g.reasoningLevel},requestAuth:b})),properties:o,...t.providerConfig.access.type==="zhipu-account"?{accountAccess:t.providerConfig.access}:{}}):()=>({...n.resolveRequest({options:{maxOutputTokens:_,reasoningLevel:g.reasoningLevel}}),properties:o,...t.providerConfig.access.type==="zhipu-account"?{accountAccess:t.providerConfig.access}:{}})},"resolveForRequest");return CVr({providerId:s.providerId,modelId:s.modelId,displayName:t.displayName,properties:o,optionSpecs:{maxOutputTokens:a.maxOutputTokens,reasoningLevel:a.reasoningLevel},options:t.options,executor:{generateText:r(f=>{let g=l(f);return this.generateTextWithResolved(g,s,u(g,f.options))},"generateText"),streamText:r(f=>{let g=l(f);return this.streamTextWithResolved(g,s,u(g,f.options))},"streamText")}})}generateTextWithResolved(t,n,o){let s=EVr(t,n);return lVr({debugDir:this.debugDir,env:this.env,logger:this.logger,request:s,resolveModel:o,resolved:n,retry:this.retry,runtime:this.runtime,statusSink:this.statusSink,modelIoFullRetentionEnabled:this.modelIoFullRetentionEnabled})}async*streamTextWithResolved(t,n,o){let s=EVr(t,n);yield*wVr({debugDir:this.debugDir,env:this.env,logger:this.logger,request:s,resolveModel:o,resolved:n,retry:this.retry,runtime:this.runtime,statusSink:this.statusSink,streamIdleTimeoutMs:this.streamIdleTimeoutMs,modelIoFullRetentionEnabled:this.modelIoFullRetentionEnabled})}};r(c6s,"requireMaxOutputTokens");r(l6s,"hasRequestAuth");r(u6s,"assertSameBoundModel");r(EVr,"projectRequestHistory")});function y6s(e,t,n){let o=Gln(n);return{"User-Agent":`ZCode/${e??"unknown"}`,...e?{"X-ZCode-App-Version":e}:{},...v6s(t),...o?{"x-api-key":o}:{},Accept:"application/json"}}function v6s(e){let t={};for(let[n,o]of Object.entries(e??{})){let s=g6s[n.toLowerCase()],a=Gln(o);s&&a&&(t[s]=a)}return t}function b6s(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{throw new Error("agent_configs_invalid_json")}let n=_6s.parse(t);if(n.code!==0)throw new Error("agent_configs_nonzero_code");let o=new Map;for(let s of n.data.proxyEndpoint?.mapping??[]){let a=PVr(s.from,"from"),l=PVr(s.to,"to"),u=RVr(a);if(o.has(u))throw new Error("agent_configs_duplicate_from");o.set(u,S6s(l))}return o}function PVr(e,t){let n;try{n=new URL(e)}catch{throw new Error(`agent_configs_invalid_${t}_url`)}if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash)throw new Error(`agent_configs_unsafe_${t}_url`);return n}function S6s(e){let t=new URL(e);return t.pathname=pat(t.pathname),t}function RVr(e){let t=e.port||"443";return`${e.protocol}//${e.hostname.toLowerCase()}:${t}${pat(e.pathname)}`}function pat(e){return e===Vln?Vln:e.replace(/\/+$/u,"")||Vln}function w6s(e){try{let t=new URL(e);return t.protocol==="https:"?t:void 0}catch{return}}function k6s(e,t){if(!e||e.size!==t.size)return!1;for(let[n,o]of t)if(e.get(n)?.href!==o.href)return!1;return!0}function x6s(e){let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw new Error("Provider endpoint routing config URL must use HTTP(S).");return t.href}function T6s(e){return Gln(e)}function Gln(e){let t=e?.trim();if(!(!t||!/^[\x20-\x7e]+$/u.test(t)))return t}function I6s(e){return e instanceof m.ZodError?"invalid_schema":e instanceof Error?e.name==="HttpClientPortError"?"http_client_error":e.message.startsWith("agent_configs_")?e.message:"unexpected_error":"unknown_error"}function Hln(e){if(e?.aborted)throw DVr(e)}function C6s(e,t){return t?(Hln(t),new Promise((n,o)=>{let s=r(()=>{o(DVr(t))},"onAbort");t.addEventListener("abort",s,{once:!0}),e.then(()=>{t.removeEventListener("abort",s),n()},a=>{t.removeEventListener("abort",s),o(a)})})):e}function DVr(e){if(e.reason instanceof Error)return e.reason;let t=new Error("The operation was aborted.");return t.name="AbortError",t}var d6s,p6s,f6s,m6s,h6s,Vln,g6s,_6s,dat,OVr=Y(()=>{"use strict";Fa();d6s=300*1e3,p6s=30*1e3,f6s=3*1e3,m6s=256*1024,h6s=256,Vln="/",g6s={"http-referer":"HTTP-Referer","user-agent":"User-Agent","x-client-language":"X-Client-Language","x-client-timezone":"X-Client-Timezone","x-device-mid":"X-Device-Mid","x-os-category":"X-Os-Category","x-os-version":"X-Os-Version","x-platform":"X-Platform","x-release-channel":"X-Release-Channel","x-title":"X-Title","x-zcode-app-version":"X-ZCode-App-Version"},_6s=m.object({code:m.number(),data:m.object({proxyEndpoint:m.object({mapping:m.array(m.object({from:m.string(),to:m.string()}).strict()).max(h6s)}).strict().optional()}).passthrough()}).passthrough(),dat=class{static{r(this,"ProviderEndpointRoutingService")}appVersion;configUrl;failureCooldownMs;httpClient;logger;maxResponseBytes;now;requestTimeoutMs;sourceHeaders;successTtlMs;refreshPromise;retryAfter=0;snapshot;constructor(t){this.appVersion=T6s(t.appVersion),this.configUrl=x6s(t.configUrl),this.failureCooldownMs=t.failureCooldownMs??p6s,this.httpClient=t.httpClient,this.logger=t.logger,this.maxResponseBytes=t.maxResponseBytes??m6s,this.now=t.now??Date.now,this.requestTimeoutMs=t.requestTimeoutMs??f6s,this.sourceHeaders=t.sourceHeaders,this.successTtlMs=t.successTtlMs??d6s}async resolve(t,n={}){let o=w6s(t);if(!o)return{routed:!1,url:t};Hln(n.signal),await this.ensureFresh(n),Hln(n.signal);let s=this.snapshot?.mapping.get(RVr(o));if(!s)return{routed:!1,url:t};let a=new URL(s);return a.search=o.search,this.logger?.debug("Provider endpoint routing matched",{event:"model.provider_endpoint_routing.matched",sourceHost:o.host,sourcePath:pat(o.pathname),targetHost:a.host,targetPath:pat(a.pathname),traceId:n.trace?.traceId}),{routed:!0,url:a.href}}async ensureFresh(t){let n=this.now();if(this.snapshot&&this.snapshot.expiresAt>n||this.retryAfter>n)return;let o=this.refreshPromise??this.beginRefresh(t);await C6s(o,t.signal)}beginRefresh(t){let n=this.refresh(t).finally(()=>{this.refreshPromise===n&&(this.refreshPromise=void 0)});return this.refreshPromise=n,n}async refresh(t){try{let n=this.sourceHeaders?await this.sourceHeaders():void 0,o=await this.httpClient.request({headers:y6s(this.appVersion,n,t.apiKey),maxResponseBytes:this.maxResponseBytes,method:"GET",redirect:"manual",timeoutMs:this.requestTimeoutMs,url:this.configUrl});if(o.status<200||o.status>=300)throw new Error(`agent_configs_http_${o.status}`);let s=b6s(o.body),a=!k6s(this.snapshot?.mapping,s);this.snapshot={expiresAt:this.now()+this.successTtlMs,mapping:s},this.retryAfter=0,a?this.logger?.info("Provider endpoint routing snapshot updated",{event:"model.provider_endpoint_routing.snapshot_updated",mappingCount:s.size,traceId:t.trace?.traceId}):this.logger?.debug("Provider endpoint routing snapshot refreshed",{event:"model.provider_endpoint_routing.snapshot_refreshed",mappingCount:s.size,traceId:t.trace?.traceId})}catch(n){this.retryAfter=this.now()+this.failureCooldownMs,this.logger?.warn("Provider endpoint routing refresh failed",{configHost:new URL(this.configUrl).host,error:I6s(n),event:"model.provider_endpoint_routing.refresh_failed",retryAfterMs:this.failureCooldownMs,traceId:t.trace?.traceId})}}};r(y6s,"buildConfigHeaders");r(v6s,"filterConfigSourceHeaders");r(b6s,"parseRoutingMapping");r(PVr,"parseMappingUrl");r(S6s,"normalizeEndpointUrl");r(RVr,"endpointKey");r(pat,"normalizedPath");r(w6s,"parseHttpsUrl");r(k6s,"sameMapping");r(x6s,"assertConfigUrl");r(T6s,"normalizeVersion");r(Gln,"normalizePrintableHeaderValue");r(I6s,"errorCategory");r(Hln,"assertNotAborted");r(C6s,"waitForSharedRefresh");r(DVr,"abortReason")});var fOe=Y(()=>{"use strict";zne();P7();AVr();Wln();Gan();oat();fln();gln();jln();OVr();Uan()});async function jVr(e){let t=BVr(e.retentionDays),n=P6s(e.now??new Date,t),o={cutoffDate:n,deletedFiles:[],failedFiles:[],retentionDays:t,scannedFiles:0,status:"completed"},s;try{s=await(0,fat.readdir)(e.logDir,{withFileTypes:!0})}catch(a){return MVr(a,"ENOENT")||(o.status="failed",D6s(e,o,a)),o}for(let a of s){if(!a.isFile())continue;let l=R6s(a.name);if(l&&(o.scannedFiles+=1,!(l>=n)))try{await(0,fat.unlink)((0,NVr.join)(e.logDir,a.name)),o.deletedFiles.push(a.name)}catch(u){if(MVr(u,"ENOENT"))continue;o.failedFiles.push(a.name),o.status="failed",O6s(e,o,a.name,u)}}return e.logger?.debug("Log retention cleanup completed",{cutoffDate:n,deletedFileCount:o.deletedFiles.length,event:"log.retention.cleanup.completed",failedFileCount:o.failedFiles.length,logDir:e.logDir,module:"adapters.logging",retentionDays:t,scannedFiles:o.scannedFiles,status:o.status}),o}function Jln(e){let t=e.delayMs??FVr,n=BVr(e.retentionDays);e.logger?.info("Log retention cleanup scheduled",{delayMs:t,event:"log.retention.cleanup.scheduled",logDir:e.logDir,module:"adapters.logging",retentionDays:n,status:"waiting"});let s=(e.setTimeout??((a,l)=>setTimeout(a,l)))(()=>{jVr({logDir:e.logDir,logger:e.logger,now:e.now?.()??new Date,retentionDays:n})},t);return s.unref?.(),s}function mOe(e){return[e.getFullYear().toString().padStart(4,"0"),(e.getMonth()+1).toString().padStart(2,"0"),e.getDate().toString().padStart(2,"0")].join("-")}function P6s(e,t){return mOe(new Date(e.getFullYear(),e.getMonth(),e.getDate()-t+1))}function BVr(e){return e===void 0||!Number.isFinite(e)?LVr:Math.max(A6s,Math.trunc(e))}function R6s(e){let t=E6s.exec(e);if(!t)return;let[,n,o,s]=t,a=new Date(Number(n),Number(o)-1,Number(s)),l=mOe(a);return l===`${n}-${o}-${s}`?l:void 0}function D6s(e,t,n){e.logger?.warn("Log retention cleanup failed",{cutoffDate:t.cutoffDate,error:UVr(n),event:"log.retention.cleanup.failed",logDir:e.logDir,module:"adapters.logging",retentionDays:t.retentionDays,status:"failed"})}function O6s(e,t,n,o){e.logger?.warn("Log retention file delete failed",{cutoffDate:t.cutoffDate,error:UVr(o),event:"log.retention.delete.failed",fileName:n,logDir:e.logDir,module:"adapters.logging",retentionDays:t.retentionDays,status:"failed"})}function UVr(e){return e instanceof Error?{code:e.code,message:e.message,name:e.name}:{message:String(e),name:"UnknownError"}}function MVr(e,t){return e instanceof Error&&e.code===t}var fat,NVr,LVr,FVr,E6s,A6s,Kln=Y(()=>{"use strict";fat=require("node:fs/promises"),NVr=require("node:path"),LVr=7,FVr=6e4,E6s=/^zcode-(\d{4})-(\d{2})-(\d{2})\.jsonl$/,A6s=1;r(jVr,"cleanupLogRetention");r(Jln,"scheduleLogRetentionCleanup");r(mOe,"formatLocalLogDate");r(P6s,"getCutoffDate");r(BVr,"normalizeRetentionDays");r(R6s,"parseLogFileDate");r(D6s,"warnCleanupFailed");r(O6s,"warnDeleteFailed");r(UVr,"summarizeError");r(MVr,"hasFileSystemCode")});function $Vr(e){let{durationMs:t,event:n,module:o,parentSpanId:s,sessionId:a,spanId:l,status:u,toolCallId:f,traceId:g,turnId:_,...b}=e;return Object.keys(b).length===0?void 0:b}function qVr(e,t){let n={timestamp:e.timestamp.toISOString(),level:e.levelName.toLowerCase(),event:e.event,module:e.module,message:e.message,traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId,sessionId:e.sessionId,turnId:e.turnId,toolCallId:e.toolCallId,durationMs:e.durationMs,status:e.status,context:t.redact(e.context),error:t.redact(e.error)};return Object.fromEntries(Object.entries(n).filter(([,o])=>o!==void 0))}function WVr(e){let t=e.traceId?` trace=${e.traceId.slice(0,8)}`:"",n=e.event?` event=${e.event}`:"";return`${e.levelName.toLowerCase()} [${e.module??"log"}]${t}${n} ${e.message}`}function VVr(e){return e==="started"||e==="waiting"||e==="completed"||e==="failed"||e==="cancelled"}function Zln(e,t,n=new WeakSet,o=0){if(o>8)return{name:"ErrorCauseDepthLimit",message:"Error cause chain exceeded the serialization depth limit."};if(e===null||typeof e!="object")return{name:"UnknownError",message:String(e)};if(n.has(e))return{name:"ErrorCauseCircularReference",message:"Error cause chain contained a circular reference."};n.add(e);let s=e,a=s.cause,l={name:typeof s.name=="string"?s.name:"Error",message:typeof s.message=="string"?s.message:String(e)},u=zVr(s,"code"),f=zVr(s,"type"),g=s.context;return u&&(l.code=u),f&&(l.type=f),t&&typeof s.stack=="string"&&(l.stack=s.stack),M6s(g)&&(l.context=g),a!==void 0&&(l.cause=Zln(a,t,n,o+1)),l}function zVr(e,t){let n=e[t];return typeof n=="string"&&n.length>0?n:void 0}function M6s(e){if(e===null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var hOe,Yln=Y(()=>{"use strict";hOe=class{static{r(this,"DefaultLogRedactor")}sensitiveKeyPattern=/(?:api[-_]?key|authorization|cookie|credential|password|secret|token)/i;redact(t){return this.redactValue(t,new WeakSet,0)}redactValue(t,n,o){return o>8?"[Redacted:DepthLimit]":t===null||typeof t!="object"?t:n.has(t)?"[Redacted:Circular]":(n.add(t),Array.isArray(t)?t.map(s=>this.redactValue(s,n,o+1)):Object.fromEntries(Object.entries(t).map(([s,a])=>[s,this.sensitiveKeyPattern.test(s)?"[Redacted]":this.redactValue(a,n,o+1)])))}};r($Vr,"stripReservedContext");r(qVr,"toSerializableEntry");r(WVr,"formatConsoleLine");r(VVr,"isLogStatus");r(Zln,"serializeLogError");r(zVr,"stringProperty");r(M6s,"isPlainObject")});function rB(e={}){let t=e.minLevel??L6s(e.env),n=!1,o=e.logDir??e.env?.ZCODE_LOG_DIR??N6s(),s=typeof e.console=="object"?e.console.stream:e.console===!0||e.env?.ZCODE_LOG_CONSOLE==="1"?process.stderr:void 0,a=e.redactor??new hOe,l=r((u,f={})=>new Xln({category:u,defaultContext:f,getMinLevel:r(()=>t,"getMinLevel"),logDir:o,consoleStream:s,includeErrorStack:e.includeErrorStack,redactor:a}),"create");return{createLogger(u){return l(u)},withContext(u){return l("root",u)},setLevel(u){t=u},getLogDir(){return o},scheduleLogRetentionCleanup(u={}){if(!n)return n=!0,Jln({...u,logDir:o,logger:u.logger??l("zcode",{module:"adapters.logging"})})}}}function N6s(){return(0,mat.join)((0,HVr.homedir)(),".zcode","cli","log")}function L6s(e){return F6s(e??process.env)?XO.Debug:XO.Info}function F6s(e){let t=XW(e[cz]);if(t==="development")return!0;if(t==="production"||t==="test")return!1;let n=process.argv[1]??"";return n.endsWith(".ts")&&n.includes(`${(0,mat.join)("packages","cli","src")}`)}function j6s(e){(0,q0e.existsSync)(e)||(xb({operation:"mkdir",path:e}),(0,q0e.mkdirSync)(e,{recursive:!0}))}function B6s(){return`zcode-${mOe(new Date)}.jsonl`}var q0e,HVr,mat,Xln,W0e=Y(()=>{"use strict";q0e=require("node:fs"),HVr=require("node:os"),mat=require("node:path");nr();ms();Kln();Yln();gfe();Kln();Yln();Xln=class e{static{r(this,"NodeFileLogger")}category;defaultContext;getMinLevel;logDir;consoleStream;includeErrorStack;redactor;constructor(t){this.category=t.category,this.defaultContext=t.defaultContext??{},this.getMinLevel=t.getMinLevel,this.logDir=t.logDir,this.consoleStream=t.consoleStream,this.includeErrorStack=t.includeErrorStack??!1,this.redactor=t.redactor}debug(t,n){this.log(XO.Debug,t,void 0,n)}info(t,n){this.log(XO.Info,t,void 0,n)}warn(t,n){this.log(XO.Warn,t,void 0,n)}error(t,n,o){this.log(XO.Error,t,n,o)}child(t){return new e({category:this.category,defaultContext:{...this.defaultContext,...t},getMinLevel:this.getMinLevel,logDir:this.logDir,consoleStream:this.consoleStream,includeErrorStack:this.includeErrorStack,redactor:this.redactor})}log(t,n,o,s){if(t<this.getMinLevel())return;let a={...this.defaultContext,...s},l=this.createEntry(t,n,a,o),u=qVr(l,this.redactor),f=JSON.stringify(u);try{j6s(this.logDir);let g=(0,mat.join)(this.logDir,B6s());xb({operation:"appendFile",path:g}),(0,q0e.appendFileSync)(g,`${f}
|
|
2113
2113
|
`,"utf8")}catch{}this.consoleStream&&this.consoleStream.write(`${WVr(l)}
|
|
2114
|
-
`)}createEntry(t,n,o,s){return{timestamp:new Date,level:t,levelName:kyr[t],event:typeof o.event=="string"?o.event:void 0,module:typeof o.module=="string"?o.module:this.category,message:n,traceId:o.traceId,sessionId:typeof o.sessionId=="string"?o.sessionId:void 0,turnId:typeof o.turnId=="string"?o.turnId:void 0,spanId:typeof o.spanId=="string"?o.spanId:void 0,parentSpanId:typeof o.parentSpanId=="string"?o.parentSpanId:void 0,toolCallId:typeof o.toolCallId=="string"?o.toolCallId:void 0,durationMs:typeof o.durationMs=="number"?o.durationMs:void 0,status:VVr(o.status)?o.status:void 0,context:$Vr(o),error:s?Zln(s,this.includeErrorStack):void 0}}};r(rB,"createNodeLoggerFactory");r(N6s,"getDefaultLogDir");r(L6s,"getDefaultMinLevel");r(F6s,"isDevelopmentMode");r(j6s,"ensureLogDir");r(B6s,"getLogFileName")});function gOe(e){return e===T2?OA:e}function ure(e){return gOe(e)===OA?[OA,T2]:[e]}function ljs(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t={...e};return!("env"in t)&&"environment"in t&&(t.env=t.environment),delete t.environment,(typeof t.enable=="boolean"||typeof t.enabled=="boolean")&&(t.enabled=t.enable===!1?!1:t.enabled??!0),delete t.enable,delete t.timeout,delete t.startup_timeout_sec,t.type==="remote"?t.type="http":typeof t.type!="string"&&(typeof t.command=="string"&&t.command.trim().length>0?t.type="stdio":typeof t.url=="string"&&t.url.trim().length>0&&(t.type="http")),(t.type==="http"||t.type==="sse")&&t.headers===void 0&&t.http_headers!==void 0&&(t.headers=t.http_headers),delete t.http_headers,t}function XVr(e){let t=[],n=pjs(e,t),o=YVr.parse(n);return{config:ujs(o),diagnostics:t}}function ujs(e){let t={};e.modelStream&&(t.modelStream=e.modelStream),e.permission&&(t.permission=e.permission),e.storage&&(t.storage=e.storage),e.network&&(t.network=e.network),e.features&&(t.features=e.features),e.memory&&(t.memory=e.memory),e.mcp&&(t.mcp=e.mcp),e.plugins&&(t.plugins=djs(e.plugins));let n=mjs(e.skills);n&&(t.skills=n);let o=gjs(e.skill,hjs(e.skills));return o&&(t.skillOverrides=o),e.command&&(t.commandOverrides=e.command),e.logging&&(t.logging=e.logging),e.ui&&(t.ui=e.ui),e.toolConcurrency&&(t.toolConcurrency=e.toolConcurrency),e.modelAnomalyGuard&&(t.modelAnomalyGuard=e.modelAnomalyGuard),e.hooks&&(t.hooks=e.hooks),t}function djs(e){if(!e)return{};let t=e.enabledPlugins?{...e.enabledPlugins}:void 0;t?.[T2]!==void 0&&(t[OA]===void 0&&(t[OA]=t[T2]),delete t[T2]);let n=e.suppressedBuiltins?e.suppressedBuiltins.reduce((s,a)=>{let l=a===T2?OA:a;return l===OA&&s.includes(OA)||s.push(l),s},[]):void 0,o=e.options?{...e.options}:void 0;return o?.[T2]!==void 0&&(o[OA]===void 0&&(o[OA]=o[T2]),delete o[T2]),{...e,...t?{enabledPlugins:t}:{},...n?{suppressedBuiltins:n}:{},...o?{options:o}:{}}}function pjs(e,t){if(!Qln(e))return e;let n={...e},o=n.mcp;if(!Qln(o))return n;let s=o.servers;if(s===void 0)return n;if(!Qln(s))return t.push({code:"config_mcp_server_invalid",message:"mcp.servers must be a JSON object; ignoring all MCP servers.",path:"mcp.servers",severity:"warning"}),n.mcp={...o,servers:{}},n;let a={};for(let[l,u]of Object.entries(s)){let f=ZVr.safeParse(u);if(f.success){a[l]=f.data;continue}t.push({code:"config_mcp_server_invalid",message:fjs(f.error),path:`mcp.servers.${l}`,severity:"warning"})}return n.mcp={...o,servers:a},n}function fjs(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"<server>"}: ${t.message}`).join("; ")}function Qln(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mjs(e){if(!e)return;let t={};return e.enabled!==void 0&&(t.enabled=e.enabled),e.includeInstructions!==void 0&&(t.includeInstructions=e.includeInstructions),e.metadataBudget!==void 0&&(t.metadataBudget=e.metadataBudget),e.roots!==void 0&&(t.roots=e.roots),Object.keys(t).length>0?t:void 0}function hjs(e){if(!e)return;let t={};for(let[n,o]of Object.entries(e))!yjs(n)||!_js(o)||(t[n]={enable:o.enable});return Object.keys(t).length>0?t:void 0}function gjs(...e){let t={};for(let n of e)n&&Object.assign(t,n);return Object.keys(t).length>0?t:void 0}function _js(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&("enable"in e?typeof e.enable=="boolean":!0)}function yjs(e){return e.startsWith("/")||e.startsWith("\\")||/^[A-Za-z]:[\\/]/.test(e)}var hat,Uhl,oB,GVr,U6s,z6s,$6s,q6s,W6s,V6s,eun,KVr,H6s,G6s,J6s,ZVr,K6s,Z6s,Y6s,X6s,T2,OA,Q6s,ejs,JVr,tjs,njs,rjs,ojs,ijs,sjs,ajs,lre,cjs,YVr,tun=Y(()=>{"use strict";Fa();hat=m.record(m.string(),m.string()),Uhl=m.record(m.string(),m.unknown()),oB=m.number().finite().positive(),GVr=m.number().int().positive(),U6s=m.object({idleTimeoutMs:oB.optional()}),z6s=m.object({mode:m.enum(["plan","build","edit","yolo","auto"]).optional(),allowedTools:m.array(m.string()).optional(),disallowedTools:m.array(m.string()).optional(),autoApproveHighRisk:m.boolean().optional(),allowMediumRiskInAuto:m.boolean().optional()}),$6s=m.object({dir:m.string().min(1).optional(),sessionDbPath:m.string().min(1).optional()}),q6s=m.object({httpProxy:m.string().min(1).optional(),noProxy:m.string().min(1).optional(),caCertFile:m.string().min(1).optional(),timeout:oB.optional()}),W6s=m.object({compact:m.boolean().optional(),rewind:m.boolean().optional(),subagent:m.boolean().optional(),memory:m.boolean().optional(),skill:m.boolean().optional(),mcp:m.boolean().optional()}),V6s=m.object({use:m.boolean().optional()}),eun={protocolVersion:m.enum(["auto","legacy","2026-07-28"]).optional(),enabled:m.boolean().optional(),timeoutMs:oB.optional()},KVr=m.union([m.object({type:m.literal("client_credentials"),clientId:m.string().min(1),clientSecret:m.string().min(1),clientName:m.string().min(1).optional(),scope:m.string().optional()}).strict(),m.object({type:m.literal("authorization_code"),clientId:m.string().min(1).optional(),clientSecret:m.string().min(1).optional(),clientName:m.string().min(1).optional(),redirectPath:m.string().min(1).optional(),scope:m.string().optional()}).strict()]),H6s=m.object({...eun,type:m.literal("stdio"),command:m.string().min(1),args:m.array(m.string()).optional(),cwd:m.string().min(1).optional(),env:hat.optional()}).strict(),G6s=m.object({...eun,type:m.literal("http"),url:m.string().min(1),headers:hat.optional(),oauth:KVr.optional()}).strict(),J6s=m.object({...eun,type:m.literal("sse"),url:m.string().min(1),headers:hat.optional(),oauth:KVr.optional()}).strict(),ZVr=m.preprocess(ljs,m.discriminatedUnion("type",[H6s,G6s,J6s])),K6s=m.object({servers:m.record(m.string(),ZVr).optional()}),Z6s=m.union([m.string(),m.number(),m.boolean()]),Y6s=m.discriminatedUnion("source",[m.object({source:m.literal("url"),url:m.string().min(1),headers:hat.optional()}).strict(),m.object({source:m.literal("github"),repo:m.string().min(1),ref:m.string().min(1).optional(),path:m.string().min(1).optional(),sparsePaths:m.array(m.string().min(1)).optional()}).strict(),m.object({source:m.literal("git"),url:m.string().min(1),ref:m.string().min(1).optional(),path:m.string().min(1).optional(),sparsePaths:m.array(m.string().min(1)).optional()}).strict(),m.object({source:m.literal("npm"),package:m.string().min(1)}).strict(),m.object({source:m.literal("file"),path:m.string().min(1)}).strict(),m.object({source:m.literal("directory"),path:m.string().min(1)}).strict()]),X6s=m.object({enabled:m.boolean().optional(),dirs:m.array(m.string().min(1)).optional(),enabledPlugins:m.record(m.string(),m.boolean()).optional(),extraKnownMarketplaces:m.record(m.string().min(1),m.object({source:Y6s}).strict()).optional(),options:m.record(m.string(),m.record(m.string(),Z6s)).optional(),suppressedBuiltins:m.array(m.string().min(1)).optional()}),T2="zcode-cua@zcode-plugins-official",OA="computer-use@zcode-plugins-official";r(gOe,"canonicalizePluginId");r(ure,"pluginIdAliases");Q6s=m.object({enable:m.boolean().optional()}),ejs=m.object({enable:m.boolean().optional()}).passthrough(),JVr=m.record(m.string(),ejs),tjs=m.object({enabled:m.boolean().optional(),includeInstructions:m.boolean().optional(),metadataBudget:oB.optional(),roots:m.array(m.string()).optional()}).catchall(Q6s),njs=m.object({level:m.enum(["debug","info","warn","error"]).optional(),format:m.enum(["text","json"]).optional()}),rjs=m.object({locale:m.enum(["auto","en-US","zh-CN"]).optional(),theme:m.enum(["auto","dark","light"]).optional()}),ojs=m.object({maxConcurrency:oB.optional()}),ijs=m.object({toolCallWarningThreshold:GVr.optional(),repeatedToolCallWarningThreshold:GVr.optional(),maxBudgetWarningsPerTurn:m.number().int().nonnegative().optional()}),sjs=m.object({type:m.literal("process"),command:m.string().min(1),enabled:m.boolean().optional(),args:m.array(m.string()).optional(),timeoutMs:oB.optional(),statusMessage:m.string().min(1).optional()}).passthrough(),ajs=m.object({type:m.literal("command"),command:m.string().min(1),enabled:m.boolean().optional(),async:m.boolean().optional(),shell:m.union([m.literal(!0),m.string().min(1)]).optional(),timeout:oB.optional(),timeoutMs:oB.optional(),statusMessage:m.string().min(1).optional()}).passthrough(),lre=m.object({matcher:m.string().min(1).optional(),hooks:m.array(m.discriminatedUnion("type",[sjs,ajs])).min(1)}).strict(),cjs=m.object({enabled:m.boolean().optional(),timeoutMs:oB.optional(),maxOutputBytes:oB.optional(),events:m.object({SessionStart:m.array(lre).optional(),UserPromptSubmit:m.array(lre).optional(),PreToolUse:m.array(lre).optional(),PermissionRequest:m.array(lre).optional(),PostToolUse:m.array(lre).optional(),PostToolUseFailure:m.array(lre).optional(),Stop:m.array(lre).optional()}).strict().optional()}).strict(),YVr=m.object({$schema:m.string().optional(),modelStream:U6s.optional(),permission:z6s.optional(),storage:$6s.optional(),network:q6s.optional(),features:W6s.optional(),memory:V6s.optional(),mcp:K6s.optional(),plugins:X6s.optional(),skills:tjs.optional(),skill:JVr.optional(),command:JVr.optional(),logging:njs.optional(),ui:rjs.optional(),toolConcurrency:ojs.optional(),modelAnomalyGuard:ijs.optional(),hooks:cjs.optional()}).passthrough();r(ljs,"normalizeMcpServerConfigInput");r(XVr,"parseConfigFileToRuntimePatchWithDiagnostics");r(ujs,"parsedConfigFileToRuntimePatch");r(djs,"normalizePluginConfig");r(pjs,"normalizeConfigFileInput");r(fjs,"formatMcpServerError");r(Qln,"isPlainRecord");r(mjs,"parseSkillsRuntimeConfig");r(hjs,"parseSkillOverridesFromPluralSkills");r(gjs,"mergeSkillCommandOverrides");r(_js,"isSkillCommandOverrideValue");r(yjs,"isAbsoluteConfigPath")});function zg(e){return e.startsWith("~/")?(0,UF.join)((0,QVr.homedir)(),e.slice(2)):(0,UF.resolve)(e)}function _Oe(e,t={}){let n=e?zg(e):(0,UF.join)(zg(t.baseDir??tHr),t.configFileName??eHr);if(!(0,iB.existsSync)(n))return{config:{},diagnostics:[],path:n,loaded:!1};try{let o=(0,iB.readFileSync)(n,"utf-8"),s=JSON.parse(o),a=vjs(s);a&&bjs(n,a);let l=XVr(require(require("node:path").join(__dirname,"cli-config.cjs")).mergeDesktopSettings(s,n,process.env));return{config:l.config,diagnostics:wjs(l.diagnostics,n),path:n,loaded:!0}}catch(o){return{config:{},diagnostics:[Sjs(o,n)],path:n,loaded:!1}}}function vjs(e){if(!Rb(e)||!Rb(e.plugins))return;let t=e.plugins,n={...t},o=!1;if(Rb(t.enabledPlugins)){let s={...t.enabledPlugins};for(let[a,l]of Object.entries(t.enabledPlugins))if(a===T2){let u=OA;s[u]===void 0&&(s[u]=l),delete s[a],o=!0}o&&(n.enabledPlugins=s)}if(Array.isArray(t.suppressedBuiltins)){let s=t.suppressedBuiltins.map(a=>a===T2?OA:a);JSON.stringify(s)!==JSON.stringify(t.suppressedBuiltins)&&(n.suppressedBuiltins=s,o=!0)}if(Rb(t.options)){let s={...t.options};for(let[a,l]of Object.entries(t.options))if(a===T2){let u=OA;s[u]===void 0&&(s[u]=l),delete s[a],o=!0}o&&(n.options=s)}return o?{...e,plugins:n}:void 0}function bjs(e,t){let n=`${e}.migrate.${process.pid}.${Date.now()}.tmp`;try{(0,iB.writeFileSync)(n,`${JSON.stringify(t,null,2)}
|
|
2115
|
-
`,{encoding:"utf-8",mode:384}),(0,iB.renameSync)(n,e)}catch{try{(0,iB.unlinkSync)(n)}catch{}}}function Sjs(e,t){return{code:"config_file_invalid",filePath:t,message:e instanceof m.ZodError?kjs(e):e instanceof Error?e.message:"Unable to parse config file.",severity:"error"}}function wjs(e,t){return e.map(n=>({...n,filePath:n.filePath??t}))}function kjs(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"<config>"}: ${t.message}`).join("; ")}async function yOe(e,t){let n=zg(e),o=await dG(n),s=Tjs(o,t);return await pG(n,s),{locale:t,path:n}}async function nun(e,t,n){let o=zg(e),s=await dG(o),a=Ijs(s,t,n);return await pG(o,a),{enabled:n,path:o,pluginId:t}}async function run(e,t){let n=zg(e);if(t.length===0)return{enabledIds:[],path:n};let o=await dG(n),s=Rb(o.plugins)?o.plugins:{},a=Rb(s.enabledPlugins)?s.enabledPlugins:{},l=t.filter(f=>!Object.prototype.hasOwnProperty.call(a,f));if(l.length===0)return{enabledIds:[],path:n};let u={...o,plugins:{...s,enabledPlugins:{...a,...Object.fromEntries(l.map(f=>[f,!0]))}}};return await pG(n,u),{enabledIds:l,path:n}}async function oun(e,t,n,o=[]){let s=zg(e),a=await dG(s),l=Cjs(a,t,n,o);return await pG(s,l),{clearedOptionKeys:o,options:n,path:s,pluginId:t}}async function vOe(e,t){let n=zg(e),o=await dG(n),{next:s,removedEnabled:a,removedOptions:l}=Ejs(o,t);return(a||l)&&await pG(n,s),{path:n,pluginId:t,removedEnabled:a,removedOptions:l}}async function iun(e,t){let n=zg(e),o=await dG(n),s=Rb(o.plugins)?o.plugins:{},a=Rb(s.enabledPlugins)?s.enabledPlugins:{},l=ure(t);if(!l.some(g=>Object.prototype.hasOwnProperty.call(a,g)))return{path:n,pluginId:t,removedEnabled:!1};let f={...a};for(let g of l)delete f[g];return await pG(n,{...o,plugins:{...s,enabledPlugins:f}}),{path:n,pluginId:t,removedEnabled:!0}}async function sun(e,t){let n=zg(e),o=await dG(n),s=Rb(o.plugins)?o.plugins:{},a=gOe(t),l=ure(a),u=Array.isArray(s.suppressedBuiltins)?s.suppressedBuiltins.filter(_=>typeof _=="string"):[],f=u.filter(_=>!l.includes(_));if(f.length===u.length&&u.includes(a))return{path:n,pluginId:t,suppressed:!0};let g={...o,plugins:{...s,suppressedBuiltins:[...f,a]}};return await pG(n,g),{path:n,pluginId:t,suppressed:!0}}async function bOe(e,t){let n=zg(e),o=await dG(n),s=Rb(o.plugins)?o.plugins:{},a=ure(t),l=Array.isArray(s.suppressedBuiltins)?s.suppressedBuiltins.filter(g=>typeof g=="string"):[],u=l.filter(g=>!a.includes(g));if(u.length===l.length)return{path:n,pluginId:t,suppressed:!1};let f={...o,plugins:{...s,suppressedBuiltins:u}};return await pG(n,f),{path:n,pluginId:t,suppressed:!1}}function U7(){return(0,UF.join)(zg(tHr),eHr)}async function xjs(e){let t;try{t=await(0,sB.readFile)(e,"utf-8")}catch(o){throw new Error(`Unable to read config file: ${e}`,{cause:o})}let n;try{n=JSON.parse(t)}catch(o){throw new Error(`Unable to parse config file as JSON: ${e}`,{cause:o})}if(!Rb(n))throw new Error(`Config file must contain a JSON object: ${e}`);return n}async function dG(e){try{return await xjs(e)}catch(t){let n=t instanceof Error?t.cause:void 0;if(Ajs(n)&&n.code==="ENOENT")return{};throw t}}function Tjs(e,t){let n=Rb(e.ui)?e.ui:{};return{...e,ui:{...n,locale:t}}}function Ijs(e,t,n){let o=Rb(e.plugins)?e.plugins:{},s=Rb(o.enabledPlugins)?o.enabledPlugins:{},a=gOe(t),l={...s};for(let u of ure(a))delete l[u];return{...e,plugins:{...o,enabledPlugins:{...l,[a]:n}}}}function Cjs(e,t,n,o){let s=Rb(e.plugins)?e.plugins:{},a=Rb(s.options)?s.options:{},l=gOe(t),u=ure(l),f=u.length>1?u[1]:void 0,g=Rb(a[l])?a[l]:f&&Rb(a[f])?a[f]:{},_={...a};for(let T of u)delete _[T];let b=new Set(o),w=Object.fromEntries(Object.entries(g).filter(([T])=>!b.has(T)));return{...e,plugins:{...s,options:{..._,[l]:{...w,...n}}}}}function Ejs(e,t){let n=Rb(e.plugins)?e.plugins:{},o=Rb(n.enabledPlugins)?n.enabledPlugins:{},s=Rb(n.options)?n.options:{},a=ure(t),l=a.some(_=>_ in o),u=a.some(_=>_ in s);if(!l&&!u)return{next:e,removedEnabled:l,removedOptions:u};let f={...o};for(let _ of a)delete f[_];let g={...s};for(let _ of a)delete g[_];return{next:{...e,plugins:{...n,enabledPlugins:f,options:g}},removedEnabled:l,removedOptions:u}}async function pG(e,t){let n=(0,UF.dirname)(e);await(0,sB.mkdir)(n,{recursive:!0});let o=(0,UF.join)(n,`.${(0,UF.basename)(e)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`),s=`${JSON.stringify(t,null,2)}
|
|
2114
|
+
`)}createEntry(t,n,o,s){return{timestamp:new Date,level:t,levelName:kyr[t],event:typeof o.event=="string"?o.event:void 0,module:typeof o.module=="string"?o.module:this.category,message:n,traceId:o.traceId,sessionId:typeof o.sessionId=="string"?o.sessionId:void 0,turnId:typeof o.turnId=="string"?o.turnId:void 0,spanId:typeof o.spanId=="string"?o.spanId:void 0,parentSpanId:typeof o.parentSpanId=="string"?o.parentSpanId:void 0,toolCallId:typeof o.toolCallId=="string"?o.toolCallId:void 0,durationMs:typeof o.durationMs=="number"?o.durationMs:void 0,status:VVr(o.status)?o.status:void 0,context:$Vr(o),error:s?Zln(s,this.includeErrorStack):void 0}}};r(rB,"createNodeLoggerFactory");r(N6s,"getDefaultLogDir");r(L6s,"getDefaultMinLevel");r(F6s,"isDevelopmentMode");r(j6s,"ensureLogDir");r(B6s,"getLogFileName")});function gOe(e){return e===T2?OA:e}function ure(e){return gOe(e)===OA?[OA,T2]:[e]}function ljs(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t={...e};return!("env"in t)&&"environment"in t&&(t.env=t.environment),delete t.environment,(typeof t.enable=="boolean"||typeof t.enabled=="boolean")&&(t.enabled=t.enable===!1?!1:t.enabled??!0),delete t.enable,delete t.timeout,delete t.startup_timeout_sec,t.type==="remote"?t.type="http":typeof t.type!="string"&&(typeof t.command=="string"&&t.command.trim().length>0?t.type="stdio":typeof t.url=="string"&&t.url.trim().length>0&&(t.type="http")),(t.type==="http"||t.type==="sse")&&t.headers===void 0&&t.http_headers!==void 0&&(t.headers=t.http_headers),delete t.http_headers,t}function XVr(e){let t=[],n=pjs(e,t),o=YVr.parse(n);return{config:ujs(o),diagnostics:t}}function ujs(e){let t={};e.modelStream&&(t.modelStream=e.modelStream),e.permission&&(t.permission=e.permission),e.storage&&(t.storage=e.storage),e.network&&(t.network=e.network),e.features&&(t.features=e.features),e.memory&&(t.memory=e.memory),e.mcp&&(t.mcp=e.mcp),e.plugins&&(t.plugins=djs(e.plugins));let n=mjs(e.skills);n&&(t.skills=n);let o=gjs(e.skill,hjs(e.skills));return o&&(t.skillOverrides=o),e.command&&(t.commandOverrides=e.command),e.logging&&(t.logging=e.logging),e.ui&&(t.ui=e.ui),e.toolConcurrency&&(t.toolConcurrency=e.toolConcurrency),e.modelAnomalyGuard&&(t.modelAnomalyGuard=e.modelAnomalyGuard),e.hooks&&(t.hooks=e.hooks),t}function djs(e){if(!e)return{};let t=e.enabledPlugins?{...e.enabledPlugins}:void 0;t?.[T2]!==void 0&&(t[OA]===void 0&&(t[OA]=t[T2]),delete t[T2]);let n=e.suppressedBuiltins?e.suppressedBuiltins.reduce((s,a)=>{let l=a===T2?OA:a;return l===OA&&s.includes(OA)||s.push(l),s},[]):void 0,o=e.options?{...e.options}:void 0;return o?.[T2]!==void 0&&(o[OA]===void 0&&(o[OA]=o[T2]),delete o[T2]),{...e,...t?{enabledPlugins:t}:{},...n?{suppressedBuiltins:n}:{},...o?{options:o}:{}}}function pjs(e,t){if(!Qln(e))return e;let n={...e},o=n.mcp;if(!Qln(o))return n;let s=o.servers;if(s===void 0)return n;if(!Qln(s))return t.push({code:"config_mcp_server_invalid",message:"mcp.servers must be a JSON object; ignoring all MCP servers.",path:"mcp.servers",severity:"warning"}),n.mcp={...o,servers:{}},n;let a={};for(let[l,u]of Object.entries(s)){let f=ZVr.safeParse(u);if(f.success){a[l]=f.data;continue}t.push({code:"config_mcp_server_invalid",message:fjs(f.error),path:`mcp.servers.${l}`,severity:"warning"})}return n.mcp={...o,servers:a},n}function fjs(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"<server>"}: ${t.message}`).join("; ")}function Qln(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mjs(e){if(!e)return;let t={};return e.enabled!==void 0&&(t.enabled=e.enabled),e.includeInstructions!==void 0&&(t.includeInstructions=e.includeInstructions),e.metadataBudget!==void 0&&(t.metadataBudget=e.metadataBudget),e.roots!==void 0&&(t.roots=e.roots),Object.keys(t).length>0?t:void 0}function hjs(e){if(!e)return;let t={};for(let[n,o]of Object.entries(e))!yjs(n)||!_js(o)||(t[n]={enable:o.enable});return Object.keys(t).length>0?t:void 0}function gjs(...e){let t={};for(let n of e)n&&Object.assign(t,n);return Object.keys(t).length>0?t:void 0}function _js(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&("enable"in e?typeof e.enable=="boolean":!0)}function yjs(e){return e.startsWith("/")||e.startsWith("\\")||/^[A-Za-z]:[\\/]/.test(e)}var hat,Uhl,oB,GVr,U6s,z6s,$6s,q6s,W6s,V6s,eun,KVr,H6s,G6s,J6s,ZVr,K6s,Z6s,Y6s,X6s,T2,OA,Q6s,ejs,JVr,tjs,njs,rjs,ojs,ijs,sjs,ajs,lre,cjs,YVr,tun=Y(()=>{"use strict";Fa();hat=m.record(m.string(),m.string()),Uhl=m.record(m.string(),m.unknown()),oB=m.number().finite().positive(),GVr=m.number().int().positive(),U6s=m.object({idleTimeoutMs:oB.optional()}),z6s=m.object({mode:m.enum(["plan","build","edit","yolo","auto"]).optional(),allowedTools:m.array(m.string()).optional(),disallowedTools:m.array(m.string()).optional(),autoApproveHighRisk:m.boolean().optional(),allowMediumRiskInAuto:m.boolean().optional()}),$6s=m.object({dir:m.string().min(1).optional(),sessionDbPath:m.string().min(1).optional()}),q6s=m.object({httpProxy:m.string().min(1).optional(),noProxy:m.string().min(1).optional(),caCertFile:m.string().min(1).optional(),timeout:oB.optional()}),W6s=m.object({compact:m.boolean().optional(),rewind:m.boolean().optional(),subagent:m.boolean().optional(),memory:m.boolean().optional(),skill:m.boolean().optional(),mcp:m.boolean().optional()}),V6s=m.object({use:m.boolean().optional()}),eun={protocolVersion:m.enum(["auto","legacy","2026-07-28"]).optional(),enabled:m.boolean().optional(),timeoutMs:oB.optional()},KVr=m.union([m.object({type:m.literal("client_credentials"),clientId:m.string().min(1),clientSecret:m.string().min(1),clientName:m.string().min(1).optional(),scope:m.string().optional()}).strict(),m.object({type:m.literal("authorization_code"),clientId:m.string().min(1).optional(),clientSecret:m.string().min(1).optional(),clientName:m.string().min(1).optional(),redirectPath:m.string().min(1).optional(),scope:m.string().optional()}).strict()]),H6s=m.object({...eun,type:m.literal("stdio"),command:m.string().min(1),args:m.array(m.string()).optional(),cwd:m.string().min(1).optional(),env:hat.optional()}).strict(),G6s=m.object({...eun,type:m.literal("http"),url:m.string().min(1),headers:hat.optional(),oauth:KVr.optional()}).strict(),J6s=m.object({...eun,type:m.literal("sse"),url:m.string().min(1),headers:hat.optional(),oauth:KVr.optional()}).strict(),ZVr=m.preprocess(ljs,m.discriminatedUnion("type",[H6s,G6s,J6s])),K6s=m.object({servers:m.record(m.string(),ZVr).optional()}),Z6s=m.union([m.string(),m.number(),m.boolean()]),Y6s=m.discriminatedUnion("source",[m.object({source:m.literal("url"),url:m.string().min(1),headers:hat.optional()}).strict(),m.object({source:m.literal("github"),repo:m.string().min(1),ref:m.string().min(1).optional(),path:m.string().min(1).optional(),sparsePaths:m.array(m.string().min(1)).optional()}).strict(),m.object({source:m.literal("git"),url:m.string().min(1),ref:m.string().min(1).optional(),path:m.string().min(1).optional(),sparsePaths:m.array(m.string().min(1)).optional()}).strict(),m.object({source:m.literal("npm"),package:m.string().min(1)}).strict(),m.object({source:m.literal("file"),path:m.string().min(1)}).strict(),m.object({source:m.literal("directory"),path:m.string().min(1)}).strict()]),X6s=m.object({enabled:m.boolean().optional(),dirs:m.array(m.string().min(1)).optional(),enabledPlugins:m.record(m.string(),m.boolean()).optional(),extraKnownMarketplaces:m.record(m.string().min(1),m.object({source:Y6s}).strict()).optional(),options:m.record(m.string(),m.record(m.string(),Z6s)).optional(),suppressedBuiltins:m.array(m.string().min(1)).optional()}),T2="zcode-cua@zcode-plugins-official",OA="computer-use@zcode-plugins-official";r(gOe,"canonicalizePluginId");r(ure,"pluginIdAliases");Q6s=m.object({enable:m.boolean().optional()}),ejs=m.object({enable:m.boolean().optional()}).passthrough(),JVr=m.record(m.string(),ejs),tjs=m.object({enabled:m.boolean().optional(),includeInstructions:m.boolean().optional(),metadataBudget:oB.optional(),roots:m.array(m.string()).optional()}).catchall(Q6s),njs=m.object({level:m.enum(["debug","info","warn","error"]).optional(),format:m.enum(["text","json"]).optional()}),rjs=m.object({locale:m.enum(["auto","en-US","zh-CN"]).optional(),theme:m.enum(["auto","dark","light"]).optional()}),ojs=m.object({maxConcurrency:oB.optional()}),ijs=m.object({toolCallWarningThreshold:GVr.optional(),repeatedToolCallWarningThreshold:GVr.optional(),maxBudgetWarningsPerTurn:m.number().int().nonnegative().optional()}),sjs=m.object({type:m.literal("process"),command:m.string().min(1),enabled:m.boolean().optional(),args:m.array(m.string()).optional(),timeoutMs:oB.optional(),statusMessage:m.string().min(1).optional()}).passthrough(),ajs=m.object({type:m.literal("command"),command:m.string().min(1),enabled:m.boolean().optional(),async:m.boolean().optional(),shell:m.union([m.literal(!0),m.string().min(1)]).optional(),timeout:oB.optional(),timeoutMs:oB.optional(),statusMessage:m.string().min(1).optional()}).passthrough(),lre=m.object({matcher:m.string().min(1).optional(),hooks:m.array(m.discriminatedUnion("type",[sjs,ajs])).min(1)}).strict(),cjs=m.object({enabled:m.boolean().optional(),timeoutMs:oB.optional(),maxOutputBytes:oB.optional(),events:m.object({SessionStart:m.array(lre).optional(),UserPromptSubmit:m.array(lre).optional(),PreToolUse:m.array(lre).optional(),PermissionRequest:m.array(lre).optional(),PostToolUse:m.array(lre).optional(),PostToolUseFailure:m.array(lre).optional(),Stop:m.array(lre).optional()}).strict().optional()}).strict(),YVr=m.object({$schema:m.string().optional(),modelStream:U6s.optional(),permission:z6s.optional(),storage:$6s.optional(),network:q6s.optional(),features:W6s.optional(),memory:V6s.optional(),mcp:K6s.optional(),plugins:X6s.optional(),skills:tjs.optional(),skill:JVr.optional(),command:JVr.optional(),logging:njs.optional(),ui:rjs.optional(),toolConcurrency:ojs.optional(),modelAnomalyGuard:ijs.optional(),hooks:cjs.optional()}).passthrough();r(ljs,"normalizeMcpServerConfigInput");r(XVr,"parseConfigFileToRuntimePatchWithDiagnostics");r(ujs,"parsedConfigFileToRuntimePatch");r(djs,"normalizePluginConfig");r(pjs,"normalizeConfigFileInput");r(fjs,"formatMcpServerError");r(Qln,"isPlainRecord");r(mjs,"parseSkillsRuntimeConfig");r(hjs,"parseSkillOverridesFromPluralSkills");r(gjs,"mergeSkillCommandOverrides");r(_js,"isSkillCommandOverrideValue");r(yjs,"isAbsoluteConfigPath")});function zg(e){return e.startsWith("~/")?(0,UF.join)((0,QVr.homedir)(),e.slice(2)):(0,UF.resolve)(e)}function _Oe(e,t={}){let n=e?zg(e):(t.baseDir===void 0&&t.configFileName===void 0&&process.env.ZCODE_CLI_SETTINGS_FILE?.trim()?require("node:path").resolve(process.env.ZCODE_CLI_SETTINGS_FILE?.trim()):(0,UF.join)(zg(t.baseDir??tHr),t.configFileName??eHr));if(!(0,iB.existsSync)(n))return{config:{},diagnostics:[],path:n,loaded:!1};try{let o=(0,iB.readFileSync)(n,"utf-8"),s=JSON.parse(o),a=vjs(s);a&&bjs(n,a);let l=XVr(require(require("node:path").join(__dirname,"cli-config.cjs")).mergeDesktopSettings(s,n,process.env));return{config:l.config,diagnostics:wjs(l.diagnostics,n),path:n,loaded:!0}}catch(o){return{config:{},diagnostics:[Sjs(o,n)],path:n,loaded:!1}}}function vjs(e){if(!Rb(e)||!Rb(e.plugins))return;let t=e.plugins,n={...t},o=!1;if(Rb(t.enabledPlugins)){let s={...t.enabledPlugins};for(let[a,l]of Object.entries(t.enabledPlugins))if(a===T2){let u=OA;s[u]===void 0&&(s[u]=l),delete s[a],o=!0}o&&(n.enabledPlugins=s)}if(Array.isArray(t.suppressedBuiltins)){let s=t.suppressedBuiltins.map(a=>a===T2?OA:a);JSON.stringify(s)!==JSON.stringify(t.suppressedBuiltins)&&(n.suppressedBuiltins=s,o=!0)}if(Rb(t.options)){let s={...t.options};for(let[a,l]of Object.entries(t.options))if(a===T2){let u=OA;s[u]===void 0&&(s[u]=l),delete s[a],o=!0}o&&(n.options=s)}return o?{...e,plugins:n}:void 0}function bjs(e,t){let n=`${e}.migrate.${process.pid}.${Date.now()}.tmp`;try{(0,iB.writeFileSync)(n,`${JSON.stringify(t,null,2)}
|
|
2115
|
+
`,{encoding:"utf-8",mode:384}),(0,iB.renameSync)(n,e)}catch{try{(0,iB.unlinkSync)(n)}catch{}}}function Sjs(e,t){return{code:"config_file_invalid",filePath:t,message:e instanceof m.ZodError?kjs(e):e instanceof Error?e.message:"Unable to parse config file.",severity:"error"}}function wjs(e,t){return e.map(n=>({...n,filePath:n.filePath??t}))}function kjs(e){return e.issues.map(t=>`${t.path.length>0?t.path.join("."):"<config>"}: ${t.message}`).join("; ")}async function yOe(e,t){let n=zg(e),o=await dG(n),s=Tjs(o,t);return await pG(n,s),{locale:t,path:n}}async function nun(e,t,n){let o=zg(e),s=await dG(o),a=Ijs(s,t,n);return await pG(o,a),{enabled:n,path:o,pluginId:t}}async function run(e,t){let n=zg(e);if(t.length===0)return{enabledIds:[],path:n};let o=await dG(n),s=Rb(o.plugins)?o.plugins:{},a=Rb(s.enabledPlugins)?s.enabledPlugins:{},l=t.filter(f=>!Object.prototype.hasOwnProperty.call(a,f));if(l.length===0)return{enabledIds:[],path:n};let u={...o,plugins:{...s,enabledPlugins:{...a,...Object.fromEntries(l.map(f=>[f,!0]))}}};return await pG(n,u),{enabledIds:l,path:n}}async function oun(e,t,n,o=[]){let s=zg(e),a=await dG(s),l=Cjs(a,t,n,o);return await pG(s,l),{clearedOptionKeys:o,options:n,path:s,pluginId:t}}async function vOe(e,t){let n=zg(e),o=await dG(n),{next:s,removedEnabled:a,removedOptions:l}=Ejs(o,t);return(a||l)&&await pG(n,s),{path:n,pluginId:t,removedEnabled:a,removedOptions:l}}async function iun(e,t){let n=zg(e),o=await dG(n),s=Rb(o.plugins)?o.plugins:{},a=Rb(s.enabledPlugins)?s.enabledPlugins:{},l=ure(t);if(!l.some(g=>Object.prototype.hasOwnProperty.call(a,g)))return{path:n,pluginId:t,removedEnabled:!1};let f={...a};for(let g of l)delete f[g];return await pG(n,{...o,plugins:{...s,enabledPlugins:f}}),{path:n,pluginId:t,removedEnabled:!0}}async function sun(e,t){let n=zg(e),o=await dG(n),s=Rb(o.plugins)?o.plugins:{},a=gOe(t),l=ure(a),u=Array.isArray(s.suppressedBuiltins)?s.suppressedBuiltins.filter(_=>typeof _=="string"):[],f=u.filter(_=>!l.includes(_));if(f.length===u.length&&u.includes(a))return{path:n,pluginId:t,suppressed:!0};let g={...o,plugins:{...s,suppressedBuiltins:[...f,a]}};return await pG(n,g),{path:n,pluginId:t,suppressed:!0}}async function bOe(e,t){let n=zg(e),o=await dG(n),s=Rb(o.plugins)?o.plugins:{},a=ure(t),l=Array.isArray(s.suppressedBuiltins)?s.suppressedBuiltins.filter(g=>typeof g=="string"):[],u=l.filter(g=>!a.includes(g));if(u.length===l.length)return{path:n,pluginId:t,suppressed:!1};let f={...o,plugins:{...s,suppressedBuiltins:u}};return await pG(n,f),{path:n,pluginId:t,suppressed:!1}}function U7(){return process.env.ZCODE_CLI_SETTINGS_FILE?.trim()?require("node:path").resolve(process.env.ZCODE_CLI_SETTINGS_FILE?.trim()):(0,UF.join)(zg(tHr),eHr)}async function xjs(e){let t;try{t=await(0,sB.readFile)(e,"utf-8")}catch(o){throw new Error(`Unable to read config file: ${e}`,{cause:o})}let n;try{n=JSON.parse(t)}catch(o){throw new Error(`Unable to parse config file as JSON: ${e}`,{cause:o})}if(!Rb(n))throw new Error(`Config file must contain a JSON object: ${e}`);return n}async function dG(e){try{return await xjs(e)}catch(t){let n=t instanceof Error?t.cause:void 0;if(Ajs(n)&&n.code==="ENOENT")return{};throw t}}function Tjs(e,t){let n=Rb(e.ui)?e.ui:{};return{...e,ui:{...n,locale:t}}}function Ijs(e,t,n){let o=Rb(e.plugins)?e.plugins:{},s=Rb(o.enabledPlugins)?o.enabledPlugins:{},a=gOe(t),l={...s};for(let u of ure(a))delete l[u];return{...e,plugins:{...o,enabledPlugins:{...l,[a]:n}}}}function Cjs(e,t,n,o){let s=Rb(e.plugins)?e.plugins:{},a=Rb(s.options)?s.options:{},l=gOe(t),u=ure(l),f=u.length>1?u[1]:void 0,g=Rb(a[l])?a[l]:f&&Rb(a[f])?a[f]:{},_={...a};for(let T of u)delete _[T];let b=new Set(o),w=Object.fromEntries(Object.entries(g).filter(([T])=>!b.has(T)));return{...e,plugins:{...s,options:{..._,[l]:{...w,...n}}}}}function Ejs(e,t){let n=Rb(e.plugins)?e.plugins:{},o=Rb(n.enabledPlugins)?n.enabledPlugins:{},s=Rb(n.options)?n.options:{},a=ure(t),l=a.some(_=>_ in o),u=a.some(_=>_ in s);if(!l&&!u)return{next:e,removedEnabled:l,removedOptions:u};let f={...o};for(let _ of a)delete f[_];let g={...s};for(let _ of a)delete g[_];return{next:{...e,plugins:{...n,enabledPlugins:f,options:g}},removedEnabled:l,removedOptions:u}}async function pG(e,t){let n=(0,UF.dirname)(e);await(0,sB.mkdir)(n,{recursive:!0});let o=(0,UF.join)(n,`.${(0,UF.basename)(e)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`),s=`${JSON.stringify(t,null,2)}
|
|
2116
2116
|
`;try{await(0,sB.writeFile)(o,s,{mode:384}),await(0,sB.rename)(o,e)}catch(a){throw await(0,sB.unlink)(o).catch(()=>{}),new Error(`Unable to write config file: ${e}`,{cause:a})}}function Rb(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ajs(e){return e instanceof Error&&"code"in e}var iB,sB,QVr,UF,eHr,tHr,gat=Y(()=>{"use strict";iB=require("node:fs"),sB=require("node:fs/promises"),QVr=require("node:os"),UF=require("node:path");Fa();tun();eHr="setting.json",tHr="~/.zcode/cli";r(zg,"resolvePath");r(_Oe,"loadFileConfig");r(vjs,"migratePluginConfigInFile");r(bjs,"persistPluginConfigMigration");r(Sjs,"createConfigFileInvalidDiagnostic");r(wjs,"attachDiagnosticFilePath");r(kjs,"formatZodError");r(yOe,"updateUiLocaleInFileConfig");r(nun,"updatePluginEnabledInFileConfig");r(run,"enablePluginsByDefaultInFileConfig");r(oun,"updatePluginOptionsInFileConfig");r(vOe,"removePluginFromFileConfig");r(iun,"removePluginEnabledFromFileConfig");r(sun,"addSuppressedBuiltinInFileConfig");r(bOe,"removeSuppressedBuiltinInFileConfig");r(U7,"getDefaultConfigPath");r(xjs,"readJsonConfigFile");r(dG,"readJsonConfigFileOrEmpty");r(Tjs,"patchUiLocale");r(Ijs,"patchPluginEnabled");r(Cjs,"patchPluginOptions");r(Ejs,"patchPluginRemoved");r(pG,"atomicWriteJson");r(Rb,"isRecord");r(Ajs,"isNodeError")});function aun(e=process.env,t={}){let n=t.prefix??Pjs,o={};for(let[s,a]of Object.entries(e)){if(!s.startsWith(n)||a===void 0)continue;let l=s.slice(n.length);l==="STORAGE_DIR"?(o.storage||(o.storage={}),o.storage.dir=a):l==="SESSION_DB_PATH"||l==="SESSION_DB"?(o.storage||(o.storage={}),o.storage.sessionDbPath=a):l==="HTTP_PROXY"?(o.network||(o.network={}),o.network.httpProxy=a):l==="NO_PROXY"?(o.network||(o.network={}),o.network.noProxy=a):l==="AGENT_CA_CERT"?(o.network||(o.network={}),o.network.caCertFile=a):l==="HTTP_TIMEOUT"||l==="TIMEOUT"?(o.network||(o.network={}),o.network.timeout=nHr(a)):l==="LOG_FORMAT"?(o.logging||(o.logging={}),o.logging.format=Rjs(a)):l==="MAX_TOOL_CONCURRENCY"&&(o.toolConcurrency||(o.toolConcurrency={}),o.toolConcurrency.maxConcurrency=nHr(a))}return o}function nHr(e){let t=Number(e);return isNaN(t)?0:t}function Rjs(e){let t=e.toLowerCase();return t==="text"||t==="json"?t:"text"}var Pjs,cun=Y(()=>{"use strict";Pjs="ZCODE_";r(aun,"parseEnvConfig");r(nHr,"normalizeNumber");r(Rjs,"normalizeLogFormat")});function _at(...e){let t=[...e].sort((o,s)=>o.priority-s.priority),n={};for(let{config:o,scope:s}of t){let a=s===Ek.Project&&o.plugins?(()=>{let f={...o.plugins};return delete f.extraKnownMarketplaces,{...o,plugins:f}})():o,l=n.hooks,u=n.plugins;Object.assign(n,a),a.modelStream&&(n.modelStream={...n.modelStream,...a.modelStream}),a.permission&&(n.permission={...n.permission,...a.permission}),a.storage&&(n.storage={...n.storage,...a.storage}),a.network&&(n.network={...n.network,...a.network}),a.features&&(n.features={...n.features,...a.features}),a.memory&&(n.memory={...n.memory,...a.memory}),a.mcp&&(n.mcp={...n.mcp,...a.mcp,servers:{...n.mcp?.servers,...a.mcp.servers}}),a.plugins&&(n.plugins={...u,...a.plugins,...a.plugins.dirs?{dirs:[...new Set([...u?.dirs??[],...a.plugins.dirs])]}:{},...a.plugins.enabledPlugins?{enabledPlugins:{...u?.enabledPlugins,...a.plugins.enabledPlugins}}:{},...a.plugins.extraKnownMarketplaces?{extraKnownMarketplaces:{...u?.extraKnownMarketplaces,...a.plugins.extraKnownMarketplaces}}:{},...a.plugins.options?{options:Djs(u?.options,a.plugins.options)}:{}}),a.skills&&(n.skills={...n.skills,...a.skills}),a.skillOverrides&&(n.skillOverrides={...n.skillOverrides,...a.skillOverrides}),a.commandOverrides&&(n.commandOverrides={...n.commandOverrides,...a.commandOverrides}),a.logging&&(n.logging={...n.logging,...a.logging}),a.toolConcurrency&&(n.toolConcurrency={...n.toolConcurrency,...a.toolConcurrency}),a.modelAnomalyGuard&&(n.modelAnomalyGuard={...n.modelAnomalyGuard,...a.modelAnomalyGuard}),a.hooks&&(n.hooks=Ojs(l,a.hooks)),a.ui&&(n.ui={...n.ui,...a.ui})}return n}function Djs(e,t){let n={...e??{}};for(let[o,s]of Object.entries(t))n[o]={...n[o]??{},...s};return n}function Ojs(e,t){let n={...e?.events};if(t.enabled!==!1)for(let[o,s]of Object.entries(t.events??{}))s&&(n[o]=[...n[o]??[],...s]);return{...e,...t,enabled:e?.enabled===!0||t.enabled===!0,events:n}}function rHr(e){return eyr[e]}function fG(e,t){return{config:e,scope:t,priority:rHr(t)}}var lun=Y(()=>{"use strict";nr();r(_at,"mergeConfigs");r(Djs,"mergePluginOptions");r(Ojs,"mergeHooksConfig");r(rHr,"getScopePriority");r(fG,"createPrioritizedConfig")});function wOe(e,t){let n=e.timeoutMs??(e.type==="command"&&e.timeout!==void 0?e.timeout*1e3:t);return Math.max(1,Math.round(n))}function uun(e){return Math.max(1,Math.round(e))}function vat(e){let t=!1,n=Mjs,o=Njs;for(let s of e)s&&(s.enabled===!0&&(t=!0),s.timeoutMs!==void 0&&(n=s.timeoutMs),s.maxOutputBytes!==void 0&&(o=s.maxOutputBytes));return{enabled:t,timeoutMs:Math.max(1,Math.round(n)),maxOutputBytes:uun(o)}}function sHr(e){let t=e.sourceEnabled!==!1,n=e.declarationEnabled!==!1;return{sourceRootEnabled:t,declarationEnabled:n,runtimeHooksEnabled:e.runtimeHooksEnabled,configuredEnabled:t&&n&&e.runtimeHooksEnabled}}function aHr(e){return e.flatMap(t=>[(0,Db.join)(t,"zcode.json"),(0,Db.join)(t,".zcode","config.json")])}function cHr(e){let t=new Set,n=[];for(let o of e){let s=(0,Db.resolve)(o.path);t.has(s)||(t.add(s),n.push(o))}return n}function lHr(e){let t=(0,Db.resolve)(e.workingDirectory),n=aHr($js(t)).filter(o=>(0,V0e.existsSync)(o)).map(o=>({path:o,explicitProjectConfig:!1}));if(e.explicitProjectConfigPath){let o=(0,Db.resolve)(e.explicitProjectConfigPath);(0,V0e.existsSync)(o)&&n.push({path:o,explicitProjectConfig:!0})}return cHr(n)}function dun(e){let t=(0,Db.resolve)(e.path),n=e.explicitProjectConfig===!0,o=(0,Db.dirname)(t);return{canonicalPath:t,baseDir:(0,Db.basename)(o)===".zcode"?(0,Db.dirname)(o):o,discoveryOrder:e.discoveryOrder,configFileKind:n?"explicit":(0,Db.basename)(t)==="zcode.json"?"zcode.json":".zcode/config.json",explicitProjectConfig:n,editable:!n&&t===(0,Db.resolve)(e.workingDirectory,".zcode","config.json"),hooks:e.hooks}}async function bat(e){let t=await jjs(e),n=[],o=[];for(let[s,a]of t.entries())try{let l=JSON.parse(await(0,H0e.readFile)(a.path,"utf8"));if(!Wjs(l)||l.hooks===void 0)continue;n.push(dun({path:a.path,workingDirectory:e.workingDirectory,hooks:pre.parse(l.hooks),discoveryOrder:s,explicitProjectConfig:a.explicitProjectConfig}))}catch(l){o.push({path:a.path,error:l})}return{sources:n,errors:o}}async function jjs(e){let t=(0,Db.resolve)(e.workingDirectory),n=aHr(await Bjs(t)),o=[];for(let s of n)await oHr(s)&&o.push({path:s,explicitProjectConfig:!1});if(e.explicitProjectConfigPath){let s=(0,Db.resolve)(e.explicitProjectConfigPath);await oHr(s)&&o.push({path:s,explicitProjectConfig:!0})}return cHr(o)}async function Bjs(e){let t=[],n=e;for(;;){if(t.push(n),await Ujs(n))return t.reverse();let o=(0,Db.dirname)(n);if(o===n)break;n=o}return[e]}async function Ujs(e){try{let t=await(0,H0e.stat)((0,Db.join)(e,".git"));return t.isDirectory()||t.isFile()}catch(t){return zjs(t,"ENOENT"),!1}}async function oHr(e){try{return await(0,H0e.access)(e),!0}catch{return!1}}function zjs(e,t){return e instanceof Error&&"code"in e&&e.code===t}function $js(e){let t=[],n=e;for(;;){if(t.push(n),qjs(n))return t.reverse();let o=(0,Db.dirname)(n);if(o===n)break;n=o}return[e]}function qjs(e){let t=(0,Db.join)(e,".git");try{if(!(0,V0e.existsSync)(t))return!1;let n=(0,V0e.statSync)(t);return n.isDirectory()||n.isFile()}catch{return!1}}function Wjs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var V0e,H0e,Db,yat,Mjs,Njs,iHr,SOe,Ljs,Fjs,dre,pre,Sat=Y(()=>{V0e=require("node:fs"),H0e=require("node:fs/promises"),Db=require("node:path");Fa();yat=1,Mjs=6e4,Njs=32768,iHr=["SessionStart","UserPromptSubmit","PreToolUse","PermissionRequest","PostToolUse","PostToolUseFailure","Stop"],SOe=m.number().finite().positive(),Ljs=m.object({type:m.literal("process"),command:m.string().min(1),enabled:m.boolean().optional(),args:m.array(m.string()).optional(),timeoutMs:SOe.optional(),statusMessage:m.string().min(1).optional()}).passthrough(),Fjs=m.object({type:m.literal("command"),command:m.string().min(1),enabled:m.boolean().optional(),async:m.boolean().optional(),shell:m.union([m.literal(!0),m.string().min(1)]).optional(),timeout:SOe.optional(),timeoutMs:SOe.optional(),statusMessage:m.string().min(1).optional()}).passthrough(),dre=m.object({matcher:m.string().min(1).optional(),hooks:m.array(m.discriminatedUnion("type",[Ljs,Fjs])).min(1)}).strict(),pre=m.object({enabled:m.boolean().optional(),timeoutMs:SOe.optional(),maxOutputBytes:SOe.optional(),events:m.object({SessionStart:m.array(dre).optional(),UserPromptSubmit:m.array(dre).optional(),PreToolUse:m.array(dre).optional(),PermissionRequest:m.array(dre).optional(),PostToolUse:m.array(dre).optional(),PostToolUseFailure:m.array(dre).optional(),Stop:m.array(dre).optional()}).strict().optional()}).strict();r(wOe,"resolveWorkspaceHookTimeoutMs");r(uun,"resolveWorkspaceHookMaxOutputBytes");r(vat,"resolveWorkspaceHookRuntimeRoot");r(sHr,"resolveWorkspaceHookConfiguredGates");r(aHr,"buildWorkspaceHookCandidatePaths");r(cHr,"deduplicateWorkspaceHookConfigRefs");r(lHr,"discoverWorkspaceHookConfigPaths");r(dun,"createWorkspaceHookSourceInput");r(bat,"readWorkspaceHookProjectSources");r(jjs,"discoverWorkspaceHookConfigPathsAsync");r(Bjs,"getProjectConfigDirectoriesAsync");r(Ujs,"hasWorktreeMarkerAsync");r(oHr,"pathExists");r(zjs,"isNodeError");r($js,"getProjectConfigDirectories");r(qjs,"hasWorktreeMarker");r(Wjs,"isRecord")});function Vjs(e){let t=[];for(let[n,o]of e.sources.entries()){let s=dHr(e.workspacePath,o.canonicalPath);for(let a of iHr)for(let[l,u]of(o.hooks.events?.[a]??[]).entries())for(let[f,g]of u.hooks.entries()){let _=sHr({sourceEnabled:o.hooks.enabled,declarationEnabled:g.enabled,runtimeHooksEnabled:e.runtimeRoot.enabled}),b=wOe(g,e.runtimeRoot.timeoutMs),w={reviewItemId:`workspace-hook-${n}-${a}-${l}-${f}`,event:a,matcherIndex:l,hookIndex:f,sourceFileIndex:n,sourceRelativePath:s,matcher:u.matcher??null,command:g.command,resolvedTimeoutMs:b,resolvedMaxOutputBytes:e.runtimeRoot.maxOutputBytes,...g.statusMessage?{statusMessage:g.statusMessage}:{},..._,editable:o.editable,declarationDigestAlgorithm:"sha256",hookDeclarationDigest:fun({sourceRelativePath:s,sourceDiscoveryOrder:o.discoveryOrder,event:a,matcher:u.matcher??null,matcherIndex:l,hookIndex:f,hook:g,defaultTimeoutMs:e.runtimeRoot.timeoutMs,resolvedMaxOutputBytes:e.runtimeRoot.maxOutputBytes})};t.push(g.type==="process"?{...w,type:"process",...g.args&&g.args.length>0?{args:[...g.args]}:{}}:{...w,type:"command",...g.async===!0?{async:!0}:{},...g.shell!==void 0?{shell:g.shell}:{}})}}return t}function G0e(e){let t=Vjs(e);if(t.length===0)return;let n=e.sources.map(s=>({canonicalPath:s.canonicalPath,baseDir:s.baseDir,discoveryOrder:s.discoveryOrder,configFileKind:s.configFileKind,explicitProjectConfig:s.explicitProjectConfig,editable:s.editable,hooksRoot:{...s.hooks.enabled!==void 0?{enabled:s.hooks.enabled}:{},...s.hooks.timeoutMs!==void 0?{timeoutMs:s.hooks.timeoutMs}:{},...s.hooks.maxOutputBytes!==void 0?{maxOutputBytes:s.hooks.maxOutputBytes}:{}}})),o=["workspace-hook-bundle",yat,e.sources.map(s=>[dHr(e.workspacePath,s.canonicalPath),s.discoveryOrder,s.configFileKind,s.explicitProjectConfig,pun(s.hooks.enabled),pun(s.hooks.timeoutMs),pun(s.hooks.maxOutputBytes)]),t.map(s=>[s.hookDeclarationDigest,s.sourceRootEnabled,s.declarationEnabled,s.runtimeHooksEnabled,s.configuredEnabled])];return fHr({schemaVersion:yat,workspaceIdentity:e.workspaceIdentity,discoveredAt:e.discoveredAt??new Date().toISOString(),sourceFiles:n,hooks:t,digestAlgorithm:"sha256",bundleDigest:pHr(o)})}function fun(e){return pHr(Hjs({...e,resolvedTimeoutMs:wOe(e.hook,e.defaultTimeoutMs)}))}function Hjs(e){let t=e.hook.type==="process"?["process",e.hook.command,[...e.hook.args??[]]]:["command",e.hook.command,e.hook.async===!0,e.hook.shell===void 0?["unset"]:e.hook.shell===!0?["true"]:["string",e.hook.shell]];return["workspace-hook-declaration",yat,e.sourceRelativePath,e.sourceDiscoveryOrder,e.event,e.matcher,e.matcherIndex,e.hookIndex,t,e.resolvedTimeoutMs,e.resolvedMaxOutputBytes]}function dHr(e,t){return(0,fre.relative)((0,fre.resolve)(e),(0,fre.resolve)(t)).replaceAll("\\","/")||(0,fre.basename)(t)}function pun(e){return e===void 0?["unset"]:["set",e]}function pHr(e){return(0,uHr.createHash)("sha256").update(JSON.stringify(e)).digest("hex")}function fHr(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))fHr(t)}return e}var uHr,fre,mun=Y(()=>{uHr=require("node:crypto"),fre=require("node:path");Sat();r(Vjs,"resolveWorkspaceHookEntries");r(G0e,"buildWorkspaceHookBundleSnapshot");r(fun,"createWorkspaceHookDeclarationDigest");r(Hjs,"canonicalDeclarationPayload");r(dHr,"normalizeRelativeSourcePath");r(pun,"canonicalOptional");r(pHr,"sha256");r(fHr,"deepFreeze")});var mre=Y(()=>{Sat();mun()});function mHr(e,t){let n=(0,zF.resolve)(e??process.cwd()),o=lHr({workingDirectory:n,...t?{explicitProjectConfigPath:t}:{}}).map((s,a)=>hun(s.path,{discoveryOrder:a,explicitProjectConfig:s.explicitProjectConfig,workingDirectory:n}));return wat(o)}function hun(e,t={}){let n=_Oe(e),o=Jjs(n.path),s=[...n.diagnostics],a=n.loaded?n.config.hooks:void 0;return a&&s.push({code:"config_project_hooks_pending_trust",filePath:n.path,message:"Project hooks are pending workspace trust and remain blocked",path:"hooks",severity:"warning"}),{baseDir:o,config:n.loaded?Kjs(n.config,o):{},diagnostics:s,...a?{hookCandidate:dun({path:n.path,workingDirectory:(0,zF.resolve)(t.workingDirectory??o),hooks:pre.parse(a),discoveryOrder:t.discoveryOrder??0,explicitProjectConfig:t.explicitProjectConfig})}:{},loaded:n.loaded,path:n.path}}function wat(e){let t=e.filter(o=>o.loaded),n=new Set;for(let o of t)for(let s of Object.keys(o.config.mcp?.servers??{}))n.add(s);return{diagnostics:e.flatMap(o=>o.diagnostics),files:t,hookCandidates:t.flatMap(o=>o.hookCandidate?[o.hookCandidate]:[]),loaded:t.length>0,paths:t.map(o=>o.path),mcpServerNames:[...n]}}function Jjs(e){let t=(0,zF.dirname)(e);return(0,zF.basename)(t)===".zcode"?(0,zF.dirname)(t):t}function Kjs(e,t){let n=e.hooks?(()=>{let{hooks:o,...s}=e;return s})():{...e};return n.mcp?.servers?{...n,mcp:{...n.mcp,servers:Object.fromEntries(Object.entries(n.mcp.servers).map(([o,s])=>[o,Zjs(s,t)]))}}:n}function Zjs(e,t){if(e.type!=="stdio")return e;let n=e.cwd??Gjs;return{...e,cwd:(0,zF.isAbsolute)(n)?n:(0,zF.resolve)(t,n)}}var zF,Gjs,hHr=Y(()=>{"use strict";zF=require("node:path");mre();gat();Gjs=".";r(mHr,"loadProjectConfigs");r(hun,"loadProjectConfigFile");r(wat,"summarizeProjectConfigs");r(Jjs,"getProjectConfigBaseDir");r(Kjs,"normalizeProjectConfig");r(Zjs,"normalizeProjectMcpServer")});function K0(e={}){let t=[fG(Lm,Ek.System)],n=e.skipUserConfig?{config:{},diagnostics:[],path:U7(),loaded:!1}:_Oe(e.userConfigPath);n.loaded&&t.push(fG(gun(n.config,{kind:"user",path:n.path}),Ek.User));let o=e.workingDirectory?mHr(e.workingDirectory,e.projectConfigPath):e.projectConfigPath?wat([hun(e.projectConfigPath,{discoveryOrder:0,explicitProjectConfig:!0})]):wat([]),s=o.files,a=o,l=o.diagnostics;Qjs({env:e.env,loggerFactory:e.loggerFactory,projectDiagnostics:l,userDiagnostics:n.diagnostics});let u=n3s(s),f=[...s].reverse().find(B=>B.config.ui?.locale!==void 0)?.path,g=[...s].reverse().find(B=>B.config.ui?.theme!==void 0)?.path;for(let B of s)t.push(fG(B.config,Ek.Project));let _=aun(e.env??process.env);Object.keys(_).length>0&&t.push(fG(gun(_,{kind:"internal"}),Ek.Env)),e.cliOverrides&&t.push(fG(gun(e.cliOverrides,{kind:"internal"}),Ek.Cli));let b=vat([Lm.hooks,n.config.hooks,...a.hookCandidates.map(B=>B.hooks),_.hooks,e.cliOverrides?.hooks]),w=(0,gHr.resolve)(e.workingDirectory??process.cwd()),T=G0e({workspaceIdentity:e.workspaceIdentity?.trim()||w,workspacePath:w,sources:a.hookCandidates,runtimeRoot:b}),I=T?Ffe(T):void 0,E=_at(...t),R=Yjs({projectConfig:u.config,projectPath:u.path,userConfig:n.config,userPath:n.path}),L=Xjs({cliOverrides:e.cliOverrides,envConfig:_,projectConfig:u.config,userConfig:n.config});E.mcp={...E.mcp,servers:L.servers};let U=yHr(E);return{configPort:U,config:U.getAll(),sources:{user:{diagnostics:n.diagnostics,path:n.path,loaded:n.loaded,hasMcpServers:n.config.mcp?.servers!==void 0,hasUiLocale:n.config.ui?.locale!==void 0,hasUiTheme:n.config.ui?.theme!==void 0,mcpServerNames:Object.keys(n.config.mcp?.servers??{})},project:{diagnostics:l,path:u.path,paths:a.paths,loaded:u.loaded,hasUiLocale:u.config.ui?.locale!==void 0,hasUiTheme:u.config.ui?.theme!==void 0,hasMcpServers:u.config.mcp?.servers!==void 0,mcpServerNames:a.mcpServerNames,uiLocalePath:f,uiThemePath:g,...I?{workspaceHookSnapshot:I}:{},workspaceHookRuntimeRoot:b},plugins:R,mcp:{serverSources:L.sources},env:Object.keys(_).length>0,cli:!!e.cliOverrides}}}function Yjs(e){let t={},n={},o={};for(let s of Object.keys(e.userConfig.plugins?.enabledPlugins??{}))t[s]="user";for(let s of Object.keys(e.projectConfig.plugins?.enabledPlugins??{}))t[s]="workspace";for(let s of Object.keys(e.userConfig.plugins?.extraKnownMarketplaces??{}))n[s]="user";for(let[s,a]of Object.entries(e.userConfig.plugins?.options??{})){o[s]={};for(let l of Object.keys(a))o[s][l]="user"}for(let[s,a]of Object.entries(e.projectConfig.plugins?.options??{})){let l=o[s]??={};for(let u of Object.keys(a))l[u]="workspace"}return{dirs:{user:e.userConfig.plugins?.dirs??[],workspace:e.projectConfig.plugins?.dirs??[]},enabled:t,marketplaces:n,options:o,paths:{user:e.userPath,workspace:e.projectPath}}}function gun(e,t){return e.hooks?.events?{...e,hooks:{...e.hooks,events:Object.fromEntries(Object.entries(e.hooks.events).map(([n,o])=>[n,o?.map(s=>({...s,hooks:s.hooks.map(a=>({...a,source:a.source??t}))}))]))}}:e}function Xjs(e){let t={},n={},o=r((s,a)=>{for(let[l,u]of Object.entries(a?.mcp?.servers??{}))t[l]=u,n[l]=s},"apply");return o("system",Lm),o("project",e.projectConfig),o("user",e.userConfig),o("env",e.envConfig),o("cli",e.cliOverrides),{servers:t,sources:n}}function Qjs(e){let t=[...e.userDiagnostics.map(s=>({...s,configScope:"user"})),...e.projectDiagnostics.map(s=>({...s,configScope:"project"}))];if(t.length===0)return;let o=(e.loggerFactory??rB({env:e.env})).createLogger("zcode").child({module:"adapters.config"});for(let s of t)o.warn(e3s(s.code),{configPath:s.filePath,configScope:s.configScope,diagnosticCode:s.code,diagnosticMessage:s.message,diagnosticPath:s.path,event:t3s(s.code),severity:s.severity})}function e3s(e){return e==="config_mcp_server_invalid"?"MCP server config skipped":e==="config_project_hooks_pending_trust"?"Project hooks pending workspace trust":"Config file failed to load"}function t3s(e){return e==="config_mcp_server_invalid"?"config.mcp_server.skipped":e==="config_project_hooks_pending_trust"?"config.project_hooks.pending_trust":"config.file.invalid"}function n3s(e){if(e.length===0)return{config:{},diagnostics:[],path:void 0,loaded:!1};let t=e[e.length-1]?.path;return{config:_at(...e.map(o=>fG(o.config,Ek.Project))),diagnostics:e.flatMap(o=>o.diagnostics),path:t,loaded:!0}}var gHr,_Hr=Y(()=>{"use strict";gHr=require("node:path");nr();mre();vw();gat();cun();lun();W0e();hHr();r(K0,"createConfig");r(Yjs,"resolvePluginConfigSources");r(gun,"withHookConfigSource");r(Xjs,"resolveEffectiveMcpServers");r(Qjs,"logConfigDiagnostics");r(e3s,"resolveConfigDiagnosticLogMessage");r(t3s,"resolveConfigDiagnosticLogEvent");r(n3s,"summarizeOptionalProjectConfig")});function vHr(e){let t=Lm;switch(e){case fs.ModelStreamIdleTimeout:return t.modelStream.idleTimeoutMs;case fs.PermissionMode:return t.permission.mode;case fs.PermissionAllowedTools:return t.permission.allowedTools;case fs.PermissionDisallowedTools:return t.permission.disallowedTools;case fs.PermissionAutoApproveHighRisk:return t.permission.autoApproveHighRisk;case fs.PermissionAllowMediumRiskInAuto:return t.permission.allowMediumRiskInAuto;case fs.StorageDir:return t.storage.dir;case fs.StorageSessionDbPath:return t.storage.sessionDbPath;case fs.HttpProxy:return t.network.httpProxy;case fs.NoProxy:return t.network.noProxy;case fs.CaCertFile:return t.network.caCertFile;case fs.HttpTimeout:return t.network.timeout;case fs.FeatureCompact:return t.features.compact;case fs.FeatureRewind:return t.features.rewind;case fs.FeatureSubagent:return t.features.subagent;case fs.FeatureMemory:return t.features.memory;case fs.FeatureSkill:return t.features.skill;case fs.FeatureMcp:return t.features.mcp;case fs.MemoryUse:return t.memory.use;case fs.McpServers:return t.mcp.servers;case fs.PluginsEnabled:return t.plugins.enabled;case fs.PluginsDirs:return t.plugins.dirs;case fs.PluginsEnabledPlugins:return t.plugins.enabledPlugins;case fs.PluginsExtraKnownMarketplaces:return t.plugins.extraKnownMarketplaces;case fs.PluginsOptions:return t.plugins.options;case fs.PluginsSuppressedBuiltins:return t.plugins.suppressedBuiltins;case fs.SkillsEnabled:return t.skills.enabled;case fs.SkillsIncludeInstructions:return t.skills.includeInstructions;case fs.SkillsMetadataBudget:return t.skills.metadataBudget;case fs.SkillsRoots:return t.skills.roots;case fs.LogLevel:return t.logging.level;case fs.LogFormat:return t.logging.format;case fs.ToolConcurrencyMax:return t.toolConcurrency.maxConcurrency;case fs.ModelAnomalyGuard:return t.modelAnomalyGuard;case fs.Hooks:return t.hooks;case fs.UiLocale:return t.ui.locale;case fs.UiTheme:return t.ui.theme;default:return}}function r3s(e){return vHr(e)!==void 0}function yHr(e){return new yun(e)}var _un,yun,vw=Y(()=>{"use strict";nr();gat();cun();tun();lun();_Hr();_un=class{static{r(this,"ConfigStore")}store=new Map;observers=new Map;allHandlers=new Set;constructor(t){t&&this.merge(t,Ek.System)}get(t){return this.store.get(t)?.value}has(t){return this.store.has(t)}set(t,n,o,s){let a=this.get(t),l={value:n,sources:[{scope:o,key:t,value:n,path:s}]};this.store.set(t,l);let u=this.observers.get(t);u&&u.forEach(f=>f(n,a)),this.allHandlers.forEach(f=>f(t,n,a))}getSources(t){return this.store.get(t)?.sources??[]}merge(t,n){if(t.modelStream?.idleTimeoutMs!==void 0&&this.set(fs.ModelStreamIdleTimeout,t.modelStream.idleTimeoutMs,n),t.permission&&(t.permission.mode&&this.set(fs.PermissionMode,t.permission.mode,n),t.permission.allowedTools&&this.set(fs.PermissionAllowedTools,t.permission.allowedTools,n),t.permission.disallowedTools&&this.set(fs.PermissionDisallowedTools,t.permission.disallowedTools,n),t.permission.autoApproveHighRisk!==void 0&&this.set(fs.PermissionAutoApproveHighRisk,t.permission.autoApproveHighRisk,n),t.permission.allowMediumRiskInAuto!==void 0&&this.set(fs.PermissionAllowMediumRiskInAuto,t.permission.allowMediumRiskInAuto,n)),t.storage&&(t.storage.dir&&this.set(fs.StorageDir,t.storage.dir,n),t.storage.sessionDbPath&&this.set(fs.StorageSessionDbPath,t.storage.sessionDbPath,n)),t.network&&(t.network.httpProxy!==void 0&&this.set(fs.HttpProxy,t.network.httpProxy,n),t.network.noProxy!==void 0&&this.set(fs.NoProxy,t.network.noProxy,n),t.network.caCertFile!==void 0&&this.set(fs.CaCertFile,t.network.caCertFile,n),t.network.timeout!==void 0&&this.set(fs.HttpTimeout,t.network.timeout,n)),t.features&&(t.features.compact!==void 0&&this.set(fs.FeatureCompact,t.features.compact,n),t.features.rewind!==void 0&&this.set(fs.FeatureRewind,t.features.rewind,n),t.features.subagent!==void 0&&this.set(fs.FeatureSubagent,t.features.subagent,n),t.features.memory!==void 0&&this.set(fs.FeatureMemory,t.features.memory,n),t.features.skill!==void 0&&this.set(fs.FeatureSkill,t.features.skill,n),t.features.mcp!==void 0&&this.set(fs.FeatureMcp,t.features.mcp,n)),t.memory&&t.memory.use!==void 0&&this.set(fs.MemoryUse,t.memory.use,n),t.mcp&&t.mcp.servers!==void 0&&this.set(fs.McpServers,t.mcp.servers,n),t.plugins&&(t.plugins.enabled!==void 0&&this.set(fs.PluginsEnabled,t.plugins.enabled,n),t.plugins.dirs!==void 0&&this.set(fs.PluginsDirs,t.plugins.dirs,n),t.plugins.enabledPlugins!==void 0&&this.set(fs.PluginsEnabledPlugins,t.plugins.enabledPlugins,n),t.plugins.extraKnownMarketplaces!==void 0&&this.set(fs.PluginsExtraKnownMarketplaces,t.plugins.extraKnownMarketplaces,n),t.plugins.options!==void 0&&this.set(fs.PluginsOptions,t.plugins.options,n),t.plugins.suppressedBuiltins!==void 0&&this.set(fs.PluginsSuppressedBuiltins,t.plugins.suppressedBuiltins,n)),t.skills&&(t.skills.enabled!==void 0&&this.set(fs.SkillsEnabled,t.skills.enabled,n),t.skills.includeInstructions!==void 0&&this.set(fs.SkillsIncludeInstructions,t.skills.includeInstructions,n),t.skills.metadataBudget!==void 0&&this.set(fs.SkillsMetadataBudget,t.skills.metadataBudget,n),t.skills.roots!==void 0&&this.set(fs.SkillsRoots,t.skills.roots,n)),t.skillOverrides!==void 0&&this.set(fs.SkillOverrides,t.skillOverrides,n),t.commandOverrides!==void 0&&this.set(fs.CommandOverrides,t.commandOverrides,n),t.logging&&(t.logging.level&&this.set(fs.LogLevel,t.logging.level,n),t.logging.format!==void 0&&this.set(fs.LogFormat,t.logging.format,n)),t.toolConcurrency&&t.toolConcurrency.maxConcurrency!==void 0&&this.set(fs.ToolConcurrencyMax,t.toolConcurrency.maxConcurrency,n),t.modelAnomalyGuard){let o=this.get(fs.ModelAnomalyGuard)??Lm.modelAnomalyGuard;this.set(fs.ModelAnomalyGuard,{...o,...t.modelAnomalyGuard},n)}if(t.hooks){let o=this.get(fs.Hooks)??Lm.hooks;this.set(fs.Hooks,{...o,...t.hooks,events:t.hooks.events??o.events},n)}t.ui?.locale!==void 0&&this.set(fs.UiLocale,t.ui.locale,n),t.ui?.theme!==void 0&&this.set(fs.UiTheme,t.ui.theme,n)}subscribe(t,n){return this.observers.has(t)||this.observers.set(t,new Set),this.observers.get(t).add(n),()=>{this.observers.get(t)?.delete(n)}}subscribeAll(t){return this.allHandlers.add(t),()=>{this.allHandlers.delete(t)}}},yun=class{static{r(this,"ConfigPortImpl")}store;constructor(t){this.store=new _un(t??Lm)}get(t){let n=this.store.get(t);if(n!==void 0)return n;let o=vHr(t);if(o!==void 0)return o;throw new Error(`Config key not found: ${t}`)}getAll(){return{modelStream:{idleTimeoutMs:this.store.get(fs.ModelStreamIdleTimeout)??Lm.modelStream.idleTimeoutMs},permission:{mode:this.get(fs.PermissionMode),allowedTools:this.get(fs.PermissionAllowedTools),disallowedTools:this.get(fs.PermissionDisallowedTools),autoApproveHighRisk:this.get(fs.PermissionAutoApproveHighRisk),allowMediumRiskInAuto:this.get(fs.PermissionAllowMediumRiskInAuto)},storage:{dir:this.store.get(fs.StorageDir)??Lm.storage.dir,sessionDbPath:this.store.get(fs.StorageSessionDbPath)??Lm.storage.sessionDbPath},network:{httpProxy:this.store.get(fs.HttpProxy),noProxy:this.store.get(fs.NoProxy),caCertFile:this.store.get(fs.CaCertFile),timeout:this.store.get(fs.HttpTimeout)??Lm.network.timeout},features:{compact:this.store.get(fs.FeatureCompact)??!0,rewind:this.store.get(fs.FeatureRewind)??!0,subagent:this.store.get(fs.FeatureSubagent)??!0,memory:this.store.get(fs.FeatureMemory)??!0,skill:this.store.get(fs.FeatureSkill)??!0,mcp:this.store.get(fs.FeatureMcp)??!0},memory:{use:this.store.get(fs.MemoryUse)??Lm.memory.use},mcp:{servers:this.store.get(fs.McpServers)??Lm.mcp.servers},plugins:{dirs:this.store.get(fs.PluginsDirs)??Lm.plugins.dirs,enabled:this.store.get(fs.PluginsEnabled)??Lm.plugins.enabled,enabledPlugins:this.store.get(fs.PluginsEnabledPlugins)??Lm.plugins.enabledPlugins,extraKnownMarketplaces:this.store.get(fs.PluginsExtraKnownMarketplaces)??Lm.plugins.extraKnownMarketplaces,options:this.store.get(fs.PluginsOptions)??Lm.plugins.options,suppressedBuiltins:this.store.get(fs.PluginsSuppressedBuiltins)??Lm.plugins.suppressedBuiltins},skills:{enabled:this.store.get(fs.SkillsEnabled)??!0,includeInstructions:this.store.get(fs.SkillsIncludeInstructions)??!0,metadataBudget:this.store.get(fs.SkillsMetadataBudget)??Lm.skills.metadataBudget,roots:this.store.get(fs.SkillsRoots)??Lm.skills.roots},skillOverrides:this.store.get(fs.SkillOverrides)??Lm.skillOverrides,commandOverrides:this.store.get(fs.CommandOverrides)??Lm.commandOverrides,logging:{level:this.store.get(fs.LogLevel)??"info",format:this.store.get(fs.LogFormat)??Lm.logging.format},toolConcurrency:{maxConcurrency:this.store.get(fs.ToolConcurrencyMax)??Lm.toolConcurrency.maxConcurrency},modelAnomalyGuard:this.store.get(fs.ModelAnomalyGuard)??Lm.modelAnomalyGuard,hooks:this.store.get(fs.Hooks)??Lm.hooks,ui:{locale:this.store.get(fs.UiLocale)??Lm.ui.locale,theme:this.store.get(fs.UiTheme)??Lm.ui.theme}}}has(t){return this.store.has(t)||r3s(t)}set(t,n){this.store.set(t,n,Ek.Session)}observe(){return{subscribe:r((t,n)=>this.store.subscribe(t,n),"subscribe"),subscribeAll:r(t=>this.store.subscribeAll(t),"subscribeAll")}}getSources(t){return this.store.getSources(t)}merge(t,n){this.store.merge(t,n)}};r(vHr,"getDefaultValue");r(r3s,"hasDefaultValue");r(yHr,"createConfigPort")});async function xHr(e,t={}){let n=(0,TC.resolve)(e),o=[],s=t.includeZcodeSkills??!0,a=t.homeDirectory??(0,bun.homedir)(),l=0,u=r(()=>(l+=i3s,l),"nextPriority");for(let g of t.extraRoots??[])o.push(vun(d3s(g,n),"project","zcode",u()));s&&o.push(...wHr(a,"user",u));let f=await c3s(n);for(let g of f)s&&o.push(...wHr(g,"project",u));return o.push(...t.extraResolvedRoots??[]),o}async function c3s(e){let t=await l3s(e);if(!t)return[e];let n=[],o=e;for(;n.push(o),!(o===t||o===(0,TC.dirname)(o));)o=(0,TC.dirname)(o);return n}async function l3s(e){let t=e;for(;;){if(await u3s((0,TC.join)(t,o3s)))return t;let n=(0,TC.dirname)(t);if(n===t)return null;t=n}}async function u3s(e){try{return await(0,kHr.stat)(e),!0}catch{return!1}}function wHr(e,t,n){return[vun((0,TC.join)(e,s3s,SHr),t,"zcode",n()),vun((0,TC.join)(e,a3s,SHr),t,"agents",n())]}function vun(e,t,n,o){return{path:(0,TC.resolve)(e),scope:t,source:n,priority:o}}function d3s(e,t){let n=e.startsWith(bHr)?(0,TC.join)((0,bun.homedir)(),e.slice(bHr.length)):e;return(0,TC.isAbsolute)(n)?n:(0,TC.resolve)(t,n)}var kHr,bun,TC,o3s,bHr,i3s,SHr,s3s,a3s,THr=Y(()=>{"use strict";kHr=require("node:fs/promises"),bun=require("node:os"),TC=require("node:path"),o3s=".git",bHr="~/",i3s=10,SHr="skills",s3s=".zcode",a3s=".agents";r(xHr,"resolveDefaultSkillRoots");r(c3s,"resolveProjectSkillDirectories");r(l3s,"findWorktreeRoot");r(u3s,"pathExists");r(wHr,"skillRootsForBase");r(vun,"root");r(d3s,"resolveConfiguredRoot")});async function EHr(e,t={}){let n=t.followSymbolicLinks??!0;if(!n&&await AHr(e))return[];if(!(await(0,hre.stat)(e).catch(u=>(Sun(u),null)))?.isDirectory())return[];let s=[],a=(0,kOe.join)(e,ffe);await IHr(a,n)&&s.push(a);let l=await(0,hre.readdir)(e,{withFileTypes:!0});for(let u of l){if(!(u.isDirectory()||n&&u.isSymbolicLink())||!EXe(u.name))continue;let g=(0,kOe.join)(e,u.name,ffe);await IHr(g,n)&&s.push(g)}return s}function xOe(e,t={}){let n=t.followSymbolicLinks??!0;if(!n&&PHr(e))return[];if(!RHr(e)?.isDirectory())return[];let s=[],a=(0,kOe.join)(e,ffe);CHr(a,n)&&s.push(a);for(let l of(0,J0e.readdirSync)(e,{withFileTypes:!0})){if(!(l.isDirectory()||n&&l.isSymbolicLink())||!EXe(l.name))continue;let f=(0,kOe.join)(e,l.name,ffe);CHr(f,n)&&s.push(f)}return s}async function IHr(e,t){return!t&&await AHr(e)?!1:(await(0,hre.stat)(e).catch(o=>(Sun(o),null)))?.isFile()??!1}function CHr(e,t){return!t&&PHr(e)?!1:RHr(e)?.isFile()??!1}async function AHr(e){try{return(await(0,hre.lstat)(e)).isSymbolicLink()}catch{return!1}}function PHr(e){try{return(0,J0e.lstatSync)(e).isSymbolicLink()}catch{return!1}}function RHr(e){try{return(0,J0e.statSync)(e)}catch(t){return Sun(t),null}}function Sun(e){if(!(typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"))throw e}var J0e,hre,kOe,kat=Y(()=>{"use strict";J0e=require("node:fs"),hre=require("node:fs/promises"),kOe=require("node:path");ms();r(EHr,"scanSkillFilesUnderRoot");r(xOe,"scanSkillFilesUnderRootSync");r(IHr,"isLoadableSkillFile");r(CHr,"isLoadableSkillFileSync");r(AHr,"isSymbolicLink");r(PHr,"isSymbolicLinkSync");r(RHr,"statSyncOrNull");r(Sun,"throwIfUnexpectedScanError")});function mG(e={}){return new kun(e)}function _3s(e){let t=e.replace(/^\uFEFF/,"");if(!t.startsWith("---"))return null;let n=t.split(/\r?\n/);if(n[0]?.trim()!=="---")return null;let o=n.findIndex((s,a)=>a>0&&s.trim()==="---");return o<=0?null:n.slice(1,o).join(`
|
|
2117
2117
|
`)}function y3s(e){let t=e.replace(/^\uFEFF/,"");if(!t.startsWith("---"))return e;let n=t.split(/\r?\n/),o=n.findIndex((s,a)=>a>0&&s.trim()==="---");return o<=0?e:n.slice(o+1).join(`
|
|
2118
2118
|
`)}function v3s(e,t,n){let o={},s=[],a=e.split(/\r?\n/);for(let l=0;l<a.length;l+=1){let u=a[l]??"";if(u.trim().length===0||u.trim().startsWith("#")||/^\s/.test(u))continue;let f=u.indexOf(":");if(f<=0){n.push({code:"skill_invalid_frontmatter",severity:"warning",message:`Invalid frontmatter line ${l+1} in ${(0,IC.basename)(t)}`,path:t});continue}let g=u.slice(0,f).trim(),_=u.slice(f+1).trim();s.push(g);let b=b3s(_);if(b){let w=S3s(a,l+1,b);o[g]=w.value,l=w.nextIndex-1}else o[g]=_}return{values:o,keys:s}}function b3s(e){return/^>[+-]?$/.test(e)?"folded":/^\|[+-]?$/.test(e)?"literal":null}function S3s(e,t,n){let o=[],s=t;for(;s<e.length;){let u=e[s]??"";if(u.trim().length>0&&!/^\s/.test(u))break;o.push(u),s+=1}let a=o.reduce((u,f)=>{if(f.trim().length===0)return u;let g=w3s(f);return u===null?g:Math.min(u,g)},null),l=o.map(u=>u.trim().length===0?"":u.slice(a??0));return{value:n==="folded"?k3s(l):l.join(`
|
|
@@ -2133,7 +2133,7 @@ ${Array.from(n,([s,a])=>`${s}: ${a}`).join(`
|
|
|
2133
2133
|
---
|
|
2134
2134
|
|
|
2135
2135
|
${o}`}function g7s(e){let t=e.replace(/^\uFEFF/,"");if(!t.startsWith("---"))return e;let n=t.split(/\r?\n/);if(n[0]?.trim()!=="---")return e;let o=n.findIndex((s,a)=>a>0&&s.trim()==="---");return o>0?n.slice(o+1).join(`
|
|
2136
|
-
`):e}function _7s(e,t,n){let o=_Gr(e);if(o!==void 0){for(let a of o)Eat(n);return o}let s=(0,Bk.join)(e,"cache",Yp);try{let a=[];for(let l of(0,WF.readdirSync)(s,{withFileTypes:!0})){if(Eat(n),!l.isDirectory())continue;let u=(0,Bk.join)(s,l.name);for(let f of(0,WF.readdirSync)(u,{withFileTypes:!0}))f.isDirectory()&&a.push((0,Bk.join)(u,f.name))}return a}catch(a){return Cat(a)?[]:(t.push({code:"plugin_root_not_found",message:a instanceof Error?a.message:`Failed to scan ${s}`,path:s,severity:"warning"}),[])}}function y7s(e,t){if(!$v(e.rootPath))return t.push({code:"plugin_root_not_found",message:`Plugin root does not exist: ${e.rootPath}`,path:e.rootPath,severity:"warning"}),null;let n=v7s(e.rootPath);if(!n)return t.push({code:"plugin_manifest_not_found",message:`Plugin manifest not found: ${e.rootPath}`,path:e.rootPath,severity:"error"}),null;let o=b7s(n,t);return o?{id:`${o.name}@${e.marketplace}`,manifest:o,manifestPath:n,marketplace:e.marketplace,rootPath:e.rootPath,source:e.source}:null}function v7s(e){let t=(0,Bk.join)(e,qzs);if(bw(t))return t;let n=(0,Bk.join)(e,Wzs);if(bw(n))return n;let o=(0,Bk.join)(e,Vzs);return bw(o)?o:null}function b7s(e,t){try{let n=JSON.parse((0,WF.readFileSync)(e,"utf8"));if(!fu(n))throw new Error("Manifest must be a JSON object");let o=typeof n.name=="string"?n.name.trim():"";if(!Kzs.test(o))throw new Error(`Invalid plugin name: ${o}`);return{...n,name:o,version:typeof n.version=="string"?n.version:Hzs}}catch(n){return t.push({code:"plugin_manifest_invalid",message:n instanceof Error?n.message:`Invalid plugin manifest: ${e}`,path:e,severity:"error"}),null}}function S7s(){return{commandRoots:[],diagnostics:[],hooks:{},mcpServers:{},plugins:[],skillRoots:[]}}function w7s(e=[]){return{commandRoots:[],hooks:{},hookDetails:e,mcpServers:{},skillCount:0,skillRoots:[]}}function k7s(e,t,n){return e.enabledPlugins[t]??n}var WF,Bk,qzs,Wzs,Vzs,Hzs,Gzs,Jzs,Kzs,Zzs,Yzs,Kdn,GOe=Y(()=>{"use strict";WF=require("node:fs"),Bk=require("node:path");nr();q7();kat();Rat();Dun();Mun();Edn();Mat();Edn();Mat();sdn();EZr();qzs=(0,Bk.join)(".zcode-plugin","plugin.json"),Wzs=(0,Bk.join)(".claude-plugin","plugin.json"),Vzs=(0,Bk.join)(".codex-plugin","plugin.json"),Hzs="0.0.0",Gzs=1e3,Jzs=10,Kzs=/^[a-z0-9][a-z0-9._-]{0,127}$/,Zzs=["channels","lspServers","outputStyles","settings"],Yzs=new Set(Object.values(Tl)),Kdn=class{static{r(this,"NodePluginAdapter")}options;constructor(t){this.options=t}async discoverPlugins(t,n){return this.discoverPluginsSync(t,n)}discoverPluginsSync(t,n){if(!t.config.enabled)return S7s();let o=[],s=(0,Bk.join)(t.storageRoot||this.options.storageRoot,"data"),a=this.resolveCandidates(t,o,n),l=[],u={},f={},g=[],_=new Set,b=[],w=Gzs;for(let T of a){Eat(n);let I=y7s(T,o);if(!I||I.source==="official"&&t.config.suppressedBuiltins.includes(I.id))continue;if(_.has(I.id)){o.push({code:"plugin_duplicate_id",message:`Duplicate plugin ignored: ${I.id}`,path:I.rootPath,pluginId:I.id,severity:"warning"});continue}_.add(I.id),n7s(I,o);let E=T.defaultEnabled||(t.officialPluginsEnabledByDefault?.has(I.id)??!1),R=k7s(t.config,I.id,E),L=(0,Bk.join)(s,$7(I.id)),U=gre({diagnostics:o,loaded:I}),B=t7s(I),z=s7s({dataPath:L,diagnostics:o,loaded:I,runnable:B}),$=R?e7s({dataPath:L,diagnostics:o,env:t.env??{},hookEvents:B?z.events:{},hookDetails:z.details,loaded:I,mcpServerDefinitions:U,options:t.config.options[I.id]??{},priority:w,workingDirectory:t.workingDirectory}):w7s(z.details);w+=Jzs,Object.assign(f,$.mcpServers),AZr(u,$.hooks),b.push(...$.skillRoots),l.push(...$.commandRoots),g.push(Qzs(I,$,L,R,Object.keys(U),t.config.options[I.id]??{}))}return{commandRoots:l,diagnostics:o,hooks:u,mcpServers:f,plugins:g,skillRoots:b}}resolveCandidates(t,n,o){let s=[];for(let a of t.config.dirs)s.push({defaultEnabled:!0,marketplace:OZn,rootPath:(0,Bk.resolve)(a),source:"inline"});for(let a of t.officialPluginRoots??[])s.push({defaultEnabled:!1,marketplace:Yp,rootPath:(0,Bk.resolve)(a),source:"official"});s.push(..._7s(t.storageRoot,n,o).map(a=>({defaultEnabled:!1,marketplace:Yp,rootPath:a,source:"official"})));for(let a of X7(t.storageRoot))s.push({defaultEnabled:!1,marketplace:a.marketplace,rootPath:ydn(t.storageRoot,a),source:"cache"});return s}};r(Xzs,"createNodePluginAdapter");r(wct,"discoverNodePluginsSync");r(Qzs,"createPluginMetadata");r(e7s,"resolveEnabledComponents");r(t7s,"canRunPluginHooks");r(n7s,"warnUnsupportedComponents");r(r7s,"resolveSkillRoots");r(o7s,"warnEmptyDeclaredSkillRoots");r(i7s,"resolveCommandRoots");r(s7s,"inspectPluginHooks");r(a7s,"parsePluginHookEvents");r(c7s,"toPluginHookDetail");r(Zdn,"createHookPluginContext");r(l7s,"attachPluginToHook");r(AZr,"mergeHookEvents");r(u7s,"mergeHookInspection");r(PZr,"emptyHookInspection");r(d7s,"countSkillFiles");r(RZr,"resolveComponentRoots");r(p7s,"materializeCommandMetadataRoot");r(f7s,"normalizeGeneratedCommandName");r(m7s,"trimRelativePrefix");r(h7s,"applyCommandMetadataFrontmatter");r(g7s,"stripMarkdownFrontmatter");r(_7s,"scanOfficialCache");r(y7s,"loadPlugin");r(v7s,"findManifest");r(b7s,"readManifest");r(S7s,"emptyOutcome");r(w7s,"emptyComponents");r(k7s,"resolveEnabled")});function OZr(e){let t=e.appId??I7s,n=e.appSecret?.trim()??"",o=e.authorizeUrl??Hpe(process.env,x7s),s=e.tokenUrl??Hpe(process.env,T7s);return{buildAuthorizeUrl(a){let l=new URLSearchParams({appId:t,redirect:a.redirectUri,state:a.state});return`${o}?${l.toString()}`},async exchangeCode(a,l){if(!n)throw new kct("BigModel OAuth appSecret is required.");let u=await e.httpClient.request({body:new TextEncoder().encode(JSON.stringify({appId:t,appSecret:n,authCode:a.code})),headers:{"Content-Type":E7s},maxResponseBytes:64*1024,method:"POST",trace:e.trace,url:s},l),f=JSON.parse(new TextDecoder().decode(u.body)),g=f.data?.accessToken?.trim()??"";if(!g)throw new kct(f.msg??"BigModel token response is missing accessToken.");return{accessToken:g,...f.data?.refreshToken?{refreshToken:f.data.refreshToken}:{}}}}}function MZr(){return(0,DZr.randomBytes)(C7s).toString("hex")}var DZr,x7s,T7s,I7s,C7s,E7s,kct,NZr=Y(()=>{"use strict";DZr=require("node:crypto");ms();x7s="/login",T7s="/api/auth/tokenByAuthCode",I7s="zcode",C7s=32,E7s="application/json",kct=class extends Error{static{r(this,"BigmodelOAuthError")}constructor(t,n={}){super(t,n),this.name="BigmodelOAuthError"}};r(OZr,"createBigmodelOAuthClient");r(MZr,"createBigmodelOAuthState")});async function Ydn(e,t={}){let n=t.platform??process.platform,o=P7s(n,e),s=t.spawnProcess??LZr.spawn;try{let a=s(o.executable,o.args,{detached:!0,stdio:"ignore",windowsHide:!0});return await R7s(a,o.executable,t.timeoutMs)}catch(a){return{command:o.executable,opened:!1,reason:a instanceof Error?a.message:String(a)}}}function P7s(e,t){return e==="darwin"?{executable:"open",args:[t]}:e==="win32"?{executable:"cmd.exe",args:["/c","start","",t]}:{executable:"xdg-open",args:[t]}}function R7s(e,t,n=A7s){return new Promise(o=>{let s=!1,a,l=r(u=>{s||(s=!0,clearTimeout(a),e.removeAllListeners("error"),e.removeAllListeners("spawn"),u.opened&&e.unref(),o(u))},"settle");a=setTimeout(()=>{l({command:t,opened:!0})},n),e.once("spawn",()=>{l({command:t,opened:!0})}),e.once("error",u=>{l({command:t,opened:!1,reason:u.message})})})}var LZr,A7s,FZr=Y(()=>{"use strict";LZr=require("node:child_process"),A7s=1e3;r(Ydn,"openUrlInBrowser");r(P7s,"browserOpenCommand");r(R7s,"waitForBrowserSpawn")});function $Zr(e){return{async resolve(t,n){let o=t.accessToken.trim();if(!o)throw new yG("OAuth access token is required.");if(t.family==="bigmodel")return BZr({authorization:o,host:XAe(process.env),httpClient:e.httpClient,trace:e.trace},n);let s=await M7s(e,o,n);return BZr({authorization:`Bearer ${s}`,host:UZr,httpClient:e.httpClient,requireSecretKey:!0,trace:e.trace},n)}}}async function M7s(e,t,n){let o=await JOe(e.httpClient,{body:new TextEncoder().encode(JSON.stringify({token:t})),headers:{"Content-Type":zZr},method:"POST",trace:e.trace,url:`${UZr}/api/auth/z/login`},n),s=o?.access_token?.trim()??o?.accessToken?.trim()??"";if(!s)throw new yG("Z.AI biz token response is missing access_token.");return s}async function BZr(e,t){let n=await JOe(e.httpClient,{headers:xct(e.authorization),method:"GET",trace:e.trace,url:`${e.host}/api/biz/customer/getCustomerInfo`},t),o=N7s(n);if(!o)throw new yG("Unable to resolve organization and project.");let s=`${e.host}/api/biz/v1/organization/${o.organizationId}/projects/${o.projectId}/api_keys`,u=((await JOe(e.httpClient,{headers:xct(e.authorization),method:"GET",trace:e.trace,url:s},t)??[]).find(_=>_.name===jZr)??await JOe(e.httpClient,{body:new TextEncoder().encode(JSON.stringify({name:jZr})),headers:xct(e.authorization),method:"POST",trace:e.trace,url:s},t))?.apiKey?.trim()??"";if(!u)throw new yG("API key response is missing apiKey.");let g=(await JOe(e.httpClient,{headers:xct(e.authorization),method:"GET",trace:e.trace,url:`${s}/copy/${encodeURIComponent(u)}`},t))?.secretKey?.trim()??"";if(!g){if(e.requireSecretKey)throw new yG("API key copy response is missing secretKey.");return u}return`${u}.${g}`}async function JOe(e,t,n){let o=await e.request({maxResponseBytes:65536,...t},n),s=JSON.parse(new TextDecoder().decode(o.body));if(!L7s(s.code))throw new yG(s.msg??`Remote business error ${s.code}`);return s.data??null}function xct(e){return{Authorization:e,"Content-Type":zZr}}function N7s(e){let t=e?.organizations??[],n=t.find(a=>a.organizationName?.includes(D7s))??t[0],o=n?.projects??[],s=o.find(a=>a.projectName?.includes(O7s))??o[0];return!n?.organizationId||!s?.projectId?null:{organizationId:n.organizationId,projectId:s.projectId}}function L7s(e){return e==null||e===0||e===200||e==="0"||e==="200"}var UZr,zZr,jZr,D7s,O7s,yG,qZr=Y(()=>{"use strict";ms();UZr="https://api.z.ai",zZr="application/json",jZr="zcode-api-key",D7s="\u9ED8\u8BA4\u673A\u6784",O7s="\u9ED8\u8BA4\u9879\u76EE",yG=class extends Error{static{r(this,"CodingPlanApiKeyError")}constructor(t,n={}){super(t,n),this.name="CodingPlanApiKeyError"}};r($Zr,"createCodingPlanApiKeyResolver");r(M7s,"resolveZaiBizToken");r(BZr,"resolveBizApiKey");r(JOe,"requestRemoteData");r(xct,"createBizAuthHeaders");r(N7s,"pickOrgAndProject");r(L7s,"isSuccessfulRemoteCode")});function Xdn(e){let t=z7s(e.baseUrl??F7s),n=new TextEncoder;return{async init(o,s){let a=await WZr(e.httpClient,{body:n.encode(JSON.stringify({provider:j7s})),headers:{Authorization:`Bearer ${o.pollToken}`,"Content-Type":U7s},method:"POST",trace:e.trace,url:`${t}/oauth/cli/init`},s);return $7s(a.data)},async poll(o,s){let a=encodeURIComponent(o.flowId),l=await WZr(e.httpClient,{headers:{Authorization:`Bearer ${o.pollToken}`},method:"GET",trace:e.trace,url:`${t}/oauth/cli/poll/${a}`},s);return q7s(l.data)}}}function HZr(){return(0,VZr.randomBytes)(B7s).toString("hex")}function z7s(e){return e.replace(/\/+$/u,"")}async function WZr(e,t,n){let o=await e.request({maxResponseBytes:65536,...t},n),s=new TextDecoder().decode(o.body),a=V7s(s,o.status),l=KOe(a);if(!l||typeof l.code!="number")throw new Q7("Invalid OAuth response envelope",{httpStatus:o.status});let u=typeof l.msg=="string"?l.msg:void 0;if(o.status<200||o.status>=300)throw new Q7(u??`OAuth HTTP error ${o.status}`,{businessCode:l.code,httpStatus:o.status});if(l.code!==0)throw new Q7(u??`OAuth business error ${l.code}`,{businessCode:l.code,httpStatus:o.status});return{code:l.code,data:l.data,msg:u}}function $7s(e){let t=KOe(e);if(!t||typeof t.flow_id!="string"||typeof t.poll_token!="string"||typeof t.authorize_url!="string"||typeof t.expires_at!="number"||typeof t.poll_interval_sec!="number")throw new Q7("Invalid OAuth init response data");return{authorize_url:t.authorize_url,expires_at:t.expires_at,flow_id:t.flow_id,poll_interval_sec:t.poll_interval_sec,poll_token:t.poll_token}}function q7s(e){let t=KOe(e),n=t?.status;if(n==="pending"||n==="failed")return{status:n};if(n==="ready"&&t)return W7s(t);throw new Q7("Invalid OAuth poll response data")}function W7s(e){let t=KOe(e.user),n=KOe(e.zai);if(typeof e.token!="string"||!t||typeof t.user_id!="string"||!n||typeof n.access_token!="string")throw new Q7("Invalid OAuth ready response data");return{status:"ready",token:e.token,user:{...typeof t.avatar=="string"?{avatar:t.avatar}:{},...typeof t.email=="string"?{email:t.email}:{},...typeof t.name=="string"?{name:t.name}:{},user_id:t.user_id},zai:{access_token:n.access_token}}}function V7s(e,t){try{return JSON.parse(e)}catch{let r=typeof t=="number"&&(t<200||t>=300)?`OAuth HTTP error ${t} (empty or non-JSON response)`:"OAuth response is not valid JSON";throw new Q7(r,{httpStatus:t})}}function KOe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}var VZr,F7s,j7s,B7s,U7s,Q7,GZr=Y(()=>{"use strict";VZr=require("node:crypto"),F7s="https://zcode.z.ai/api/v1",j7s="zai",B7s=32,U7s="application/json",Q7=class extends Error{static{r(this,"ZaiCliOAuthError")}businessCode;httpStatus;constructor(t,n={}){super(t),this.name="ZaiCliOAuthError",this.businessCode=n.businessCode,this.httpStatus=n.httpStatus}};r(Xdn,"createZaiCliOAuthClient");r(HZr,"createZaiCliOAuthPollToken");r(z7s,"normalizeBaseUrl");r(WZr,"requestJsonEnvelope");r($7s,"parseInitData");r(q7s,"parsePollData");r(W7s,"parseReadyData");r(V7s,"parseJson");r(KOe,"asRecord")});function ZZr(e={}){let t=K7s(Z7s(e.env??process.env));return{decrypt(n){if(!J7s(n))return n;let s=n.slice(Qdn.length).split("."),[a,l,u]=s;if(!a||!l||!u||s.length!==3)throw new Error("Credential decrypt failed: invalid ciphertext format");let f=Buffer.from(a,"base64url"),g=Buffer.from(l,"base64url"),_=Buffer.from(u,"base64url");if(f.length!==KZr)throw new Error("Credential decrypt failed: invalid IV length");if(g.length!==H7s)throw new Error("Credential decrypt failed: invalid auth tag length");try{let b=(0,vG.createDecipheriv)(JZr,t,f);return b.setAuthTag(g),Buffer.concat([b.update(_),b.final()]).toString("utf-8")}catch(b){throw new Error("Credential decrypt failed: key mismatch or corrupted ciphertext",{cause:b})}},encrypt(n){let o=(0,vG.randomBytes)(KZr),s=(0,vG.createCipheriv)(JZr,t,o),a=Buffer.concat([s.update(n,"utf-8"),s.final()]),l=s.getAuthTag();return[Qdn,o.toString("base64url"),".",l.toString("base64url"),".",a.toString("base64url")].join("")}}}function J7s(e){return e.startsWith(Qdn)}function K7s(e){return(0,vG.createHash)("sha256").update(e).digest()}function Z7s(e){let t=e[G7s]?.trim();if(t)return t;let n="unknown";try{n=(0,oge.userInfo)().username}catch{}return`zcode-credential-fallback:${(0,oge.platform)()}:${(0,oge.homedir)()}:${n}`}var vG,oge,Qdn,JZr,KZr,H7s,G7s,epn=Y(()=>{"use strict";vG=require("node:crypto"),oge=require("node:os"),Qdn="enc:v1:",JZr="aes-256-gcm",KZr=12,H7s=16,G7s="ZCODE_CREDENTIAL_SECRET";r(ZZr,"createZCodeCredentialCipher");r(J7s,"isEncryptedZCodeCredentialValue");r(K7s,"deriveCipherKey");r(Z7s,"resolveCredentialSecret")});function Q7s(e,t){let n=new Error(`OAuth authorization was rejected by the authorization server: ${e}`);return n.code=X7s,n.oauthError=e,t&&(n.oauthErrorDescription=t),n}async function YOe(e){let t=r(()=>{},"resolveCallback"),n=r(()=>{},"rejectCallback"),o=!1,s=new Promise((f,g)=>{t=f,n=g}),a=(0,XZr.createServer)((f,g)=>{try{let _=new URL(f.url??"/",`http://${tpn}`);if(_.pathname!==e.callbackPath){ige(g,404,ZOe);return}if((_.searchParams.get("state")??"")!==e.state){ige(g,400,ZOe);return}let w=_.searchParams.get("error");if(w){ige(g,400,ZOe),o||(o=!0,n(Q7s(w,_.searchParams.get("error_description"))));return}let T=_.searchParams.get("authCode")??_.searchParams.get("code")??"";if(!T){ige(g,400,ZOe),o||(o=!0,n(new Error("OAuth callback is missing an authorization code.")));return}ige(g,200,Y7s),o||(o=!0,t({code:T,url:_.toString()}))}catch(_){ige(g,500,ZOe),o||(o=!0,n(_ instanceof Error?_:new Error(String(_))))}});await new Promise((f,g)=>{a.once("error",g),a.listen(0,tpn,()=>{a.off("error",g),f()})});let l=a.address();if(!e$s(l))throw await YZr(a),new Error("Unable to resolve localhost callback server address.");let u=`http://${tpn}:${l.port}${e.callbackPath}`;return{callbackPath:e.callbackPath,callbackUrl:u,close:r(async()=>{await YZr(a)},"close"),waitForCallback:r(()=>s,"waitForCallback")}}function ige(e,t,n){e.writeHead(t,{"Content-Type":"text/plain; charset=utf-8"}),e.end(n)}function YZr(e){return e.listening?new Promise((t,n)=>{e.close(o=>{if(o){n(o);return}t()})}):Promise.resolve()}function e$s(e){return typeof e=="object"&&e!==null&&"port"in e}var XZr,tpn,Y7s,ZOe,X7s,Tct=Y(()=>{"use strict";XZr=require("node:http"),tpn="127.0.0.1",Y7s="Authorization successful! You may close this window and return to the CLI.",ZOe="Authorization failed. You may close this window and return to the CLI.",X7s="MCP_OAUTH_CALLBACK_DENIED";r(Q7s,"createCallbackDeniedError");r(YOe,"createLocalhostOAuthCallbackServer");r(ige,"writeText");r(YZr,"closeServer");r(e$s,"isAddressInfo")});function jM(e={}){let t=e.env??process.env,n=n$s(e),o=e.cipher??ZZr({env:t});return{filePath:n,async clearZaiLoginCredentials(){await e$(n,async s=>{let a=s[R1.activeProvider],l=a?o.decrypt(a):null;delete s[R1.zaiAccessToken],delete s[R1.zaiRefreshToken],delete s[R1.zaiUserInfo],delete s[R1.zcodeJwtToken],l===QZr&&delete s[R1.activeProvider]})},async delete(s){let a=VF(s);await e$(n,l=>{delete l[a]})},async deleteIfValue(s,a){let l=VF(s),u=bG(a),f=!1;return await e$(n,g=>{let _=g[l];_===void 0||o.decrypt(_)!==u||(delete g[l],f=!0)}),f},async deleteIfValues(s){let a=Object.entries(s).map(([u,f])=>[VF(u),bG(f)]);if(a.length===0)return{};let l={};return await e$(n,u=>{for(let[f,g]of a){let _=u[f],b=_!==void 0&&o.decrypt(_)===g;l[f]=b,b&&delete u[f]}}),l},async deleteManyIfValue(s,a,l){let u=VF(s),f=bG(a),g=l.map(VF),_=!1;return await e$(n,b=>{let w=b[u];if(!(w===void 0||o.decrypt(w)!==f)){for(let T of g)delete b[T];_=!0}}),_},async load(s){let l=(await npn(n))[VF(s)];return l===void 0?null:o.decrypt(l)},async loadMany(s){let a=s.map(VF),l=await npn(n);return Object.fromEntries(a.map(u=>{let f=l[u];return[u,f===void 0?null:o.decrypt(f)]}))},onDidChange(s){let a=Ict.get(n);return a||(a=new Set,Ict.set(n,a)),a.add(s),()=>{a?.delete(s),a?.size===0&&Ict.delete(n)}},async save(s,a){let l=VF(s),u=o.encrypt(bG(a));await e$(n,f=>{f[l]=u})},async saveMany(s){let a=Object.entries(s).map(([l,u])=>[VF(l),o.encrypt(bG(u))]);await e$(n,l=>{for(let[u,f]of a)l[u]=f})},async saveReplacing(s,a,l){let u=VF(s),f=o.encrypt(bG(a)),g=l.map(VF);await e$(n,_=>{_[u]=f;for(let b of g)b!==u&&delete _[b]})},async saveZaiLoginCredentials(s){let a={activeProvider:o.encrypt(QZr),accessToken:o.encrypt(bG(s.accessToken)),jwtToken:o.encrypt(bG(s.jwtToken)),userInfo:o.encrypt(JSON.stringify(s.user))};await e$(n,l=>{l[R1.activeProvider]=a.activeProvider,l[R1.zaiAccessToken]=a.accessToken,l[R1.zcodeJwtToken]=a.jwtToken,l[R1.zaiUserInfo]=a.userInfo})}}}function n$s(e={}){if(e.filePath)return eYr(e.filePath);let t=e.env??process.env,n=e.baseDir??t[t$s]??(0,Cct.homedir)();return(0,XOe.join)(eYr(n),".zcode","v2","credentials.json")}async function npn(e){let t;try{t=await(0,tYr.readFile)(e,"utf-8")}catch(n){if(o$s(n)==="ENOENT")return{};throw new Error(`Unable to read shared ZCode credentials: ${e}`,{cause:n})}try{return r$s(JSON.parse(t))}catch(n){let o=await Gqt(e).catch(()=>{}),s=o?` Backup: ${o}`:"";throw new Error(`Shared ZCode credentials are corrupt: ${e}.${s}`,{cause:n})}}async function e$(e,t){await lw(e,async()=>{let o=await npn(e);await t(o),await qL(e,`${JSON.stringify(o,null,2)}
|
|
2136
|
+
`):e}function _7s(e,t,n){let o=_Gr(e);if(o!==void 0){for(let a of o)Eat(n);return o}let s=(0,Bk.join)(e,"cache",Yp);try{let a=[];for(let l of(0,WF.readdirSync)(s,{withFileTypes:!0})){if(Eat(n),!l.isDirectory())continue;let u=(0,Bk.join)(s,l.name);for(let f of(0,WF.readdirSync)(u,{withFileTypes:!0}))f.isDirectory()&&a.push((0,Bk.join)(u,f.name))}return a}catch(a){return Cat(a)?[]:(t.push({code:"plugin_root_not_found",message:a instanceof Error?a.message:`Failed to scan ${s}`,path:s,severity:"warning"}),[])}}function y7s(e,t){if(!$v(e.rootPath))return t.push({code:"plugin_root_not_found",message:`Plugin root does not exist: ${e.rootPath}`,path:e.rootPath,severity:"warning"}),null;let n=v7s(e.rootPath);if(!n)return t.push({code:"plugin_manifest_not_found",message:`Plugin manifest not found: ${e.rootPath}`,path:e.rootPath,severity:"error"}),null;let o=b7s(n,t);return o?{id:`${o.name}@${e.marketplace}`,manifest:o,manifestPath:n,marketplace:e.marketplace,rootPath:e.rootPath,source:e.source}:null}function v7s(e){let t=(0,Bk.join)(e,qzs);if(bw(t))return t;let n=(0,Bk.join)(e,Wzs);if(bw(n))return n;let o=(0,Bk.join)(e,Vzs);return bw(o)?o:null}function b7s(e,t){try{let n=JSON.parse((0,WF.readFileSync)(e,"utf8"));if(!fu(n))throw new Error("Manifest must be a JSON object");let o=typeof n.name=="string"?n.name.trim():"";if(!Kzs.test(o))throw new Error(`Invalid plugin name: ${o}`);return{...n,name:o,version:typeof n.version=="string"?n.version:Hzs}}catch(n){return t.push({code:"plugin_manifest_invalid",message:n instanceof Error?n.message:`Invalid plugin manifest: ${e}`,path:e,severity:"error"}),null}}function S7s(){return{commandRoots:[],diagnostics:[],hooks:{},mcpServers:{},plugins:[],skillRoots:[]}}function w7s(e=[]){return{commandRoots:[],hooks:{},hookDetails:e,mcpServers:{},skillCount:0,skillRoots:[]}}function k7s(e,t,n){return e.enabledPlugins[t]??n}var WF,Bk,qzs,Wzs,Vzs,Hzs,Gzs,Jzs,Kzs,Zzs,Yzs,Kdn,GOe=Y(()=>{"use strict";WF=require("node:fs"),Bk=require("node:path");nr();q7();kat();Rat();Dun();Mun();Edn();Mat();Edn();Mat();sdn();EZr();qzs=(0,Bk.join)(".zcode-plugin","plugin.json"),Wzs=(0,Bk.join)(".claude-plugin","plugin.json"),Vzs=(0,Bk.join)(".codex-plugin","plugin.json"),Hzs="0.0.0",Gzs=1e3,Jzs=10,Kzs=/^[a-z0-9][a-z0-9._-]{0,127}$/,Zzs=["channels","lspServers","outputStyles","settings"],Yzs=new Set(Object.values(Tl)),Kdn=class{static{r(this,"NodePluginAdapter")}options;constructor(t){this.options=t}async discoverPlugins(t,n){return this.discoverPluginsSync(t,n)}discoverPluginsSync(t,n){if(!t.config.enabled)return S7s();let o=[],s=(0,Bk.join)(t.storageRoot||this.options.storageRoot,"data"),a=this.resolveCandidates(t,o,n),l=[],u={},f={},g=[],_=new Set,b=[],w=Gzs;for(let T of a){Eat(n);let I=y7s(T,o);if(!I||I.source==="official"&&t.config.suppressedBuiltins.includes(I.id))continue;if(_.has(I.id)){o.push({code:"plugin_duplicate_id",message:`Duplicate plugin ignored: ${I.id}`,path:I.rootPath,pluginId:I.id,severity:"warning"});continue}_.add(I.id),n7s(I,o);let E=T.defaultEnabled||(t.officialPluginsEnabledByDefault?.has(I.id)??!1),R=k7s(t.config,I.id,E),L=(0,Bk.join)(s,$7(I.id)),U=gre({diagnostics:o,loaded:I}),B=t7s(I),z=s7s({dataPath:L,diagnostics:o,loaded:I,runnable:B}),$=R?e7s({dataPath:L,diagnostics:o,env:t.env??{},hookEvents:B?z.events:{},hookDetails:z.details,loaded:I,mcpServerDefinitions:U,options:t.config.options[I.id]??{},priority:w,workingDirectory:t.workingDirectory}):w7s(z.details);w+=Jzs,Object.assign(f,$.mcpServers),AZr(u,$.hooks),b.push(...$.skillRoots),l.push(...$.commandRoots),g.push(Qzs(I,$,L,R,Object.keys(U),t.config.options[I.id]??{}))}return{commandRoots:l,diagnostics:o,hooks:u,mcpServers:f,plugins:g,skillRoots:b}}resolveCandidates(t,n,o){let s=[];for(let a of t.config.dirs)s.push({defaultEnabled:!0,marketplace:OZn,rootPath:(0,Bk.resolve)(a),source:"inline"});for(let a of t.officialPluginRoots??[])s.push({defaultEnabled:!1,marketplace:Yp,rootPath:(0,Bk.resolve)(a),source:"official"});s.push(..._7s(t.storageRoot,n,o).map(a=>({defaultEnabled:!1,marketplace:Yp,rootPath:a,source:"official"})));for(let a of X7(t.storageRoot))s.push({defaultEnabled:!1,marketplace:a.marketplace,rootPath:ydn(t.storageRoot,a),source:"cache"});return s}};r(Xzs,"createNodePluginAdapter");r(wct,"discoverNodePluginsSync");r(Qzs,"createPluginMetadata");r(e7s,"resolveEnabledComponents");r(t7s,"canRunPluginHooks");r(n7s,"warnUnsupportedComponents");r(r7s,"resolveSkillRoots");r(o7s,"warnEmptyDeclaredSkillRoots");r(i7s,"resolveCommandRoots");r(s7s,"inspectPluginHooks");r(a7s,"parsePluginHookEvents");r(c7s,"toPluginHookDetail");r(Zdn,"createHookPluginContext");r(l7s,"attachPluginToHook");r(AZr,"mergeHookEvents");r(u7s,"mergeHookInspection");r(PZr,"emptyHookInspection");r(d7s,"countSkillFiles");r(RZr,"resolveComponentRoots");r(p7s,"materializeCommandMetadataRoot");r(f7s,"normalizeGeneratedCommandName");r(m7s,"trimRelativePrefix");r(h7s,"applyCommandMetadataFrontmatter");r(g7s,"stripMarkdownFrontmatter");r(_7s,"scanOfficialCache");r(y7s,"loadPlugin");r(v7s,"findManifest");r(b7s,"readManifest");r(S7s,"emptyOutcome");r(w7s,"emptyComponents");r(k7s,"resolveEnabled")});function OZr(e){let t=e.appId??I7s,n=e.appSecret?.trim()??"",o=e.authorizeUrl??Hpe(process.env,x7s),s=e.tokenUrl??Hpe(process.env,T7s);return{buildAuthorizeUrl(a){let l=new URLSearchParams({appId:t,redirect:a.redirectUri,state:a.state});return`${o}?${l.toString()}`},async exchangeCode(a,l){if(!n)throw new kct("BigModel OAuth appSecret is required.");let u=await e.httpClient.request({body:new TextEncoder().encode(JSON.stringify({appId:t,appSecret:n,authCode:a.code})),headers:{"Content-Type":E7s},maxResponseBytes:64*1024,method:"POST",trace:e.trace,url:s},l),f=JSON.parse(new TextDecoder().decode(u.body)),g=f.data?.accessToken?.trim()??"";if(!g)throw new kct(f.msg??"BigModel token response is missing accessToken.");return{accessToken:g,...f.data?.refreshToken?{refreshToken:f.data.refreshToken}:{}}}}}function MZr(){return(0,DZr.randomBytes)(C7s).toString("hex")}var DZr,x7s,T7s,I7s,C7s,E7s,kct,NZr=Y(()=>{"use strict";DZr=require("node:crypto");ms();x7s="/login",T7s="/api/auth/tokenByAuthCode",I7s="zcode",C7s=32,E7s="application/json",kct=class extends Error{static{r(this,"BigmodelOAuthError")}constructor(t,n={}){super(t,n),this.name="BigmodelOAuthError"}};r(OZr,"createBigmodelOAuthClient");r(MZr,"createBigmodelOAuthState")});async function Ydn(e,t={}){let n=t.platform??process.platform,o=P7s(n,e),s=t.spawnProcess??LZr.spawn;try{let a=s(o.executable,o.args,{detached:!0,stdio:"ignore",windowsHide:!0});return await R7s(a,o.executable,t.timeoutMs)}catch(a){return{command:o.executable,opened:!1,reason:a instanceof Error?a.message:String(a)}}}function P7s(e,t){return e==="darwin"?{executable:"open",args:[t]}:e==="win32"?{executable:"cmd.exe",args:["/c","start","",t]}:{executable:"xdg-open",args:[t]}}function R7s(e,t,n=A7s){return new Promise(o=>{let s=!1,a,l=r(u=>{s||(s=!0,clearTimeout(a),e.removeAllListeners("error"),e.removeAllListeners("spawn"),u.opened&&e.unref(),o(u))},"settle");a=setTimeout(()=>{l({command:t,opened:!0})},n),e.once("spawn",()=>{l({command:t,opened:!0})}),e.once("error",u=>{l({command:t,opened:!1,reason:u.message})})})}var LZr,A7s,FZr=Y(()=>{"use strict";LZr=require("node:child_process"),A7s=1e3;r(Ydn,"openUrlInBrowser");r(P7s,"browserOpenCommand");r(R7s,"waitForBrowserSpawn")});function $Zr(e){return{async resolve(t,n){let o=t.accessToken.trim();if(!o)throw new yG("OAuth access token is required.");if(t.family==="bigmodel")return BZr({authorization:o,host:XAe(process.env),httpClient:e.httpClient,trace:e.trace},n);let s=await M7s(e,o,n);return BZr({authorization:`Bearer ${s}`,host:UZr,httpClient:e.httpClient,requireSecretKey:!0,trace:e.trace},n)}}}async function M7s(e,t,n){let o=await JOe(e.httpClient,{body:new TextEncoder().encode(JSON.stringify({token:t})),headers:{"Content-Type":zZr},method:"POST",trace:e.trace,url:`${UZr}/api/auth/z/login`},n),s=o?.access_token?.trim()??o?.accessToken?.trim()??"";if(!s)throw new yG("Z.AI biz token response is missing access_token.");return s}async function BZr(e,t){let n=await JOe(e.httpClient,{headers:xct(e.authorization),method:"GET",trace:e.trace,url:`${e.host}/api/biz/customer/getCustomerInfo`},t),o=N7s(n);if(!o)throw new yG("Unable to resolve organization and project.");let s=`${e.host}/api/biz/v1/organization/${o.organizationId}/projects/${o.projectId}/api_keys`,u=((await JOe(e.httpClient,{headers:xct(e.authorization),method:"GET",trace:e.trace,url:s},t)??[]).find(_=>_.name===jZr)??await JOe(e.httpClient,{body:new TextEncoder().encode(JSON.stringify({name:jZr})),headers:xct(e.authorization),method:"POST",trace:e.trace,url:s},t))?.apiKey?.trim()??"";if(!u)throw new yG("API key response is missing apiKey.");let g=(await JOe(e.httpClient,{headers:xct(e.authorization),method:"GET",trace:e.trace,url:`${s}/copy/${encodeURIComponent(u)}`},t))?.secretKey?.trim()??"";if(!g){if(e.requireSecretKey)throw new yG("API key copy response is missing secretKey.");return u}return`${u}.${g}`}async function JOe(e,t,n){let o=await e.request({maxResponseBytes:65536,...t},n),s=JSON.parse(new TextDecoder().decode(o.body));if(!L7s(s.code))throw new yG(s.msg??`Remote business error ${s.code}`);return s.data??null}function xct(e){return{Authorization:e,"Content-Type":zZr}}function N7s(e){let t=e?.organizations??[],n=t.find(a=>a.organizationName?.includes(D7s))??t[0],o=n?.projects??[],s=o.find(a=>a.projectName?.includes(O7s))??o[0];return!n?.organizationId||!s?.projectId?null:{organizationId:n.organizationId,projectId:s.projectId}}function L7s(e){return e==null||e===0||e===200||e==="0"||e==="200"}var UZr,zZr,jZr,D7s,O7s,yG,qZr=Y(()=>{"use strict";ms();UZr="https://api.z.ai",zZr="application/json",jZr="zcode-api-key",D7s="\u9ED8\u8BA4\u673A\u6784",O7s="\u9ED8\u8BA4\u9879\u76EE",yG=class extends Error{static{r(this,"CodingPlanApiKeyError")}constructor(t,n={}){super(t,n),this.name="CodingPlanApiKeyError"}};r($Zr,"createCodingPlanApiKeyResolver");r(M7s,"resolveZaiBizToken");r(BZr,"resolveBizApiKey");r(JOe,"requestRemoteData");r(xct,"createBizAuthHeaders");r(N7s,"pickOrgAndProject");r(L7s,"isSuccessfulRemoteCode")});function Xdn(e){let t=z7s(e.baseUrl??F7s),n=new TextEncoder;return{async init(o,s){let a=await WZr(e.httpClient,{body:n.encode(JSON.stringify({provider:j7s})),headers:{Authorization:`Bearer ${o.pollToken}`,"Content-Type":U7s},method:"POST",trace:e.trace,url:`${t}/oauth/cli/init`},s);return $7s(a.data)},async poll(o,s){let a=encodeURIComponent(o.flowId),l=await WZr(e.httpClient,{headers:{Authorization:`Bearer ${o.pollToken}`},method:"GET",trace:e.trace,url:`${t}/oauth/cli/poll/${a}`},s);return q7s(l.data)}}}function HZr(){return(0,VZr.randomBytes)(B7s).toString("hex")}function z7s(e){return e.replace(/\/+$/u,"")}async function WZr(e,t,n){let o=await e.request({maxResponseBytes:65536,...t},n),s=new TextDecoder().decode(o.body),a=V7s(s,o.status),l=KOe(a);if(!l||typeof l.code!="number")throw new Q7("Invalid OAuth response envelope",{httpStatus:o.status});let u=typeof l.msg=="string"?l.msg:void 0;if(o.status<200||o.status>=300)throw new Q7(u??`OAuth HTTP error ${o.status}`,{businessCode:l.code,httpStatus:o.status});if(l.code!==0)throw new Q7(u??`OAuth business error ${l.code}`,{businessCode:l.code,httpStatus:o.status});return{code:l.code,data:l.data,msg:u}}function $7s(e){let t=KOe(e);if(!t||typeof t.flow_id!="string"||typeof t.poll_token!="string"||typeof t.authorize_url!="string"||typeof t.expires_at!="number"||typeof t.poll_interval_sec!="number")throw new Q7("Invalid OAuth init response data");return{authorize_url:t.authorize_url,expires_at:t.expires_at,flow_id:t.flow_id,poll_interval_sec:t.poll_interval_sec,poll_token:t.poll_token}}function q7s(e){let t=KOe(e),n=t?.status;if(n==="pending"||n==="failed")return{status:n};if(n==="ready"&&t)return W7s(t);throw new Q7("Invalid OAuth poll response data")}function W7s(e){let t=KOe(e.user),n=KOe(e.zai);if(typeof e.token!="string"||!t||typeof t.user_id!="string"||!n||typeof n.access_token!="string")throw new Q7("Invalid OAuth ready response data");return{status:"ready",token:e.token,user:{...typeof t.avatar=="string"?{avatar:t.avatar}:{},...typeof t.email=="string"?{email:t.email}:{},...typeof t.name=="string"?{name:t.name}:{},user_id:t.user_id},zai:{access_token:n.access_token}}}function V7s(e,t){try{return JSON.parse(e)}catch{let r=typeof t=="number"&&(t<200||t>=300)?`OAuth HTTP error ${t} (empty or non-JSON response)`:"OAuth response is not valid JSON";throw new Q7(r,{httpStatus:t})}}function KOe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}var VZr,F7s,j7s,B7s,U7s,Q7,GZr=Y(()=>{"use strict";VZr=require("node:crypto"),F7s="https://zcode.z.ai/api/v1",j7s="zai",B7s=32,U7s="application/json",Q7=class extends Error{static{r(this,"ZaiCliOAuthError")}businessCode;httpStatus;constructor(t,n={}){super(t),this.name="ZaiCliOAuthError",this.businessCode=n.businessCode,this.httpStatus=n.httpStatus}};r(Xdn,"createZaiCliOAuthClient");r(HZr,"createZaiCliOAuthPollToken");r(z7s,"normalizeBaseUrl");r(WZr,"requestJsonEnvelope");r($7s,"parseInitData");r(q7s,"parsePollData");r(W7s,"parseReadyData");r(V7s,"parseJson");r(KOe,"asRecord")});function ZZr(e={}){let t=K7s(Z7s(e.env??process.env));return{decrypt(n){if(!J7s(n))return n;let s=n.slice(Qdn.length).split("."),[a,l,u]=s;if(!a||!l||!u||s.length!==3)throw new Error("Credential decrypt failed: invalid ciphertext format");let f=Buffer.from(a,"base64url"),g=Buffer.from(l,"base64url"),_=Buffer.from(u,"base64url");if(f.length!==KZr)throw new Error("Credential decrypt failed: invalid IV length");if(g.length!==H7s)throw new Error("Credential decrypt failed: invalid auth tag length");try{let b=(0,vG.createDecipheriv)(JZr,t,f);return b.setAuthTag(g),Buffer.concat([b.update(_),b.final()]).toString("utf-8")}catch(b){throw new Error("Credential decrypt failed: key mismatch or corrupted ciphertext",{cause:b})}},encrypt(n){let o=(0,vG.randomBytes)(KZr),s=(0,vG.createCipheriv)(JZr,t,o),a=Buffer.concat([s.update(n,"utf-8"),s.final()]),l=s.getAuthTag();return[Qdn,o.toString("base64url"),".",l.toString("base64url"),".",a.toString("base64url")].join("")}}}function J7s(e){return e.startsWith(Qdn)}function K7s(e){return(0,vG.createHash)("sha256").update(e).digest()}function Z7s(e){let t=e[G7s]?.trim();if(t)return t;let n="unknown";try{n=(0,oge.userInfo)().username}catch{}return`zcode-credential-fallback:${(0,oge.platform)()}:${(0,oge.homedir)()}:${n}`}var vG,oge,Qdn,JZr,KZr,H7s,G7s,epn=Y(()=>{"use strict";vG=require("node:crypto"),oge=require("node:os"),Qdn="enc:v1:",JZr="aes-256-gcm",KZr=12,H7s=16,G7s="ZCODE_CREDENTIAL_SECRET";r(ZZr,"createZCodeCredentialCipher");r(J7s,"isEncryptedZCodeCredentialValue");r(K7s,"deriveCipherKey");r(Z7s,"resolveCredentialSecret")});function Q7s(e,t){let n=new Error(`OAuth authorization was rejected by the authorization server: ${e}`);return n.code=X7s,n.oauthError=e,t&&(n.oauthErrorDescription=t),n}async function YOe(e){let t=r(()=>{},"resolveCallback"),n=r(()=>{},"rejectCallback"),o=!1,s=new Promise((f,g)=>{t=f,n=g}),a=(0,XZr.createServer)((f,g)=>{try{let _=new URL(f.url??"/",`http://${tpn}`);if(_.pathname!==e.callbackPath){ige(g,404,ZOe);return}if((_.searchParams.get("state")??"")!==e.state){ige(g,400,ZOe);return}let w=_.searchParams.get("error");if(w){ige(g,400,ZOe),o||(o=!0,n(Q7s(w,_.searchParams.get("error_description"))));return}let T=_.searchParams.get("authCode")??_.searchParams.get("code")??"";if(!T){ige(g,400,ZOe),o||(o=!0,n(new Error("OAuth callback is missing an authorization code.")));return}ige(g,200,Y7s),o||(o=!0,t({code:T,url:_.toString()}))}catch(_){ige(g,500,ZOe),o||(o=!0,n(_ instanceof Error?_:new Error(String(_))))}});await new Promise((f,g)=>{a.once("error",g),a.listen(0,tpn,()=>{a.off("error",g),f()})});let l=a.address();if(!e$s(l))throw await YZr(a),new Error("Unable to resolve localhost callback server address.");let u=`http://${tpn}:${l.port}${e.callbackPath}`;return{callbackPath:e.callbackPath,callbackUrl:u,close:r(async()=>{await YZr(a)},"close"),waitForCallback:r(()=>s,"waitForCallback")}}function ige(e,t,n){e.writeHead(t,{"Content-Type":"text/plain; charset=utf-8"}),e.end(n)}function YZr(e){return e.listening?new Promise((t,n)=>{e.close(o=>{if(o){n(o);return}t()})}):Promise.resolve()}function e$s(e){return typeof e=="object"&&e!==null&&"port"in e}var XZr,tpn,Y7s,ZOe,X7s,Tct=Y(()=>{"use strict";XZr=require("node:http"),tpn="127.0.0.1",Y7s="Authorization successful! You may close this window and return to the CLI.",ZOe="Authorization failed. You may close this window and return to the CLI.",X7s="MCP_OAUTH_CALLBACK_DENIED";r(Q7s,"createCallbackDeniedError");r(YOe,"createLocalhostOAuthCallbackServer");r(ige,"writeText");r(YZr,"closeServer");r(e$s,"isAddressInfo")});function jM(e={}){let t=e.env??process.env,n=n$s(e),o=e.cipher??ZZr({env:t});return{filePath:n,async clearZaiLoginCredentials(){await e$(n,async s=>{let a=s[R1.activeProvider],l=a?o.decrypt(a):null;delete s[R1.zaiAccessToken],delete s[R1.zaiRefreshToken],delete s[R1.zaiUserInfo],delete s[R1.zcodeJwtToken],l===QZr&&delete s[R1.activeProvider]})},async delete(s){let a=VF(s);await e$(n,l=>{delete l[a]})},async deleteIfValue(s,a){let l=VF(s),u=bG(a),f=!1;return await e$(n,g=>{let _=g[l];_===void 0||o.decrypt(_)!==u||(delete g[l],f=!0)}),f},async deleteIfValues(s){let a=Object.entries(s).map(([u,f])=>[VF(u),bG(f)]);if(a.length===0)return{};let l={};return await e$(n,u=>{for(let[f,g]of a){let _=u[f],b=_!==void 0&&o.decrypt(_)===g;l[f]=b,b&&delete u[f]}}),l},async deleteManyIfValue(s,a,l){let u=VF(s),f=bG(a),g=l.map(VF),_=!1;return await e$(n,b=>{let w=b[u];if(!(w===void 0||o.decrypt(w)!==f)){for(let T of g)delete b[T];_=!0}}),_},async load(s){let l=(await npn(n))[VF(s)];return l===void 0?null:o.decrypt(l)},async loadMany(s){let a=s.map(VF),l=await npn(n);return Object.fromEntries(a.map(u=>{let f=l[u];return[u,f===void 0?null:o.decrypt(f)]}))},onDidChange(s){let a=Ict.get(n);return a||(a=new Set,Ict.set(n,a)),a.add(s),()=>{a?.delete(s),a?.size===0&&Ict.delete(n)}},async save(s,a){let l=VF(s),u=o.encrypt(bG(a));await e$(n,f=>{f[l]=u})},async saveMany(s){let a=Object.entries(s).map(([l,u])=>[VF(l),o.encrypt(bG(u))]);await e$(n,l=>{for(let[u,f]of a)l[u]=f})},async saveReplacing(s,a,l){let u=VF(s),f=o.encrypt(bG(a)),g=l.map(VF);await e$(n,_=>{_[u]=f;for(let b of g)b!==u&&delete _[b]})},async saveZaiLoginCredentials(s){let a={activeProvider:o.encrypt(QZr),accessToken:o.encrypt(bG(s.accessToken)),jwtToken:o.encrypt(bG(s.jwtToken)),userInfo:o.encrypt(JSON.stringify(s.user))};await e$(n,l=>{l[R1.activeProvider]=a.activeProvider,l[R1.zaiAccessToken]=a.accessToken,l[R1.zcodeJwtToken]=a.jwtToken,l[R1.zaiUserInfo]=a.userInfo})}}}function n$s(e={}){e={...e,filePath:e.filePath??(e.env??process.env).ZCODE_CLI_CREDENTIALS_FILE?.trim()};if(e.filePath)return eYr(e.filePath);let t=e.env??process.env,n=e.baseDir??t[t$s]??(0,Cct.homedir)();return(0,XOe.join)(eYr(n),".zcode","v2","credentials.json")}async function npn(e){let t;try{t=await(0,tYr.readFile)(e,"utf-8")}catch(n){if(o$s(n)==="ENOENT")return{};throw new Error(`Unable to read shared ZCode credentials: ${e}`,{cause:n})}try{return r$s(JSON.parse(t))}catch(n){let o=await Gqt(e).catch(()=>{}),s=o?` Backup: ${o}`:"";throw new Error(`Shared ZCode credentials are corrupt: ${e}.${s}`,{cause:n})}}async function e$(e,t){await lw(e,async()=>{let o=await npn(e);await t(o),await qL(e,`${JSON.stringify(o,null,2)}
|
|
2137
2137
|
`)});let n=[...Ict.get(e)??[]];await Promise.allSettled(n.map(o=>o()))}function r$s(e){if(!i$s(e))throw new Error("Credential record must be an object");let t={};for(let[n,o]of Object.entries(e)){if(typeof o!="string")throw new Error(`Credential record value must be a string: ${n}`);t[n]=o}return t}function o$s(e){if(typeof e!="object"||e===null||!("code"in e))return;let t=e.code;return typeof t=="string"?t:void 0}function VF(e){let t=e.trim();if(t.length===0)throw new Error("Credential key must not be empty");return t}function bG(e){if(e.length===0)throw new Error("Credential value must not be empty");return e}function eYr(e){return e==="~"?(0,Cct.homedir)():e.startsWith("~/")?(0,XOe.join)((0,Cct.homedir)(),e.slice(2)):(0,XOe.resolve)(e)}function i$s(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var tYr,Cct,XOe,t$s,QZr,Ict,R1,Ect=Y(()=>{"use strict";tYr=require("node:fs/promises"),Cct=require("node:os"),XOe=require("node:path");bz();epn();t$s="ZCODE_DATA_BASE_DIR",QZr="zai",Ict=new Map,R1={activeProvider:"oauth:active_provider",bigmodelAccessToken:"oauth:bigmodel:access_token",bigmodelRefreshToken:"oauth:bigmodel:refresh_token",bigmodelUserInfo:"oauth:bigmodel:user_info",zaiAccessToken:"oauth:zai:access_token",zaiRefreshToken:"oauth:zai:refresh_token",zaiUserInfo:"oauth:zai:user_info",zcodeJwtToken:"zcodejwttoken"};r(jM,"createSharedZCodeCredentialStore");r(n$s,"resolveSharedZCodeCredentialsPath");r(npn,"readRawCredentialRecord");r(e$,"mutateRawCredentialRecord");r(r$s,"parseCredentialRecord");r(o$s,"getErrorCode");r(VF,"validateCredentialKey");r(bG,"validateCredentialValue");r(eYr,"resolveUserPath");r(i$s,"isRecord")});var rpn=Y(()=>{"use strict";NZr();FZr();qZr();GZr();epn();Tct();Ect()});function nYr(e,t){return{id:e,generation:t,type:"cdp",name:"ZCode Headless Chromium",capabilities:{browser:[],tab:[]},apiSupportOverrides:{"BrowserUser.openTabs":!1,"BrowserUser.history":!1,"PlaywrightAPI.waitForEvent":!1,"PlaywrightDownload.path":!1,"PlaywrightFileChooser.setFiles":!1,"PlaywrightLocator.downloadMedia":!1,"PlaywrightLocator.evaluate":!1,"CUAAPI.downloadMedia":!1,"DomCUAAPI.downloadMedia":!1},metadata:{provider:"zcode-cli",launchMode:"managed",headless:"true"}}}var rYr=Y(()=>{"use strict";r(nYr,"createManagedCdpDescriptor")});function c$s(e){return[e.PROGRAMFILES,e["PROGRAMFILES(X86)"],e.LOCALAPPDATA].filter(t=>!!t?.trim()).flatMap(t=>[(0,sge.join)(t,"Google","Chrome","Application","chrome.exe"),(0,sge.join)(t,"Chromium","Application","chrome.exe"),(0,sge.join)(t,"Microsoft","Edge","Application","msedge.exe")])}function oYr(e,t){try{return!(0,SG.existsSync)(e)||!(0,SG.statSync)(e).isFile()?!1:(t!=="win32"&&(0,SG.accessSync)(e,SG.constants.X_OK),!0)}catch{return!1}}function Act(e,t=process.platform){if(e===void 0)return;if(!(0,sge.isAbsolute)(e))throw new Error(`Browser executable path must be absolute: ${e}`);let n=e;if(!oYr(n,t))throw new Error(`Browser executable is missing or not executable: ${n}`);return n}function opn(e,t={}){let n=t.platform??process.platform,o=Act(t.executablePath,n);if(o)return o;let s=e.chromium.executablePath(),l=[...s?[s]:[],...n==="darwin"?a$s:n==="win32"?c$s(t.env??process.env):s$s].find(u=>oYr(u,n));if(l)return l;throw new Error("No installed Chrome or Chromium executable was found. Install Chromium or pass --browser-executable <absolute-path>.")}async function iYr(){return await import("playwright-core")}var SG,sge,s$s,a$s,ipn=Y(()=>{"use strict";SG=require("node:fs"),sge=require("node:path"),s$s=["/usr/bin/google-chrome-stable","/usr/bin/google-chrome","/usr/bin/chromium","/usr/bin/chromium-browser","/snap/bin/chromium"],a$s=["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"];r(c$s,"windowsBrowserPaths");r(oYr,"isUsableExecutable");r(Act,"validateExplicitBrowserExecutable");r(opn,"resolveInstalledBrowserExecutable");r(iYr,"loadPlaywrightChromium")});function Pct(e){return e===void 0?3e3:Math.min(3e3,Math.max(1,Math.floor(e)))}function l$s(e,t){return e.locator(t)}function sYr(e){return(e??[]).map(t=>t==="ControlOrMeta"?process.platform==="darwin"?"Meta":"Control":t)}async function spn(e,t,n,o,s){let a=await e.context().newCDPSession(e);try{let l=n==="function"?`(${t})(${JSON.stringify(o)})`:t,u=await a.send("Runtime.evaluate",{expression:l,awaitPromise:!0,returnByValue:!0,timeout:s});if(u.exceptionDetails){let f=u.exceptionDetails.exception?.description??u.exceptionDetails.text??"Playwright evaluate failed";throw new Error(`playwright.evaluate failed: ${f}`)}return u.result?.value}finally{await a.detach().catch(()=>{})}}async function u$s(e,t){let n=l$s(e,t.selector),o=Pct(t.timeoutMs);switch(t.operation){case"allTextContents":return await n.allTextContents();case"count":return await n.count();case"getAttribute":return await n.getAttribute(t.attribute??"",{timeout:o});case"innerText":return await n.innerText({timeout:o});case"isEnabled":return await n.isEnabled({timeout:o});case"isVisible":return await n.isVisible();case"textContent":return await n.textContent({timeout:o});case"click":await n.click({button:t.button,force:t.force,modifiers:sYr(t.modifiers),timeout:o});return;case"dblclick":await n.dblclick({button:t.button,force:t.force,modifiers:sYr(t.modifiers),timeout:o});return;case"fill":t.replace===!1?await n.pressSequentially(String(t.value??""),{timeout:o}):await n.fill(String(t.value??""),{timeout:o});return;case"press":await n.press(String(t.value??""),{timeout:o});return;case"selectOption":{let s=(t.selections??[]).map(a=>a.index!==void 0?{index:a.index}:a.label!==void 0?{label:a.label}:{value:a.value??""});await n.selectOption(s,{timeout:o});return}case"setChecked":await n.setChecked(t.checked??!0,{force:t.force,timeout:o});return;case"waitFor":await n.waitFor({state:t.state??"visible",timeout:o});return;case"downloadMedia":case"evaluate":throw new Error(`Playwright locator operation '${t.operation}' is unavailable`)}}async function aYr(e,t){switch(t.name){case"domSnapshot":return{ok:!0,value:await e.locator("html").ariaSnapshot({timeout:3e3})};case"elementInfo":return{ok:!0,value:await e.evaluate(({x:n,y:o,includeNonInteractable:s})=>document.elementsFromPoint(n,o).filter(a=>s||a.matches("a,button,input,select,textarea,[role],[tabindex]")).map(a=>{let l=a.getBoundingClientRect(),u=(a.innerText||a.textContent||"").trim();return{tagName:a.tagName.toLowerCase(),role:a.getAttribute("role"),visibleText:u||null,ariaName:a.getAttribute("aria-label")||u||null,testId:a.getAttribute("data-testid"),boundingBox:{x:l.x,y:l.y,width:l.width,height:l.height},preview:a.outerHTML.slice(0,300),selector:{primary:a.id?`#${a.id}`:a.tagName.toLowerCase(),candidates:[]}}}),t)};case"elementScreenshot":{let n="data-zcode-element-screenshot";if(await e.evaluate(({x:s,y:a,includeNonInteractable:l,markerAttribute:u})=>{let f=document.elementsFromPoint(s,a).filter(_=>l||_.matches("a,button,input,select,textarea,[role],[tabindex]")),g=0;for(let _ of f){let b=_.getBoundingClientRect();if(b.width<=0||b.height<=0)continue;let w=document.createElement("div");w.setAttribute(u,""),Object.assign(w.style,{border:"2px solid #ff2d55",boxSizing:"border-box",height:`${b.height}px`,left:`${b.left}px`,pointerEvents:"none",position:"fixed",top:`${b.top}px`,width:`${b.width}px`,zIndex:"2147483647"}),document.documentElement.append(w),g+=1}return g},{...t,markerAttribute:n})===0)throw new Error("No matching element was found at the requested point");try{return{ok:!0,image:{base64:(await e.screenshot({type:"png"})).toString("base64"),mimeType:"image/png"}}}finally{await e.evaluate(s=>document.querySelectorAll(`[${s}]`).forEach(a=>a.remove()),n).catch(()=>{})}}case"evaluate":return{ok:!0,value:await spn(e,t.expression,t.expressionKind,t.arg,Pct(t.timeoutMs))};case"waitForLoadState":if((t.state??"load")==="networkidle")throw new Error("playwright_wait_for_load_state does not support networkidle");return await e.waitForLoadState(t.state??"load",{timeout:Pct(t.timeoutMs)}),{ok:!0};case"waitForURL":if(t.waitUntil==="networkidle")throw new Error("playwright_wait_for_url does not support networkidle");return await e.waitForURL(t.url,{timeout:Pct(t.timeoutMs),waitUntil:t.waitUntil??"load"}),{ok:!0};case"locator":{let n=await u$s(e,t);return n===void 0?{ok:!0}:{ok:!0,value:n}}case"waitForEvent":case"downloadPath":case"fileChooserSetFiles":throw new Error(`Playwright action '${t.name}' is unavailable`)}}var cYr=Y(()=>{"use strict";r(Pct,"timeoutMs");r(l$s,"locatorFor");r(sYr,"modifiers");r(spn,"evaluatePage");r(u$s,"runLocatorAction");r(aYr,"executeManagedPlaywrightAction")});function d$s(e){let t="a[href],button,input,textarea,select,[role],[onclick],[tabindex],summary,label,[contenteditable]",n="body,main,nav,header,footer,aside,section,article,h1,h2,h3,h4,h5,h6,p,ul,ol,li,dl,dt,dd,blockquote,pre,code,table,caption,thead,tbody,tfoot,tr,th,td,form,fieldset,legend,figure,figcaption,img,canvas,svg,a[href],button,input,textarea,select,option,summary,label,[role],[aria-label],[contenteditable]",o=[],s=new WeakMap,a=window.innerWidth||document.documentElement.clientWidth||0,l=window.innerHeight||document.documentElement.clientHeight||0,u=r(B=>{let z=window.getComputedStyle(B),$=B.getBoundingClientRect();return z.display==="none"||z.visibility==="hidden"||z.opacity==="0"||$.width<=0&&$.height<=0},"hidden"),f=r((B,z)=>String(B??"").trim().replace(/\s+/g," ").slice(0,z),"text"),g=r((B,z)=>{if(z==="a"&&B.hasAttribute("href"))return"link";if(z==="button")return"button";if(z==="select")return"combobox";if(z==="textarea")return"textbox";if(z!=="input")return"";let $=(B.getAttribute("type")||"text").toLowerCase();return $==="checkbox"?"checkbox":$==="radio"?"radio":["button","submit","reset"].includes($)?"button":$==="search"?"searchbox":"textbox"},"implicitRole"),_=r(B=>f(B.getAttribute("aria-label")||B.getAttribute("alt")||B.getAttribute("title")||B.getAttribute("placeholder")||B.innerText||B.textContent,120),"accessibleName"),b=r(B=>{let z={};for(let $ of["id","href","name","type","placeholder","title","alt","role","aria-label","data-testid","data-test","data-qa"]){let J=f(B.getAttribute($),240);J&&(z[$]=J)}return z},"attributes"),w=r(B=>{if(B.id&&/^[A-Za-z][A-Za-z0-9_-]*$/.test(B.id))return`#${B.id}`;let z=[],$=B;for(let J=0;$&&J<6;J+=1){let q=$.tagName.toLowerCase(),ie=$.parentElement?[...$.parentElement.children].filter(ae=>ae.tagName===$?.tagName):[];z.unshift(`${q}:nth-of-type(${ie.indexOf($)+1})`),$=$.parentElement}return z.join(" > ")},"selector"),T=r(B=>{let z=[],$=B;for(;$;){let J=$.tagName.toLowerCase(),q=$.parentElement?[...$.parentElement.children].filter(ie=>ie.tagName===$?.tagName):[];z.unshift(`${J}[${q.indexOf($)+1}]`),$=$.parentElement}return`/${z.join("/")}`},"xpath"),I=r(B=>B.top<l&&B.bottom>0&&B.left<a&&B.right>0,"inViewport"),E=[...document.querySelectorAll(t)].filter(B=>e.includeHidden||!u(B)),R=E.slice(0,e.maxElements).map((B,z)=>{let $=`e${z+1}`;o.push(B),s.set(B,$);let J=B.getBoundingClientRect(),q=B.tagName.toLowerCase(),ie=B.getAttribute("role")||g(B,q),ae=_(B),Ce=f(B.innerText,100),pe=b(B),ze="value"in B?f(String(B.value),240):"",rt=B.parentElement,Pe;for(;rt&&!Pe;)Pe=s.get(rt),rt=rt.parentElement;return{ref:$,tag:q,...ie?{role:ie}:{},...ae?{name:ae}:{},...Ce?{text:Ce}:{},...ze?{value:ze}:{},..."disabled"in B&&B.disabled?{disabled:!0}:{},..."checked"in B?{checked:!!B.checked}:{},selector:w(B),xpath:T(B),rect:{x:Math.round(J.x),y:Math.round(J.y),width:Math.round(J.width),height:Math.round(J.height)},inViewport:I(J),...Pe?{parentRef:Pe}:{},...Object.keys(pe).length>0?{attributes:pe}:{}}}),L=[...document.querySelectorAll(n)].filter(B=>e.includeHidden||!u(B)),U=L.slice(0,e.maxDomNodes).map(B=>{let z=B.getBoundingClientRect(),$=B.tagName.toLowerCase(),J=B.getAttribute("role")||g(B,$),q=_(B),ie=/^(h[1-6]|p|li|dt|dd|blockquote|pre|code|caption|th|td|label|summary|button|a|option|legend|figcaption)$/.test($)?f(B.innerText||B.textContent,300):"",ae=0;for(let ze=B.parentElement;ze&&ze!==document.body;ze=ze.parentElement)ae+=1;let Ce=s.get(B),pe=b(B);return{tag:$,depth:ae,inViewport:I(z),...Ce?{ref:Ce}:{},...J?{role:J}:{},...q?{name:q}:{},...ie?{text:ie}:{},...Object.keys(pe).length>0?{attributes:pe}:{}}});return{refElements:o,snapshot:{url:location.href,title:document.title,elements:R,truncated:E.length>e.maxElements,dom:U,domTruncated:L.length>e.maxDomNodes}}}async function cpn(e,t=200,n=!1){let o=await e.evaluateHandle(d$s,{includeHidden:n,maxDomNodes:300,maxElements:Math.max(1,Math.floor(t))}),s=await o.getProperty("snapshot"),a=await o.getProperty("refElements"),l=await s.jsonValue(),u=new Map;for(let[g,_]of await a.getProperties()){let b=_.asElement();if(!b||!/^\d+$/u.test(g)){await _.dispose();continue}u.set(`e${Number(g)+1}`,b)}let f=apn.get(e);return apn.set(e,u),await Promise.all([...f?.values()??[]].map(async g=>g.dispose())),await Promise.all([s.dispose(),a.dispose(),o.dispose()]),l}async function lpn(e,t){let n=apn.get(e)?.get(t);return n&&await n.evaluate(s=>s.isConnected).catch(()=>!1)?n:void 0}async function lYr(e,t){let n=await lpn(e,t);if(!n)return;await n.scrollIntoViewIfNeeded();let o=await n.boundingBox();return o?{x:Math.round(o.x+o.width/2),y:Math.round(o.y+o.height/2)}:void 0}var apn,uYr=Y(()=>{"use strict";apn=new WeakMap;r(d$s,"collectSnapshot");r(cpn,"captureManagedCdpSnapshot");r(lpn,"resolveSnapshotElement");r(lYr,"resolveSnapshotRef")});function pYr(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"||t.href==="about:blank"}catch{return!1}}function p$s(e){return e==="ControlOrMeta"?process.platform==="darwin"?"Meta":"Control":e}async function age(e,t,n){let o=(t??[]).map(p$s);for(let s of o)await e.keyboard.down(s);try{await n()}finally{for(let s of o.reverse())await e.keyboard.up(s)}}async function Ere(e,t){let n=await lpn(e,t);if(!n)throw new Error(`Browser ref '${t}' is stale or unavailable. Take a fresh snapshot before retrying.`);return n}async function QOe(e,t,n){if(t){let o=await lYr(e,t);if(!o)throw new Error(`Browser ref '${t}' is stale or unavailable`);return o}if(n)return n;throw new Error("Browser action requires a ref or x/y coordinates")}async function eMe(e){let t=await e.context().newCDPSession(e);try{let n=await t.send("Page.getNavigationHistory"),o=n.currentIndex??0,s=n.entries?.length??1,a=e.viewportSize(),l=await e.evaluate(()=>({scrollX:Math.round(window.scrollX),scrollY:Math.round(window.scrollY)})).catch(()=>({scrollX:0,scrollY:0}));return{url:e.url(),title:await e.title().catch(()=>""),canGoBack:o>0,canGoForward:o+1<s,...l,...a?{viewportWidth:a.width,viewportHeight:a.height}:{}}}finally{await t.detach().catch(()=>{})}}async function f$s(e,t){if(t.length===0)return;let n=t.map(s=>s==="ControlOrMeta"?process.platform==="darwin"?"Meta":"Control":s),o=n.slice(0,-1);for(let s of o)await e.keyboard.down(s);try{await e.keyboard.press(n.at(-1)??"")}finally{for(let s of o.reverse())await e.keyboard.up(s)}}async function dYr(e,t){if(t.length===0)throw new Error("Browser drag requires a non-empty path");let[n,...o]=t;await e.mouse.move(n.x,n.y),await e.mouse.down();try{for(let s of o)await e.mouse.move(s.x,s.y,{steps:4})}finally{await e.mouse.up()}}async function fYr(e,t){switch(t.method){case"navigate":return pYr(t.url)?(await e.goto(t.url,{timeout:Rct,waitUntil:"load"}),{ok:!0,state:await eMe(e)}):{ok:!1,error:{code:"navigation_blocked",message:`Navigation URL is not allowed: ${t.url}`}};case"back":return await e.goBack({timeout:Rct,waitUntil:"load"}),{ok:!0,state:await eMe(e)};case"forward":return await e.goForward({timeout:Rct,waitUntil:"load"}),{ok:!0,state:await eMe(e)};case"reload":return await e.reload({timeout:Rct,waitUntil:"load"}),{ok:!0,state:await eMe(e)};case"getState":return{ok:!0,state:await eMe(e)};case"snapshot":return{ok:!0,snapshot:await cpn(e,t.maxElements,t.includeHidden)};case"screenshot":return{ok:!0,image:{base64:(t.ref?await(await Ere(e,t.ref)).screenshot({type:"png"}):await e.screenshot({type:"png",fullPage:t.fullPage,clip:t.clip})).toString("base64"),mimeType:"image/png"}};case"click":{let n=await QOe(e,t.ref,t.x!==void 0&&t.y!==void 0?{x:t.x,y:t.y}:void 0);return await age(e,t.modifiers,async()=>{await e.mouse.click(n.x,n.y,{button:t.button,clickCount:t.doubleClick?2:1})}),{ok:!0}}case"fill":return await(await Ere(e,t.ref)).fill(t.value),{ok:!0};case"type":return t.ref&&await(await Ere(e,t.ref)).focus(),await e.keyboard.type(t.text),{ok:!0};case"press":return t.ref?await(await Ere(e,t.ref)).press(t.key):await age(e,t.modifiers,async()=>e.keyboard.press(t.key)),{ok:!0};case"cuaKeypress":return await f$s(e,t.keys),{ok:!0};case"scroll":return t.ref&&await(await Ere(e,t.ref)).evaluate(n=>n.scrollIntoView()),await e.evaluate(({x:n,y:o})=>window.scrollBy(n,o),{x:t.x??0,y:t.y??0}),{ok:!0};case"cuaScroll":return await age(e,t.modifiers,async()=>{await e.mouse.move(t.x,t.y),await e.mouse.wheel(t.scrollX,t.scrollY)}),{ok:!0};case"domCuaScroll":{let n=t.nodeId?await QOe(e,t.nodeId,void 0):await e.evaluate(()=>({x:window.innerWidth/2,y:window.innerHeight/2}));return await e.mouse.move(n.x,n.y),await e.mouse.wheel(t.scrollX,t.scrollY),{ok:!0}}case"hover":{let n=await QOe(e,t.ref,t.x!==void 0&&t.y!==void 0?{x:t.x,y:t.y}:void 0);return await age(e,t.modifiers,async()=>e.mouse.move(n.x,n.y)),{ok:!0}}case"select":return await(await Ere(e,t.ref)).selectOption(t.values),{ok:!0};case"check":return await(await Ere(e,t.ref)).setChecked(t.checked??!0),{ok:!0};case"drag":{let n=await QOe(e,t.fromRef,t.from),o=await QOe(e,t.toRef,t.to);return await age(e,t.modifiers,async()=>dYr(e,[n,o])),{ok:!0}}case"cuaDrag":return await age(e,t.modifiers,async()=>dYr(e,t.path)),{ok:!0};case"elementInfo":return{ok:!0,element:(await cpn(e)).elements.find(o=>t.x>=o.rect.x&&t.x<=o.rect.x+o.rect.width&&t.y>=o.rect.y&&t.y<=o.rect.y+o.rect.height)};case"evaluate":return{ok:!0,value:await spn(e,t.expression,"string",void 0,3e3)};case"waitFor":{let n=Math.min(3e3,Math.max(1,t.timeoutMs??3e3));if(t.selector)await e.locator(t.selector).waitFor({timeout:n,state:"visible"});else if(t.text)await e.getByText(t.text).waitFor({timeout:n,state:"visible"});else if(t.textGone)await e.getByText(t.textGone).waitFor({timeout:n,state:"hidden"});else throw new Error("waitFor requires selector, text, or textGone");return{ok:!0}}case"playwright":return await aYr(e,t.action);case"playwrightWaitForTimeout":return await new Promise(n=>setTimeout(n,t.timeoutMs)),{ok:!0};default:return{ok:!1,error:{code:"capability_unsupported",message:`Browser command '${t.method}' is unavailable in the managed CDP page runtime`}}}}var Rct,upn=Y(()=>{"use strict";cYr();uYr();Rct=3e4;r(pYr,"isAllowedManagedBrowserUrl");r(p$s,"normalizedModifier");r(age,"withModifiers");r(Ere,"elementForRef");r(QOe,"pointFor");r(eMe,"readManagedPageState");r(f$s,"pressKeys");r(dYr,"dragPath");r(fYr,"executeManagedPageCommand")});function HF(){return new DOMException("Browser command cancelled","AbortError")}async function dpn(e,t){if(t.aborted)throw HF();return await new Promise((n,o)=>{let s=r(()=>o(HF()),"onAbort");t.addEventListener("abort",s,{once:!0}),e.then(n,o).finally(()=>t.removeEventListener("abort",s))})}function mYr(e){return e.method==="playwright"&&e.action.name==="locator"?["click","dblclick","fill","press","selectOption","setChecked"].includes(e.action.operation):e.method==="playwright"&&e.action.name==="evaluate"?!0:["navigate","back","forward","reload","click","fill","type","press","cuaKeypress","scroll","cuaScroll","domCuaScroll","hover","select","check","drag","cuaDrag","handleDialog","close","newTab","evaluate"].includes(e.method)}function hYr(e){return e instanceof Error&&e.name==="AbortError"?"cancelled":e instanceof Error&&e.name==="TimeoutError"?"timeout":e instanceof Error&&/unavailable|closed|disconnected/iu.test(e.message)?"backend_unavailable":"execution_error"}var gYr=Y(()=>{"use strict";r(HF,"abortError");r(dpn,"raceWithAbort");r(mYr,"hasSideEffects");r(hYr,"classifyError")});var yYr,_Yr,Dct,vYr=Y(()=>{"use strict";yYr=require("node:crypto"),_Yr={width:1280,height:720},Dct=class{static{r(this,"ManagedCdpSession")}context;#e=new Map;#t=new Map;#n;constructor(t){this.context=t;for(let n of t.pages())this.registerPage(n);t.on("page",n=>this.registerPage(n))}get tabIds(){return[...this.#t.keys()]}get activeTabId(){return this.#n}async createTab(){let t=await this.context.newPage(),n=this.tabForPage(t)??this.registerPage(t);return this.#n=n.id,await t.bringToFront(),n}async ensureTab(t){if(t){let s=this.#t.get(t);if(!s||s.page.isClosed())throw new Error(`Browser tab '${t}' is unavailable`);return s}let n=this.#n?this.#t.get(this.#n):void 0;return n&&!n.page.isClosed()?n:[...this.#t.values()].find(s=>!s.page.isClosed())??await this.createTab()}async activateTab(t){let n=await this.ensureTab(t);return this.#n=n.id,await n.page.bringToFront(),n}async closeTab(t){let n=await this.ensureTab(t);this.#t.delete(n.id),this.#e.delete(n.id),n.page.isClosed()||await n.page.close({runBeforeUnload:!1}),this.#n===n.id&&(this.#n=[...this.#t.keys()].at(-1))}async listTabs(){let t=[];for(let n of this.#t.values())n.page.isClosed()||t.push({tabId:n.id,url:n.page.url(),title:await n.page.title().catch(()=>""),viewport:n.page.viewportSize()??_Yr,...n.id===this.#n?{active:!0}:{},lifecycle:"active"});return t}dialogFor(t){return this.#e.get(t)}clearDialog(t){this.#e.delete(t)}async setViewport(t,n){await(await this.ensureTab(t)).page.setViewportSize(n??_Yr)}async close(){this.#e.clear(),this.#t.clear(),this.context.browser()?.isConnected()&&await this.context.close().catch(()=>{})}registerPage(t){let n=this.tabForPage(t);if(n)return n;let o={id:`tab:${(0,yYr.randomUUID)()}`,page:t};return this.#t.set(o.id,o),this.#n??=o.id,t.on("dialog",s=>this.#e.set(o.id,s)),t.on("close",()=>{this.#t.delete(o.id),this.#e.delete(o.id),this.#n===o.id&&(this.#n=[...this.#t.keys()].at(-1))}),o}tabForPage(t){return[...this.#t.values()].find(n=>n.page===t)}}});function bYr(e={}){let t={...e,executablePath:Act(e.executablePath,e.platform)},n=new fpn(t);return{browserControlPort:n,close:r(async()=>n.close(),"close")}}function Are(e,t){return new Promise(n=>{let o=!1,s,a=r(l=>{o||(o=!0,s&&clearTimeout(s),n(l))},"finish");s=setTimeout(()=>a(!1),t),e.then(()=>a(!0),()=>a(!0))})}var ppn,m$s,fpn,mpn=Y(()=>{"use strict";ppn=require("node:crypto");rYr();ipn();upn();gYr();vYr();ipn();upn();m$s=1500,fpn=class{static{r(this,"ManagedCdpBrowserControlPort")}#e=`cdp:${(0,ppn.randomUUID)()}`;#t;#n;#r;#o=new Set;#i=new Map;#c=new Map;#s=new Map;#a;#l=!1;#d=1;#u;constructor(t){this.#n=t,this.#t=t.loadPlaywright??iYr,this.#r=Math.max(1,Math.trunc(t.closeTimeoutMs??m$s))}async list(t){return await this.ensureBrowser(t.signal),[this.descriptor()]}async execute(t){let n=Date.now();if(t.browserId!==this.#e||t.browserGeneration!==this.#d)return this.errorResult("backend_unavailable",`Browser backend '${t.browserId}' generation ${t.browserGeneration} is stale`,n);let o=(0,ppn.randomUUID)(),s=new AbortController,a=r(()=>s.abort(t.signal?.reason??HF()),"forwardAbort");t.signal?.addEventListener("abort",a,{once:!0}),t.signal?.aborted&&a(),this.#i.set(o,{controller:s,sessionId:t.sessionId,turnId:t.turnId});let l=!1;try{if(s.signal.aborted)throw HF();await this.ensureBrowser(s.signal);let u=await this.ensureSession(t.sessionId);if(s.signal.aborted)throw HF();l=!0;let f=await dpn(this.executeSessionCommand(u,t.command),s.signal);return await this.withMeta(u,t.command,f,n)}catch(u){let f=hYr(u);return this.errorResult(f,u instanceof Error?u.message:String(u),n,f==="cancelled"&&l&&mYr(t.command)?"uncertain":void 0)}finally{t.signal?.removeEventListener("abort",a),this.#i.delete(o)}}async turnEnded(t){for(let n of this.#i.values())n.sessionId===t.sessionId&&n.turnId===t.turnId&&n.controller.abort(HF())}async closeSession(t){this.#o.add(t.sessionId);for(let s of this.#i.values())s.sessionId===t.sessionId&&s.controller.abort(HF());let n=this.#c.get(t.sessionId);n&&(await Are(n,this.#r)||n.then(async()=>{this.#s.size===0&&await this.closeBrowser()},async()=>{this.#s.size===0&&await this.closeBrowser()}));let o=this.#s.get(t.sessionId);this.#s.delete(t.sessionId),o&&await Are(o.close(),this.#r),this.#s.size===0&&await this.closeBrowser()}async close(){if(this.#l)return;this.#l=!0;let t=this.#u;for(let n of this.#i.values())n.controller.abort(HF());this.#i.clear(),this.#o.clear(),await Promise.all([...this.#c.values()].map(async n=>{await Are(n,this.#r)})),await Promise.all([...this.#s.values()].map(async n=>{await Are(n.close(),this.#r)})),this.#s.clear(),await this.closeBrowser(),t&&await Are(t.then(async n=>this.closeBrowserInstance(n)),this.#r)}descriptor(){return nYr(this.#e,this.#d)}async ensureBrowser(t){if(this.#l)throw new Error("Managed CDP browser runtime is closed");if(t?.aborted)throw HF();if(this.#a?.isConnected())return this.#a;this.#u??=(async()=>{let o;try{o=await this.#t()}catch(l){throw new Error("Managed headless Chromium is unavailable: failed to load the pinned Playwright runtime.",{cause:l})}let s=opn(o,this.#n),a;try{a=await o.chromium.launch({executablePath:s,headless:!0,args:["--no-first-run","--no-default-browser-check"]})}catch(l){throw new Error("Managed headless Chromium is unavailable: launch failed. Verify the browser executable and OS sandbox/runtime dependencies.",{cause:l})}if(this.#l)throw await this.closeBrowserInstance(a),new Error("Managed CDP browser runtime is closed");return a.on("disconnected",()=>{this.#a===a&&(this.#a=void 0,this.#s.clear(),this.#d+=1)}),this.#a=a,a})().finally(()=>{this.#u=void 0});let n=t?await dpn(this.#u,t):await this.#u;if(t?.aborted)throw await this.closeBrowserInstance(n),HF();return n}async ensureSession(t){if(this.#o.has(t))throw new Error(`Browser session '${t}' is closing`);let n=this.#s.get(t);if(n)return n;let o=this.#c.get(t);if(o)return await o;let s=(async()=>{let a=await this.ensureBrowser(),l=this.#d,u=await a.newContext({acceptDownloads:!1,viewport:{width:1280,height:720}});if(this.#l||this.#o.has(t)||this.#a!==a||this.#d!==l||!a.isConnected())throw await Are(u.close(),this.#r),new Error("Managed CDP browser context became unavailable during creation");let f=new Dct(u);return this.#s.set(t,f),f})();this.#c.set(t,s);try{return await s}finally{this.#c.get(t)===s&&this.#c.delete(t)}}async executeSessionCommand(t,n){switch(n.method){case"list":return{ok:!0,tabs:await t.listTabs()};case"newTab":{let o=await t.createTab();return{ok:!0,tab:(await t.listTabs()).find(s=>s.tabId===o.id)}}case"activateTab":{let o=await t.activateTab(n.tabId);return{ok:!0,tab:(await t.listTabs()).find(s=>s.tabId===o.id)}}case"close":return await t.closeTab(n.tabId),{ok:!0};case"browserViewportSet":return await t.setViewport(n.tabId,{width:n.width,height:n.height}),{ok:!0};case"browserViewportReset":return await t.setViewport(n.tabId,null),{ok:!0};case"getDialog":{let o=await t.ensureTab(n.tabId),s=t.dialogFor(o.id),a=s?.type();return{ok:!0,dialog:s&&a&&["alert","confirm","prompt","beforeunload"].includes(a)?{type:a,message:s.message(),...s.defaultValue()?{defaultPrompt:s.defaultValue()}:{}}:null}}case"handleDialog":{let o=await t.ensureTab(n.tabId),s=t.dialogFor(o.id);if(!s)throw new Error("No JavaScript dialog is pending for this tab");return n.accept?await s.accept(n.promptText):await s.dismiss(),t.clearDialog(o.id),{ok:!0}}case"nameSession":return{ok:!0};case"listUserTabs":return{ok:!0,userTabs:[]};case"browserVisibilityGet":case"browserVisibilitySet":case"capabilities":case"claimTab":case"finalize":case"finalizeTabs":case"markDeliverable":case"markHandoff":case"turnEnded":case"closeSession":case"cancelRequest":return{ok:!1,error:{code:"capability_unsupported",message:`Browser command '${n.method}' is unavailable in managed headless CDP`}};default:{let o=await t.ensureTab("tabId"in n?n.tabId:void 0);return await fYr(o.page,n)}}}async withMeta(t,n,o,s){let a="tabId"in n?n.tabId:t.activeTabId,l=a?await t.ensureTab(a).catch(()=>{}):void 0;return{...o,elapsedMs:Date.now()-s,meta:{browserUse:!0,backendType:"cdp",browserId:this.#e,browserGeneration:this.#d,openTabIds:t.tabIds,...l?{tabId:l.id,currentUrl:l.page.url(),lifecycle:"active"}:{}}}}errorResult(t,n,o,s){return{ok:!1,error:{code:t,message:n,...s?{sideEffect:s}:{}},elapsedMs:Date.now()-o}}async closeBrowser(){let t=this.#a;this.#a=void 0,t&&await this.closeBrowserInstance(t)}async closeBrowserInstance(t){t.isConnected()&&await Are(t.close(),this.#r)}};r(bYr,"createManagedCdpBrowserRuntime");r(Are,"waitForPromise")});var h$s,Oct,g$s,_$s,y$s,v$s,qs,SYr,b$s,Mct,hpn=Y(()=>{h$s=Object.create,Oct=Object.defineProperty,g$s=Object.getOwnPropertyDescriptor,_$s=Object.getOwnPropertyNames,y$s=Object.getPrototypeOf,v$s=Object.prototype.hasOwnProperty,qs=r((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"__commonJSMin"),SYr=r((e,t)=>{let n={};for(var o in e)Oct(n,o,{get:e[o],enumerable:!0});return t&&Oct(n,Symbol.toStringTag,{value:"Module"}),n},"__exportAll"),b$s=r((e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(var s=_$s(t),a=0,l=s.length,u;a<l;a++)u=s[a],!v$s.call(e,u)&&u!==n&&Oct(e,u,{get:(f=>t[f]).bind(null,u),enumerable:!(o=g$s(t,u))||o.enumerable});return e},"__copyProps"),Mct=r((e,t,n)=>(n=e!=null?h$s(y$s(e)):{},b$s(t||!e||!e.__esModule?Oct(n,"default",{value:e,enumerable:!0}):n,e)),"__toESM")});function kYr(e){return typeof e=="string"&&wYr.has(e.replace(/#$/,""))}function xYr(e,t){if(!("$schema"in e)||typeof e.$schema!="string")return"2020-12";let n=e.$schema.replace(/#$/,"");if(S$s.has(n))return"2020-12";if(wYr.has(n))return"2019-09";if(w$s.has(n)||k$s.has(n))return"draft-7";throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}var S$s,wYr,w$s,k$s,gpn=Y(()=>{S$s=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),wYr=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),w$s=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),k$s=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);r(kYr,"declares2019Dialect");r(xYr,"declaredDialect")});var cge,Nct,Lct,n$,lge,r$,Rre,tMe,uge,Dre,wG,qv,ypn,nMe,rMe,Fct,jct,oMe,zk,Ore,Wv,D1,O1,iMe,Vv,kG,sMe,aMe,dge,pge,pB,vpn,cMe,Bct,lMe,Uct,xG,t$,fge,x$s,T$s,zct,$ct,qct,Wct,uMe,dMe,Vct,pMe,Hct,Mre,fMe,Gct,Jct,mMe,Kct,TG,IG,hMe,gMe,bpn,_Me,CG,o$,yMe,Zct,Yct,Xct,Qct,elt,mge,tlt,nlt,rlt,olt,ilt,slt,alt,clt,vMe,llt,ult,dlt,plt,flt,mlt,hlt,glt,_lt,ylt,vlt,blt,Slt,wlt,hge,gge,_ge,klt,xlt,Tlt,yge,Ilt,Clt,Elt,Alt,Plt,bMe,Rlt,Dlt,SMe,Spn,Olt,Mlt,Nlt,wMe,kMe,Llt,Flt,jlt,Blt,Ult,zlt,$lt,qlt,Wlt,Pre,Vlt,Hlt,Glt,Jlt,Klt,xMe,vge,bge,TMe,IMe,CMe,Zlt,EMe,AMe,Ylt,Xlt,PMe,Sge,Qlt,eut,tut,nut,rut,out,iut,sut,aut,cut,lut,uut,dut,put,fut,wpn,mut,EG,kpn,hut,xpn,Tpn,Ipn,Cpn,Epn,Apn,Ppn,Rpn,Dpn,Opn,Mpn,Npn,Lpn,Fpn,jpn,Uk,RMe,wge,gut,DMe,OMe,_ut,MMe,_pn,yut,vut,NMe,Bpn,Upn,TYr=Y(()=>{tc();cge="2025-11-25",Nct=[cge,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Lct="io.modelcontextprotocol/related-task",n$="io.modelcontextprotocol/protocolVersion",lge="io.modelcontextprotocol/clientInfo",r$="io.modelcontextprotocol/serverInfo",Rre="io.modelcontextprotocol/clientCapabilities",tMe="io.modelcontextprotocol/subscriptionId",uge="io.modelcontextprotocol/logLevel",Dre="2.0",wG=mV(()=>bc([$t(),Gs(),kc(),Bj(),cc($t(),wG),Go(wG)])),qv=cc($t(),wG),ypn=Go(wG),nMe=bc([$t(),Gs().int()]),rMe=$t(),Fct=Fr({ttl:Gs().optional()}),jct=Fr({taskId:$t()}),oMe=nu({progressToken:nMe.optional(),[Lct]:jct.optional()}),zk=Fr({_meta:oMe.optional()}),Ore=zk.extend({task:Fct.optional()}),Wv=Fr({method:$t(),params:zk.loose().optional()}),D1=Fr({_meta:oMe.optional()}),O1=Fr({method:$t(),params:D1.loose().optional()}),iMe=nu({get[r$](){return fge.optional().catch(void 0)}}),Vv=nu({_meta:iMe.optional()}),kG=bc([$t(),Gs().int()]),sMe=Fr({jsonrpc:si(Dre),id:kG,...Wv.shape}).strict(),aMe=Fr({jsonrpc:si(Dre),...O1.shape}).strict(),dge=Fr({jsonrpc:si(Dre),id:kG,result:Vv}).strict(),pge=Fr({jsonrpc:si(Dre),id:kG.optional(),error:Fr({code:Gs().int(),message:$t(),data:Dl().optional()})}).strict(),pB=bc([sMe,aMe,dge,pge]),vpn=bc([dge,pge]),cMe=Vv.strict(),Bct=D1.extend({requestId:kG.optional(),reason:$t().optional()}),lMe=O1.extend({method:si("notifications/cancelled"),params:Bct}),Uct=Fr({src:$t(),mimeType:$t().optional(),sizes:Go($t()).optional(),theme:Bu(["light","dark"]).optional()}),xG=Fr({icons:Go(Uct).optional()}),t$=Fr({name:$t(),title:$t().optional()}),fge=t$.extend({...t$.shape,...xG.shape,version:$t(),websiteUrl:$t().optional(),description:$t().optional()}),x$s=$L(Fr({applyDefaults:kc().optional()}),qv),T$s=hz(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,$L(Fr({form:x$s.optional(),url:qv.optional()}),qv.optional())),zct=nu({list:qv.optional(),cancel:qv.optional(),requests:nu({sampling:nu({createMessage:qv.optional()}).optional(),elicitation:nu({create:qv.optional()}).optional()}).optional()}),$ct=nu({list:qv.optional(),cancel:qv.optional(),requests:nu({tools:nu({call:qv.optional()}).optional()}).optional()}),qct=Fr({experimental:cc($t(),qv).optional(),sampling:Fr({context:qv.optional(),tools:qv.optional()}).optional(),elicitation:T$s.optional(),roots:Fr({listChanged:kc().optional()}).optional(),tasks:zct.optional(),extensions:cc($t(),qv).optional()}),Wct=zk.extend({protocolVersion:$t(),capabilities:qct,clientInfo:fge}),uMe=Wv.extend({method:si("initialize"),params:Wct}),dMe=Fr({experimental:cc($t(),qv).optional(),logging:qv.optional(),completions:qv.optional(),prompts:Fr({listChanged:kc().optional()}).optional(),resources:Fr({subscribe:kc().optional(),listChanged:kc().optional()}).optional(),tools:Fr({listChanged:kc().optional()}).optional(),tasks:$ct.optional(),extensions:cc($t(),qv).optional()}),Vct=Vv.extend({protocolVersion:$t(),capabilities:dMe,serverInfo:fge,instructions:$t().optional()}),pMe=O1.extend({method:si("notifications/initialized"),params:D1.optional()}),Hct=Wv.extend({method:si("server/discover"),params:zk.optional()}),Mre=Vv.extend({supportedVersions:Go($t()),capabilities:dMe,instructions:$t().optional()}),fMe=Wv.extend({method:si("ping"),params:zk.optional()}),Gct=Fr({progress:Gs(),total:xl(Gs()),message:xl($t())}),Jct=Fr({...D1.shape,...Gct.shape,progressToken:nMe}),mMe=O1.extend({method:si("notifications/progress"),params:Jct}),Kct=zk.extend({cursor:rMe.optional()}),TG=Wv.extend({params:Kct.optional()}),IG=Vv.extend({nextCursor:rMe.optional()}),hMe=Fr({uri:$t(),mimeType:xl($t()),_meta:cc($t(),Dl()).optional()}),gMe=hMe.extend({text:$t()}),bpn=$t().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),_Me=hMe.extend({blob:bpn}),CG=Bu(["user","assistant"]),o$=Fr({audience:Go(CG).optional(),priority:Gs().min(0).max(1).optional(),lastModified:jO.datetime({offset:!0}).optional()}),yMe=Fr({...t$.shape,...xG.shape,uri:$t(),description:xl($t()),mimeType:xl($t()),size:xl(Gs()),annotations:o$.optional(),_meta:xl(nu({}))}),Zct=Fr({...t$.shape,...xG.shape,uriTemplate:$t(),description:xl($t()),mimeType:xl($t()),annotations:o$.optional(),_meta:xl(nu({}))}),Yct=TG.extend({method:si("resources/list")}),Xct=IG.extend({resources:Go(yMe)}),Qct=TG.extend({method:si("resources/templates/list")}),elt=IG.extend({resourceTemplates:Go(Zct)}),mge=zk.extend({uri:$t()}),tlt=mge,nlt=Wv.extend({method:si("resources/read"),params:tlt}),rlt=Vv.extend({contents:Go(bc([gMe,_Me]))}),olt=O1.extend({method:si("notifications/resources/list_changed"),params:D1.optional()}),ilt=mge,slt=Wv.extend({method:si("resources/subscribe"),params:ilt}),alt=mge,clt=Wv.extend({method:si("resources/unsubscribe"),params:alt}),vMe=Fr({toolsListChanged:kc().optional(),promptsListChanged:kc().optional(),resourcesListChanged:kc().optional(),resourceSubscriptions:Go($t()).optional()}),llt=zk.extend({notifications:vMe}),ult=Wv.extend({method:si("subscriptions/listen"),params:llt}),dlt=D1.extend({notifications:vMe}),plt=O1.extend({method:si("notifications/subscriptions/acknowledged"),params:dlt}),flt=iMe.extend({[tMe]:kG}),mlt=Vv.extend({_meta:flt}),hlt=D1.extend({uri:$t()}),glt=O1.extend({method:si("notifications/resources/updated"),params:hlt}),_lt=Fr({name:$t(),description:xl($t()),required:xl(kc())}),ylt=Fr({...t$.shape,...xG.shape,description:xl($t()),arguments:xl(Go(_lt)),_meta:xl(nu({}))}),vlt=TG.extend({method:si("prompts/list")}),blt=IG.extend({prompts:Go(ylt)}),Slt=zk.extend({name:$t(),arguments:cc($t(),$t()).optional()}),wlt=Wv.extend({method:si("prompts/get"),params:Slt}),hge=Fr({type:si("text"),text:$t(),annotations:o$.optional(),_meta:cc($t(),Dl()).optional()}),gge=Fr({type:si("image"),data:bpn,mimeType:$t(),annotations:o$.optional(),_meta:cc($t(),Dl()).optional()}),_ge=Fr({type:si("audio"),data:bpn,mimeType:$t(),annotations:o$.optional(),_meta:cc($t(),Dl()).optional()}),klt=Fr({type:si("tool_use"),name:$t(),id:$t(),input:cc($t(),Dl()),_meta:cc($t(),Dl()).optional()}),xlt=Fr({type:si("resource"),resource:bc([gMe,_Me]),annotations:o$.optional(),_meta:cc($t(),Dl()).optional()}),Tlt=yMe.extend({type:si("resource_link")}),yge=bc([hge,gge,_ge,Tlt,xlt]),Ilt=Fr({role:CG,content:yge}),Clt=Vv.extend({description:$t().optional(),messages:Go(Ilt)}),Elt=O1.extend({method:si("notifications/prompts/list_changed"),params:D1.optional()}),Alt=Fr({title:$t().optional(),readOnlyHint:kc().optional(),destructiveHint:kc().optional(),idempotentHint:kc().optional(),openWorldHint:kc().optional()}),Plt=Fr({taskSupport:Bu(["required","optional","forbidden"]).optional()}),bMe=Fr({...t$.shape,...xG.shape,description:$t().optional(),inputSchema:Fr({type:si("object"),properties:cc($t(),wG).optional(),required:Go($t()).optional()}).catchall(Dl()),outputSchema:nu({$schema:$t().optional()}).optional(),annotations:Alt.optional(),execution:Plt.optional(),_meta:cc($t(),Dl()).optional()}),Rlt=TG.extend({method:si("tools/list")}),Dlt=IG.extend({tools:Go(bMe)}),SMe=Vv.extend({content:Go(yge).default([]),structuredContent:Dl().optional(),isError:kc().optional()}),Spn=SMe.or(Vv.extend({toolResult:Dl()})),Olt=Ore.extend({name:$t(),arguments:cc($t(),Dl()).optional()}),Mlt=Wv.extend({method:si("tools/call"),params:Olt}),Nlt=O1.extend({method:si("notifications/tools/list_changed"),params:D1.optional()}),wMe=Fr({autoRefresh:kc().default(!0),debounceMs:Gs().int().nonnegative().default(300)}),kMe=Bu(["debug","info","notice","warning","error","critical","alert","emergency"]),Llt=zk.extend({level:kMe}),Flt=Wv.extend({method:si("logging/setLevel"),params:Llt}),jlt=D1.extend({level:kMe,logger:$t().optional(),data:Dl()}),Blt=O1.extend({method:si("notifications/message"),params:jlt}),Ult=Fr({name:$t().optional()}),zlt=Fr({hints:Go(Ult).optional(),costPriority:Gs().min(0).max(1).optional(),speedPriority:Gs().min(0).max(1).optional(),intelligencePriority:Gs().min(0).max(1).optional()}),$lt=Fr({mode:Bu(["auto","required","none"]).optional()}),qlt=Fr({type:si("tool_result"),toolUseId:$t().describe("The unique identifier for the corresponding tool call."),content:Go(yge),structuredContent:Dl().optional(),isError:kc().optional(),_meta:cc($t(),Dl()).optional()}),Wlt=fV("type",[hge,gge,_ge]),Pre=fV("type",[hge,gge,_ge,klt,qlt]),Vlt=Fr({role:CG,content:bc([Pre,Go(Pre)]),_meta:cc($t(),Dl()).optional()}),Hlt=Ore.extend({messages:Go(Vlt),modelPreferences:zlt.optional(),systemPrompt:$t().optional(),includeContext:Bu(["none","thisServer","allServers"]).optional(),temperature:Gs().optional(),maxTokens:Gs().int(),stopSequences:Go($t()).optional(),metadata:qv.optional(),tools:Go(bMe).optional(),toolChoice:$lt.optional()}),Glt=Wv.extend({method:si("sampling/createMessage"),params:Hlt}),Jlt=Vv.extend({model:$t(),stopReason:xl(Bu(["endTurn","stopSequence","maxTokens"]).or($t())),role:CG,content:Wlt}),Klt=Vv.extend({model:$t(),stopReason:xl(Bu(["endTurn","stopSequence","maxTokens","toolUse"]).or($t())),role:CG,content:bc([Pre,Go(Pre)])}),xMe=Fr({type:si("boolean"),title:$t().optional(),description:$t().optional(),default:kc().optional()}),vge=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),minLength:Gs().optional(),maxLength:Gs().optional(),format:Bu(["email","uri","date","date-time"]).optional(),default:$t().optional()}),bge=Fr({type:Bu(["number","integer"]),title:$t().optional(),description:$t().optional(),minimum:Gs().optional(),maximum:Gs().optional(),default:Gs().optional()}),TMe=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),enum:Go($t()),default:$t().optional()}),IMe=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),oneOf:Go(Fr({const:$t(),title:$t()})),default:$t().optional()}),CMe=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),enum:Go($t()),enumNames:Go($t()).optional(),default:$t().optional()}),Zlt=bc([TMe,IMe]),EMe=Fr({type:si("array"),title:$t().optional(),description:$t().optional(),minItems:Gs().optional(),maxItems:Gs().optional(),items:Fr({type:si("string"),enum:Go($t())}),default:Go($t()).optional()}),AMe=Fr({type:si("array"),title:$t().optional(),description:$t().optional(),minItems:Gs().optional(),maxItems:Gs().optional(),items:Fr({anyOf:Go(Fr({const:$t(),title:$t()}))}),default:Go($t()).optional()}),Ylt=bc([EMe,AMe]),Xlt=bc([CMe,Zlt,Ylt]),PMe=bc([Xlt,xMe,vge,bge]),Sge=Ore.extend({mode:si("form").optional(),message:$t(),requestedSchema:Fr({type:si("object"),properties:cc($t(),PMe),required:Go($t()).optional()}).catchall(Dl())}),Qlt=Ore.extend({mode:si("url"),message:$t(),elicitationId:$t(),url:$t().url()}),eut=bc([Sge,Qlt]),tut=Wv.extend({method:si("elicitation/create"),params:eut}),nut=D1.extend({elicitationId:$t()}),rut=O1.extend({method:si("notifications/elicitation/complete"),params:nut}),out=Vv.extend({action:Bu(["accept","decline","cancel"]),content:hz(e=>e===null?void 0:e,cc($t(),bc([$t(),Gs(),kc(),Go($t())])).optional())}),iut=Fr({type:si("ref/resource"),uri:$t()}),sut=Fr({type:si("ref/prompt"),name:$t()}),aut=zk.extend({ref:bc([sut,iut]),argument:Fr({name:$t(),value:$t()}),context:Fr({arguments:cc($t(),$t()).optional()}).optional()}),cut=Wv.extend({method:si("completion/complete"),params:aut}),lut=Vv.extend({completion:nu({values:Go($t()).max(100),total:xl(Gs().int()),hasMore:xl(kc())})}),uut=Fr({uri:$t().startsWith("file://"),name:$t().optional(),_meta:cc($t(),Dl()).optional()}),dut=Wv.extend({method:si("roots/list"),params:zk.optional()}),put=Vv.extend({roots:Go(uut)}),fut=O1.extend({method:si("notifications/roots/list_changed"),params:D1.optional()}),wpn=nu({ttl:Gs().optional(),pollInterval:Gs().optional()}),mut=Bu(["working","input_required","completed","failed","cancelled"]),EG=Fr({taskId:$t(),status:mut,ttl:bc([Gs(),Bj()]),createdAt:$t(),lastUpdatedAt:$t(),pollInterval:xl(Gs()),statusMessage:xl($t())}),kpn=Vv.extend({task:EG}),hut=D1.merge(EG),xpn=O1.extend({method:si("notifications/tasks/status"),params:hut}),Tpn=Wv.extend({method:si("tasks/get"),params:zk.extend({taskId:$t()})}),Ipn=Vv.merge(EG),Cpn=Wv.extend({method:si("tasks/result"),params:zk.extend({taskId:$t()})}),Epn=Vv.loose(),Apn=TG.extend({method:si("tasks/list")}),Ppn=IG.extend({tasks:Go(EG)}),Rpn=Wv.extend({method:si("tasks/cancel"),params:zk.extend({taskId:$t()})}),Dpn=Vv.merge(EG),Opn=bc([fMe,uMe,Hct,cut,Flt,wlt,vlt,Yct,Qct,nlt,slt,clt,ult,Mlt,Rlt]),Mpn=bc([lMe,mMe,pMe,fut]),Npn=bc([cMe,Jlt,Klt,out,put]),Lpn=bc([fMe,Glt,tut,dut]),Fpn=bc([lMe,mMe,Blt,glt,olt,Nlt,Elt,plt,rut]),jpn=bc([cMe,Vct,Mre,lut,Clt,blt,Xct,elt,rlt,SMe,Dlt,mlt]),Uk=ape().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Eqt.custom,message:"URL must be parseable",fatal:!0}),KCe}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),RMe=nu({resource:$t().url(),authorization_servers:Go(Uk).optional(),jwks_uri:$t().url().optional(),scopes_supported:Go($t()).optional(),bearer_methods_supported:Go($t()).optional(),resource_signing_alg_values_supported:Go($t()).optional(),resource_name:$t().optional(),resource_documentation:$t().optional(),resource_policy_uri:$t().url().optional(),resource_tos_uri:$t().url().optional(),tls_client_certificate_bound_access_tokens:kc().optional(),authorization_details_types_supported:Go($t()).optional(),dpop_signing_alg_values_supported:Go($t()).optional(),dpop_bound_access_tokens_required:kc().optional()}),wge=nu({issuer:$t(),authorization_endpoint:Uk,token_endpoint:Uk,registration_endpoint:Uk.optional(),scopes_supported:Go($t()).optional(),response_types_supported:Go($t()),response_modes_supported:Go($t()).optional(),grant_types_supported:Go($t()).optional(),token_endpoint_auth_methods_supported:Go($t()).optional(),token_endpoint_auth_signing_alg_values_supported:Go($t()).optional(),service_documentation:Uk.optional(),revocation_endpoint:Uk.optional(),revocation_endpoint_auth_methods_supported:Go($t()).optional(),revocation_endpoint_auth_signing_alg_values_supported:Go($t()).optional(),introspection_endpoint:$t().optional(),introspection_endpoint_auth_methods_supported:Go($t()).optional(),introspection_endpoint_auth_signing_alg_values_supported:Go($t()).optional(),code_challenge_methods_supported:Go($t()).optional(),client_id_metadata_document_supported:kc().optional(),authorization_response_iss_parameter_supported:kc().optional().catch(void 0)}),gut=nu({issuer:$t(),authorization_endpoint:Uk,token_endpoint:Uk,userinfo_endpoint:Uk.optional(),jwks_uri:Uk,registration_endpoint:Uk.optional(),scopes_supported:Go($t()).optional(),response_types_supported:Go($t()),response_modes_supported:Go($t()).optional(),grant_types_supported:Go($t()).optional(),acr_values_supported:Go($t()).optional(),subject_types_supported:Go($t()),id_token_signing_alg_values_supported:Go($t()),id_token_encryption_alg_values_supported:Go($t()).optional(),id_token_encryption_enc_values_supported:Go($t()).optional(),userinfo_signing_alg_values_supported:Go($t()).optional(),userinfo_encryption_alg_values_supported:Go($t()).optional(),userinfo_encryption_enc_values_supported:Go($t()).optional(),request_object_signing_alg_values_supported:Go($t()).optional(),request_object_encryption_alg_values_supported:Go($t()).optional(),request_object_encryption_enc_values_supported:Go($t()).optional(),token_endpoint_auth_methods_supported:Go($t()).optional(),token_endpoint_auth_signing_alg_values_supported:Go($t()).optional(),display_values_supported:Go($t()).optional(),claim_types_supported:Go($t()).optional(),claims_supported:Go($t()).optional(),service_documentation:$t().optional(),claims_locales_supported:Go($t()).optional(),ui_locales_supported:Go($t()).optional(),claims_parameter_supported:kc().optional(),request_parameter_supported:kc().optional(),request_uri_parameter_supported:kc().optional(),require_request_uri_registration:kc().optional(),op_policy_uri:Uk.optional(),op_tos_uri:Uk.optional(),client_id_metadata_document_supported:kc().optional(),authorization_response_iss_parameter_supported:kc().optional().catch(void 0)}),DMe=Fr({...gut.shape,...wge.pick({code_challenge_methods_supported:!0}).shape}),OMe=Fr({access_token:$t(),id_token:$t().optional(),token_type:$t(),expires_in:qEe.number().optional(),scope:$t().optional(),refresh_token:$t().optional()}).strip(),_ut=Fr({issued_token_type:si("urn:ietf:params:oauth:token-type:id-jag"),access_token:$t(),token_type:$t().optional(),expires_in:Gs().optional(),scope:$t().optional()}).strip(),MMe=Fr({error:$t(),error_description:$t().optional(),error_uri:$t().optional()}),_pn=Uk.optional().or(si("").transform(()=>{})),yut=Fr({redirect_uris:Go(Uk),token_endpoint_auth_method:$t().optional(),grant_types:Go($t()).optional(),response_types:Go($t()).optional(),application_type:$t().optional(),client_name:$t().optional(),client_uri:Uk.optional(),logo_uri:_pn,scope:$t().optional(),contacts:Go($t()).optional(),tos_uri:_pn,policy_uri:$t().optional(),jwks_uri:Uk.optional(),jwks:sKe().optional(),software_id:$t().optional(),software_version:$t().optional(),software_statement:$t().optional()}).strip(),vut=Fr({client_id:$t(),client_secret:$t().optional(),client_id_issued_at:Gs().optional(),client_secret_expires_at:Gs().optional()}).strip(),NMe=yut.merge(vut),Bpn=Fr({error:$t(),error_description:$t().optional()}).strip(),Upn=Fr({token:$t(),token_type_hint:$t().optional()}).strip()});var NYr=Y(()=>{TYr()});function Lre(e,t){let n=new Set,o=t;for(;typeof o=="function";){let s=o.mcpBrand;Object.prototype.hasOwnProperty.call(o,"mcpBrand")&&typeof s=="string"&&n.add(s),o=Object.getPrototypeOf(o)}n.size!==0&&Object.defineProperty(e,Vpn,{value:n,enumerable:!1,configurable:!0})}function C2(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,Vpn)){let n=t[Vpn];if(n&&typeof n.has=="function"&&n.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}function GYr(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function JYr({requestedResource:e,configuredResource:t}){let n=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(n.origin!==o.origin||n.pathname.length<o.pathname.length)return!1;let s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",a=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return s.startsWith(a)}function a$(e){return e>=KYr}function Ypn(e){return e.filter(t=>!a$(t))}function $Me(e){return e.filter(t=>a$(t))}function ZYr(e){let t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(e.content?.some(n=>n.type==="text")??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}function I$s(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||YYr.some(t=>t in e)?e:{...e,content:[]}}function C$s(){let e=mV(()=>bc([$t(),Gs(),kc(),Bj(),cc($t(),e),Go(e)])),t=cc($t(),e),n=bc([$t(),Gs().int()]),o=$t(),s=Fr({ttl:Gs().optional()}),a=Fr({taskId:$t()}),l=nu({progressToken:n.optional(),"io.modelcontextprotocol/related-task":a.optional()}),u=Fr({_meta:l.optional()}),f=u.extend({task:s.optional()}),g=Fr({method:$t(),params:u.loose().optional()}),_=Fr({_meta:l.optional()}),b=Fr({method:$t(),params:_.loose().optional()}),w=nu({_meta:l.optional()}),T=bc([$t(),Gs().int()]),I=w.strict(),E=_.extend({requestId:T.optional(),reason:$t().optional()}),R=b.extend({method:si("notifications/cancelled"),params:E}),L=Fr({src:$t(),mimeType:$t().optional(),sizes:Go($t()).optional(),theme:Bu(["light","dark"]).optional()}),U=Fr({icons:Go(L).optional()}),B=Fr({name:$t(),title:$t().optional()}),z=B.extend({...B.shape,...U.shape,version:$t(),websiteUrl:$t().optional(),description:$t().optional()}),$=$L(Fr({applyDefaults:kc().optional()}),t),J=hz(Xv=>Xv&&typeof Xv=="object"&&!Array.isArray(Xv)&&Object.keys(Xv).length===0?{form:{}}:Xv,$L(Fr({form:$.optional(),url:t.optional()}),t.optional())),q=nu({list:t.optional(),cancel:t.optional(),requests:nu({sampling:nu({createMessage:t.optional()}).optional(),elicitation:nu({create:t.optional()}).optional()}).optional()}),ie=nu({list:t.optional(),cancel:t.optional(),requests:nu({tools:nu({call:t.optional()}).optional()}).optional()}),ae=Fr({experimental:cc($t(),t).optional(),sampling:Fr({context:t.optional(),tools:t.optional()}).optional(),elicitation:J.optional(),roots:Fr({listChanged:kc().optional()}).optional(),tasks:q.optional(),extensions:cc($t(),t).optional()}),Ce=u.extend({protocolVersion:$t(),capabilities:ae,clientInfo:z}),pe=g.extend({method:si("initialize"),params:Ce}),ze=Fr({experimental:cc($t(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:Fr({listChanged:kc().optional()}).optional(),resources:Fr({subscribe:kc().optional(),listChanged:kc().optional()}).optional(),tools:Fr({listChanged:kc().optional()}).optional(),tasks:ie.optional(),extensions:cc($t(),t).optional()}),rt=w.extend({protocolVersion:$t(),capabilities:ze,serverInfo:z,instructions:$t().optional()}),Pe=b.extend({method:si("notifications/initialized"),params:_.optional()}),Tt=g.extend({method:si("ping"),params:u.optional()}),Ye=Fr({progress:Gs(),total:xl(Gs()),message:xl($t())}),Fe=Fr({..._.shape,...Ye.shape,progressToken:n}),St=b.extend({method:si("notifications/progress"),params:Fe}),kt=u.extend({cursor:o.optional()}),st=g.extend({params:kt.optional()}),$e=w.extend({nextCursor:o.optional()}),jt=Fr({uri:$t(),mimeType:xl($t()),_meta:cc($t(),Dl()).optional()}),Je=jt.extend({text:$t()}),Xe=$t().refine(Xv=>{try{return atob(Xv),!0}catch{return!1}},{message:"Invalid Base64 string"}),_t=jt.extend({blob:Xe}),Dt=Bu(["user","assistant"]),gn=Fr({audience:Go(Dt).optional(),priority:Gs().min(0).max(1).optional(),lastModified:jO.datetime({offset:!0}).optional()}),cn=Fr({...B.shape,...U.shape,uri:$t(),description:xl($t()),mimeType:xl($t()),size:xl(Gs()),annotations:gn.optional(),_meta:xl(nu({}))}),Fn=Fr({...B.shape,...U.shape,uriTemplate:$t(),description:xl($t()),mimeType:xl($t()),annotations:gn.optional(),_meta:xl(nu({}))}),on=st.extend({method:si("resources/list")}),dt=$e.extend({resources:Go(cn)}),we=st.extend({method:si("resources/templates/list")}),_e=$e.extend({resourceTemplates:Go(Fn)}),Pt=u.extend({uri:$t()}),ut=Pt,Mn=g.extend({method:si("resources/read"),params:ut}),Dr=w.extend({contents:Go(bc([Je,_t]))}),gr=b.extend({method:si("notifications/resources/list_changed"),params:_.optional()}),eo=Pt,to=g.extend({method:si("resources/subscribe"),params:eo}),oo=Pt,ro=g.extend({method:si("resources/unsubscribe"),params:oo}),Ji=_.extend({uri:$t()}),pi=b.extend({method:si("notifications/resources/updated"),params:Ji}),Wi=Fr({name:$t(),description:xl($t()),required:xl(kc())}),Ii=Fr({...B.shape,...U.shape,description:xl($t()),arguments:xl(Go(Wi)),_meta:xl(nu({}))}),Rs=st.extend({method:si("prompts/list")}),ht=$e.extend({prompts:Go(Ii)}),mr=u.extend({name:$t(),arguments:cc($t(),$t()).optional()}),mi=g.extend({method:si("prompts/get"),params:mr}),Ar=Fr({type:si("text"),text:$t(),annotations:gn.optional(),_meta:cc($t(),Dl()).optional()}),hi=Fr({type:si("image"),data:Xe,mimeType:$t(),annotations:gn.optional(),_meta:cc($t(),Dl()).optional()}),Js=Fr({type:si("audio"),data:Xe,mimeType:$t(),annotations:gn.optional(),_meta:cc($t(),Dl()).optional()}),qa=Fr({type:si("tool_use"),name:$t(),id:$t(),input:cc($t(),Dl()),_meta:cc($t(),Dl()).optional()}),li=Fr({type:si("resource"),resource:bc([Je,_t]),annotations:gn.optional(),_meta:cc($t(),Dl()).optional()}),oa=cn.extend({type:si("resource_link")}),Fs=bc([Ar,hi,Js,oa,li]),Qo=Fr({role:Dt,content:Fs}),gi=w.extend({description:$t().optional(),messages:Go(Qo)}),kn=b.extend({method:si("notifications/prompts/list_changed"),params:_.optional()}),Nn=Fr({title:$t().optional(),readOnlyHint:kc().optional(),destructiveHint:kc().optional(),idempotentHint:kc().optional(),openWorldHint:kc().optional()}),Ur=Fr({taskSupport:Bu(["required","optional","forbidden"]).optional()}),Vo=Fr({...B.shape,...U.shape,description:$t().optional(),inputSchema:Fr({type:si("object"),properties:cc($t(),e).optional(),required:Go($t()).optional()}).catchall(Dl()),outputSchema:Fr({type:si("object"),properties:cc($t(),e).optional(),required:Go($t()).optional()}).catchall(Dl()).optional(),annotations:Nn.optional(),execution:Ur.optional(),_meta:cc($t(),Dl()).optional()}),qe=st.extend({method:si("tools/list")}),Kt=$e.extend({tools:Go(Vo)}),Jt=w.extend({content:Go(Fs),structuredContent:cc($t(),Dl()).optional(),isError:kc().optional()}),en=f.extend({name:$t(),arguments:cc($t(),Dl()).optional()}),qn=g.extend({method:si("tools/call"),params:en}),Yr=b.extend({method:si("notifications/tools/list_changed"),params:_.optional()}),ei=Bu(["debug","info","notice","warning","error","critical","alert","emergency"]),ki=u.extend({level:ei}),ca=g.extend({method:si("logging/setLevel"),params:ki}),ks=_.extend({level:ei,logger:$t().optional(),data:Dl()}),Ud=b.extend({method:si("notifications/message"),params:ks}),zd=Fr({name:$t().optional()}),Bm=Fr({hints:Go(zd).optional(),costPriority:Gs().min(0).max(1).optional(),speedPriority:Gs().min(0).max(1).optional(),intelligencePriority:Gs().min(0).max(1).optional()}),Xf=Fr({mode:Bu(["auto","required","none"]).optional()}),kf=Fr({type:si("tool_result"),toolUseId:$t().describe("The unique identifier for the corresponding tool call."),content:Go(Fs),structuredContent:Fr({}).loose().optional(),isError:kc().optional(),_meta:cc($t(),Dl()).optional()}),qi=fV("type",[Ar,hi,Js]),Tm=fV("type",[Ar,hi,Js,qa,kf]),ev=Fr({role:Dt,content:bc([Tm,Go(Tm)]),_meta:cc($t(),Dl()).optional()}),E0=f.extend({messages:Go(ev),modelPreferences:Bm.optional(),systemPrompt:$t().optional(),includeContext:Bu(["none","thisServer","allServers"]).optional(),temperature:Gs().optional(),maxTokens:Gs().int(),stopSequences:Go($t()).optional(),metadata:t.optional(),tools:Go(Vo).optional(),toolChoice:Xf.optional()}),tv=g.extend({method:si("sampling/createMessage"),params:E0}),z_=w.extend({model:$t(),stopReason:xl(Bu(["endTurn","stopSequence","maxTokens"]).or($t())),role:Dt,content:qi}),Yv=w.extend({model:$t(),stopReason:xl(Bu(["endTurn","stopSequence","maxTokens","toolUse"]).or($t())),role:Dt,content:bc([Tm,Go(Tm)])}),Lw=Fr({type:si("boolean"),title:$t().optional(),description:$t().optional(),default:kc().optional()}),Tu=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),minLength:Gs().optional(),maxLength:Gs().optional(),format:Bu(["email","uri","date","date-time"]).optional(),default:$t().optional()}),t0=Fr({type:Bu(["number","integer"]),title:$t().optional(),description:$t().optional(),minimum:Gs().optional(),maximum:Gs().optional(),default:Gs().optional()}),Ub=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),enum:Go($t()),default:$t().optional()}),ta=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),oneOf:Go(Fr({const:$t(),title:$t()})),default:$t().optional()}),af=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),enum:Go($t()),enumNames:Go($t()).optional(),default:$t().optional()}),lP=bc([Ub,ta]),tE=Fr({type:si("array"),title:$t().optional(),description:$t().optional(),minItems:Gs().optional(),maxItems:Gs().optional(),items:Fr({type:si("string"),enum:Go($t())}),default:Go($t()).optional()}),IS=Fr({type:si("array"),title:$t().optional(),description:$t().optional(),minItems:Gs().optional(),maxItems:Gs().optional(),items:Fr({anyOf:Go(Fr({const:$t(),title:$t()}))}),default:Go($t()).optional()}),Fw=bc([tE,IS]),Vs=bc([af,lP,Fw]),Iu=bc([Vs,Lw,Tu,t0]),bs=f.extend({mode:si("form").optional(),message:$t(),requestedSchema:Fr({type:si("object"),properties:cc($t(),Iu),required:Go($t()).optional()}).catchall(Dl())}),A0=f.extend({mode:si("url"),message:$t(),elicitationId:$t(),url:$t().url()}),ri=bc([bs,A0]),la=g.extend({method:si("elicitation/create"),params:ri}),ul=_.extend({elicitationId:$t()}),py=b.extend({method:si("notifications/elicitation/complete"),params:ul}),X0=w.extend({action:Bu(["accept","decline","cancel"]),content:hz(Xv=>Xv===null?void 0:Xv,cc($t(),bc([$t(),Gs(),kc(),Go($t())])).optional())}),jw=Fr({type:si("ref/resource"),uri:$t()}),Ds=Fr({type:si("ref/prompt"),name:$t()}),e_=u.extend({ref:bc([Ds,jw]),argument:Fr({name:$t(),value:$t()}),context:Fr({arguments:cc($t(),$t()).optional()}).optional()}),nE=g.extend({method:si("completion/complete"),params:e_}),$_=w.extend({completion:nu({values:Go($t()).max(100),total:xl(Gs().int()),hasMore:xl(kc())})}),Va=Fr({uri:$t().startsWith("file://"),name:$t().optional(),_meta:cc($t(),Dl()).optional()}),lp=g.extend({method:si("roots/list"),params:u.optional()}),Eh=w.extend({roots:Go(Va)}),rE=b.extend({method:si("notifications/roots/list_changed"),params:_.optional()}),cf=nu({ttl:Gs().optional(),pollInterval:Gs().optional()}),t_=Bu(["working","input_required","completed","failed","cancelled"]),q_=Fr({taskId:$t(),status:t_,ttl:bc([Gs(),Bj()]),createdAt:$t(),lastUpdatedAt:$t(),pollInterval:xl(Gs()),statusMessage:xl($t())}),zb=w.extend({task:q_}),Yl=_.merge(q_),dh=b.extend({method:si("notifications/tasks/status"),params:Yl}),X1=g.extend({method:si("tasks/get"),params:u.extend({taskId:$t()})}),nD=w.merge(q_),ox=g.extend({method:si("tasks/result"),params:u.extend({taskId:$t()})}),eZ=w.loose(),Sd=st.extend({method:si("tasks/list")}),Ah=$e.extend({tasks:Go(q_)}),U8=g.extend({method:si("tasks/cancel"),params:u.extend({taskId:$t()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:o,TaskMetadataSchema:s,RelatedTaskMetadataSchema:a,RequestMetaSchema:l,BaseRequestParamsSchema:u,TaskAugmentedRequestParamsSchema:f,RequestSchema:g,NotificationsParamsSchema:_,NotificationSchema:b,ResultSchema:w,RequestIdSchema:T,EmptyResultSchema:I,CancelledNotificationParamsSchema:E,CancelledNotificationSchema:R,IconSchema:L,IconsSchema:U,BaseMetadataSchema:B,ImplementationSchema:z,ClientTasksCapabilitySchema:q,ServerTasksCapabilitySchema:ie,ClientCapabilitiesSchema:ae,InitializeRequestParamsSchema:Ce,InitializeRequestSchema:pe,ServerCapabilitiesSchema:ze,InitializeResultSchema:rt,InitializedNotificationSchema:Pe,PingRequestSchema:Tt,ProgressSchema:Ye,ProgressNotificationParamsSchema:Fe,ProgressNotificationSchema:St,PaginatedRequestParamsSchema:kt,PaginatedRequestSchema:st,PaginatedResultSchema:$e,ResourceContentsSchema:jt,TextResourceContentsSchema:Je,BlobResourceContentsSchema:_t,RoleSchema:Dt,AnnotationsSchema:gn,ResourceSchema:cn,ResourceTemplateSchema:Fn,ListResourcesRequestSchema:on,ListResourcesResultSchema:dt,ListResourceTemplatesRequestSchema:we,ListResourceTemplatesResultSchema:_e,ResourceRequestParamsSchema:Pt,ReadResourceRequestParamsSchema:ut,ReadResourceRequestSchema:Mn,ReadResourceResultSchema:Dr,ResourceListChangedNotificationSchema:gr,SubscribeRequestParamsSchema:eo,SubscribeRequestSchema:to,UnsubscribeRequestParamsSchema:oo,UnsubscribeRequestSchema:ro,ResourceUpdatedNotificationParamsSchema:Ji,ResourceUpdatedNotificationSchema:pi,PromptArgumentSchema:Wi,PromptSchema:Ii,ListPromptsRequestSchema:Rs,ListPromptsResultSchema:ht,GetPromptRequestParamsSchema:mr,GetPromptRequestSchema:mi,TextContentSchema:Ar,ImageContentSchema:hi,AudioContentSchema:Js,ToolUseContentSchema:qa,EmbeddedResourceSchema:li,ResourceLinkSchema:oa,ContentBlockSchema:Fs,PromptMessageSchema:Qo,GetPromptResultSchema:gi,PromptListChangedNotificationSchema:kn,ToolAnnotationsSchema:Nn,ToolExecutionSchema:Ur,ToolSchema:Vo,ListToolsRequestSchema:qe,ListToolsResultSchema:Kt,CallToolResultSchema:Jt,CallToolRequestParamsSchema:en,CallToolRequestSchema:qn,ToolListChangedNotificationSchema:Yr,LoggingLevelSchema:ei,SetLevelRequestParamsSchema:ki,SetLevelRequestSchema:ca,LoggingMessageNotificationParamsSchema:ks,LoggingMessageNotificationSchema:Ud,ModelHintSchema:zd,ModelPreferencesSchema:Bm,ToolChoiceSchema:Xf,ToolResultContentSchema:kf,SamplingContentSchema:qi,SamplingMessageContentBlockSchema:Tm,SamplingMessageSchema:ev,CreateMessageRequestParamsSchema:E0,CreateMessageRequestSchema:tv,CreateMessageResultSchema:z_,CreateMessageResultWithToolsSchema:Yv,BooleanSchemaSchema:Lw,StringSchemaSchema:Tu,NumberSchemaSchema:t0,UntitledSingleSelectEnumSchemaSchema:Ub,TitledSingleSelectEnumSchemaSchema:ta,LegacyTitledEnumSchemaSchema:af,SingleSelectEnumSchemaSchema:lP,UntitledMultiSelectEnumSchemaSchema:tE,TitledMultiSelectEnumSchemaSchema:IS,MultiSelectEnumSchemaSchema:Fw,EnumSchemaSchema:Vs,PrimitiveSchemaDefinitionSchema:Iu,ElicitRequestFormParamsSchema:bs,ElicitRequestURLParamsSchema:A0,ElicitRequestParamsSchema:ri,ElicitRequestSchema:la,ElicitationCompleteNotificationParamsSchema:ul,ElicitationCompleteNotificationSchema:py,ElicitResultSchema:X0,ResourceTemplateReferenceSchema:jw,PromptReferenceSchema:Ds,CompleteRequestParamsSchema:e_,CompleteRequestSchema:nE,CompleteResultSchema:$_,RootSchema:Va,ListRootsRequestSchema:lp,ListRootsResultSchema:Eh,RootsListChangedNotificationSchema:rE,TaskCreationParamsSchema:cf,TaskStatusSchema:t_,TaskSchema:q_,CreateTaskResultSchema:zb,TaskStatusNotificationParamsSchema:Yl,TaskStatusNotificationSchema:dh,GetTaskRequestSchema:X1,GetTaskResultSchema:nD,GetTaskPayloadRequestSchema:ox,GetTaskPayloadResultSchema:eZ,ListTasksRequestSchema:Sd,ListTasksResultSchema:Ah,CancelTaskRequestSchema:U8,CancelTaskResultSchema:w.merge(q_),ClientRequestSchema:bc([Tt,pe,nE,ca,mi,Rs,on,we,Mn,to,ro,qn,qe,X1,ox,Sd,U8]),ClientNotificationSchema:bc([R,St,Pe,rE,dh]),ClientResultSchema:bc([I,z_,Yv,X0,Eh,nD,Ah,zb]),ServerRequestSchema:bc([Tt,tv,la,lp,X1,ox,Sd,U8]),ServerNotificationSchema:bc([R,St,Ud,pi,gr,Yr,kn,dh,py]),ServerResultSchema:bc([I,rt,$_,gi,ht,dt,_e,Dr,Jt,Kt,nD,Ah,zb]),CallToolResultWireSchema:Dl().superRefine((Xv,pse)=>{if(!(typeof Xv!="object"||Xv===null||Array.isArray(Xv)||Xv.content!==void 0)){for(let fse of YYr)if(fse in Xv){pse.addIssue({code:"custom",message:`content is required when the body carries '${fse}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(I$s).pipe(Jt)}}function XYr(){return E$s??=C$s()}function QYr(e){return e.type!=="object"}function LYr(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}function R$s(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(LYr(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let n=kYr(e.$schema)&&e.$recursiveAnchor!==!0,o=r((s,a)=>{if(Array.isArray(s))return s.map(f=>o(f,!1));if(s===null||typeof s!="object"||!a&&LYr(s.$id))return s;let l={},u=!1;for(let[f,g]of Object.entries(s))a?l[f]=o(g,!1):(f==="$ref"||f==="$dynamicRef")&&typeof g=="string"?l[f]=g==="#"?"#/properties/result":g.startsWith("#/")?`#/properties/result${g.slice(1)}`:g:f==="$recursiveRef"&&g==="#"&&n?u=!0:A$s.has(f)?l[f]=g:P$s.has(f)?l[f]=o(g,!0):l[f]=o(g,!1);return u&&("$ref"in l?l.allOf=[...Array.isArray(l.allOf)?l.allOf:[],{$ref:"#/properties/result"}]:l.$ref="#/properties/result"),l},"rewriteRefs");return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}function Xpn(){if(but)return but;let e=XYr();return but={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},but}function nXr(e){return Object.prototype.hasOwnProperty.call(eXr,e)}function rXr(e){return Object.prototype.hasOwnProperty.call(tXr,e)}function O$s(e){return Object.prototype.hasOwnProperty.call(D$s,e)}function M$s(e){return O$s(e)?Xpn().resultSchemas[e]:void 0}function N$s(e){return nXr(e)?Xpn().requestSchemas[e]:void 0}function L$s(e){return rXr(e)?Xpn().notificationSchemas[e]:void 0}function Hpn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Sut(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:"invalid",message:String(n.error)}}function jYr(e){return Hpn(e)&&Hpn(e.outputSchema)&&QYr(e.outputSchema)}function F$s(){let e=mV(()=>bc([$t(),Gs(),kc(),Bj(),cc($t(),e),Go(e)])),t=cc($t(),e),n=bc([$t(),Gs().int()]),o=$t(),s=bc([$t(),Gs().int()]),a=Bu(["user","assistant"]),l=Bu(["debug","info","notice","warning","error","critical","alert","emergency"]),u=$t().refine(Ah=>{try{return atob(Ah),!0}catch{return!1}},{message:"Invalid Base64 string"}),f=Fr({ttl:Gs().optional()}),g=Fr({taskId:$t()}),_=nu({progressToken:n.optional(),"io.modelcontextprotocol/related-task":g.optional()}),b=Fr({_meta:_.optional()}),w=b.extend({task:f.optional()}),T=Fr({_meta:_.optional()}),I=Fr({method:$t(),params:T.loose().optional()}),E=Fr({src:$t(),mimeType:$t().optional(),sizes:Go($t()).optional(),theme:Bu(["light","dark"]).optional()}),R=Fr({icons:Go(E).optional()}),L=Fr({name:$t(),title:$t().optional()}),U=L.extend({...L.shape,...R.shape,version:$t(),websiteUrl:$t().optional(),description:$t().optional()}),B=$L(Fr({applyDefaults:kc().optional()}),t),z=hz(Ah=>Ah&&typeof Ah=="object"&&!Array.isArray(Ah)&&Object.keys(Ah).length===0?{form:{}}:Ah,$L(Fr({form:B.optional(),url:t.optional()}),t.optional())),$=nu({list:t.optional(),cancel:t.optional(),requests:nu({sampling:nu({createMessage:t.optional()}).optional(),elicitation:nu({create:t.optional()}).optional()}).optional()}),J=nu({list:t.optional(),cancel:t.optional(),requests:nu({tools:nu({call:t.optional()}).optional()}).optional()}),q=Fr({experimental:cc($t(),t).optional(),sampling:Fr({context:t.optional(),tools:t.optional()}).optional(),elicitation:z.optional(),roots:Fr({listChanged:kc().optional()}).optional(),tasks:$.optional(),extensions:cc($t(),t).optional()}),ie=Fr({experimental:cc($t(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:Fr({listChanged:kc().optional()}).optional(),resources:Fr({subscribe:kc().optional(),listChanged:kc().optional()}).optional(),tools:Fr({listChanged:kc().optional()}).optional(),tasks:J.optional(),extensions:cc($t(),t).optional()}),ae=Fr({progress:Gs(),total:xl(Gs()),message:xl($t())}),Ce=Fr({...T.shape,...ae.shape,progressToken:n}),pe=I.extend({method:si("notifications/progress"),params:Ce}),ze=T.extend({level:l,logger:$t().optional(),data:Dl()}),rt=I.extend({method:si("notifications/message"),params:ze}),Pe=Fr({uri:$t(),mimeType:xl($t()),_meta:cc($t(),Dl()).optional()}),Tt=Pe.extend({text:$t()}),Ye=Pe.extend({blob:u}),Fe=Fr({audience:Go(a).optional(),priority:Gs().min(0).max(1).optional(),lastModified:jO.datetime({offset:!0}).optional()}),St=Fr({...L.shape,...R.shape,uri:$t(),description:xl($t()),mimeType:xl($t()),size:xl(Gs()),annotations:Fe.optional(),_meta:xl(nu({}))}),kt=Fr({...L.shape,...R.shape,uriTemplate:$t(),description:xl($t()),mimeType:xl($t()),annotations:Fe.optional(),_meta:xl(nu({}))}),st=I.extend({method:si("notifications/resources/list_changed"),params:T.optional()}),$e=T.extend({uri:$t()}),jt=I.extend({method:si("notifications/resources/updated"),params:$e}),Je=Fr({name:$t(),description:xl($t()),required:xl(kc())}),Xe=Fr({...L.shape,...R.shape,description:xl($t()),arguments:xl(Go(Je)),_meta:xl(nu({}))}),_t=I.extend({method:si("notifications/prompts/list_changed"),params:T.optional()}),Dt=Fr({type:si("text"),text:$t(),annotations:Fe.optional(),_meta:cc($t(),Dl()).optional()}),gn=Fr({type:si("image"),data:u,mimeType:$t(),annotations:Fe.optional(),_meta:cc($t(),Dl()).optional()}),cn=Fr({type:si("audio"),data:u,mimeType:$t(),annotations:Fe.optional(),_meta:cc($t(),Dl()).optional()}),Fn=Fr({type:si("tool_use"),name:$t(),id:$t(),input:cc($t(),Dl()),_meta:cc($t(),Dl()).optional()}),on=Fr({type:si("resource"),resource:bc([Tt,Ye]),annotations:Fe.optional(),_meta:cc($t(),Dl()).optional()}),dt=St.extend({type:si("resource_link")}),we=bc([Dt,gn,cn,dt,on]),_e=Fr({role:a,content:we}),Pt=Fr({title:$t().optional(),readOnlyHint:kc().optional(),destructiveHint:kc().optional(),idempotentHint:kc().optional(),openWorldHint:kc().optional()}),ut=I.extend({method:si("notifications/tools/list_changed"),params:T.optional()}),Mn=Fr({name:$t().optional()}),Dr=Fr({hints:Go(Mn).optional(),costPriority:Gs().min(0).max(1).optional(),speedPriority:Gs().min(0).max(1).optional(),intelligencePriority:Gs().min(0).max(1).optional()}),gr=Fr({mode:Bu(["auto","required","none"]).optional()}),eo=Fr({type:si("boolean"),title:$t().optional(),description:$t().optional(),default:kc().optional()}),to=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),minLength:Gs().optional(),maxLength:Gs().optional(),format:Bu(["email","uri","date","date-time"]).optional(),default:$t().optional()}),oo=Fr({type:Bu(["number","integer"]),title:$t().optional(),description:$t().optional(),minimum:Gs().optional(),maximum:Gs().optional(),default:Gs().optional()}),ro=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),enum:Go($t()),default:$t().optional()}),Ji=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),oneOf:Go(Fr({const:$t(),title:$t()})),default:$t().optional()}),pi=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),enum:Go($t()),enumNames:Go($t()).optional(),default:$t().optional()}),Wi=bc([ro,Ji]),Ii=Fr({type:si("array"),title:$t().optional(),description:$t().optional(),minItems:Gs().optional(),maxItems:Gs().optional(),items:Fr({type:si("string"),enum:Go($t())}),default:Go($t()).optional()}),Rs=Fr({type:si("array"),title:$t().optional(),description:$t().optional(),minItems:Gs().optional(),maxItems:Gs().optional(),items:Fr({anyOf:Go(Fr({const:$t(),title:$t()}))}),default:Go($t()).optional()}),ht=bc([Ii,Rs]),mr=bc([pi,Wi,ht]),mi=bc([mr,eo,to,oo]),Ar=w.extend({mode:si("form").optional(),message:$t(),requestedSchema:Fr({type:si("object"),properties:cc($t(),mi),required:Go($t()).optional()}).catchall(Dl())}),hi=Fr({type:si("ref/resource"),uri:$t()}),Js=Fr({type:si("ref/prompt"),name:$t()}),qa=Fr({uri:$t().startsWith("file://"),name:$t().optional(),_meta:cc($t(),Dl()).optional()}),li=q.shape,oa=Fr({experimental:li.experimental,sampling:li.sampling,elicitation:li.elicitation,roots:li.roots,extensions:li.extensions}),Fs=ie.shape,Qo=Fr({experimental:Fs.experimental,logging:Fs.logging,completions:Fs.completions,prompts:Fs.prompts,resources:Fs.resources,tools:Fs.tools,extensions:Fs.extensions}),gi=nu({progressToken:n.optional(),[n$]:$t(),[lge]:U.optional(),[Rre]:oa,[uge]:l.optional()}),kn=Fr({...L.shape,...R.shape,description:$t().optional(),inputSchema:nu({$schema:$t().optional(),type:si("object")}),outputSchema:nu({$schema:$t().optional()}).optional(),annotations:Pt.optional(),_meta:cc($t(),Dl()).optional()}),Nn=Fr({type:si("tool_result"),toolUseId:$t(),content:Go(we),structuredContent:Dl().optional(),isError:kc().optional(),_meta:cc($t(),Dl()).optional()}),Ur=bc([Dt,gn,cn,Fn,Nn]),Vo=Fr({role:a,content:bc([Ur,Go(Ur)]),_meta:cc($t(),Dl()).optional()}),qe=$t(),Kt=nu({[r$]:U.optional().catch(void 0)}),Jt=Kt.optional();function en(Ah){return nu({_meta:Jt,resultType:qe.default("complete"),...Ah})}r(en,"wireResult");let qn=en({}),Yr=en({nextCursor:o.optional()}),ei=en({content:Go(we),structuredContent:Dl().optional(),isError:kc().optional()}),ki=en({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),tools:Go(kn),nextCursor:o.optional()}),ca=en({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),prompts:Go(Xe),nextCursor:o.optional()}),ks=en({description:$t().optional(),messages:Go(_e)}),Ud=en({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),resources:Go(St),nextCursor:o.optional()}),zd=en({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),resourceTemplates:Go(kt),nextCursor:o.optional()}),Bm=en({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),contents:Go(bc([Tt,Ye]))}),Xf=en({completion:Fr({values:Go($t()).max(100),total:Gs().int().optional(),hasMore:kc().optional()}).loose()}),kf=en({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"])}),qi=en({ttlMs:Gs().int().min(0).catch(0),cacheScope:Bu(["public","private"]).catch("private"),supportedVersions:Go($t()),capabilities:Qo,instructions:$t().optional()}),Tm=Fr({messages:Go(Vo),modelPreferences:Dr.optional(),systemPrompt:$t().optional(),includeContext:Bu(["none","thisServer","allServers"]).optional(),temperature:Gs().optional(),maxTokens:Gs().int(),stopSequences:Go($t()).optional(),metadata:t.optional(),tools:Go(kn).optional(),toolChoice:gr.optional()}),ev=Fr({method:si("sampling/createMessage"),params:Tm}),E0=Fr({method:si("roots/list"),params:Fr({_meta:cc($t(),Dl()).optional()}).optional()}),tv=Fr({...Vo.shape,model:$t(),stopReason:$t().optional()}),z_=Fr({roots:Go(qa)}),Yv=Fr({action:Bu(["accept","decline","cancel"]),content:cc($t(),bc([$t(),Gs(),kc(),Go($t())])).optional()}),Lw=Fr({mode:si("url"),message:$t(),url:$t().url()}),Tu=bc([Ar,Lw]),t0=Fr({method:si("elicitation/create"),params:Tu}),Ub=bc([ev,E0,t0]),ta=bc([tv,z_,Yv]),af=cc($t(),Ub),lP=cc($t(),ta),tE=en({inputRequests:af.optional(),requestState:$t().optional()}),IS={inputResponses:lP.optional(),requestState:$t().optional()},Fw=Fr({_meta:gi,...IS}),Vs=nu({progressToken:n.optional()});function Iu(Ah,U8){return Fr({method:si(Ah),params:Fr({_meta:gi,...U8})})}r(Iu,"wireRequest");function bs(Ah,U8){return Fr({method:si(Ah),params:Fr({_meta:Vs.optional(),...U8}).optional()})}r(bs,"dispatchRequest");let A0={name:$t(),arguments:cc($t(),Dl()).optional(),...IS},ri={cursor:o.optional()},la=Iu("tools/call",A0),ul=Iu("tools/list",ri),py=Iu("prompts/list",ri),X0=Iu("prompts/get",{name:$t(),arguments:cc($t(),$t()).optional(),...IS}),jw=Iu("resources/list",ri),Ds=Iu("resources/templates/list",ri),e_=Iu("resources/read",{uri:$t(),...IS}),nE={ref:bc([Js,hi]),argument:Fr({name:$t(),value:$t()}),context:Fr({arguments:cc($t(),$t()).optional()}).optional()},$_=Iu("completion/complete",nE),Va=Iu("server/discover",{}),lp=Fr({toolsListChanged:kc().optional(),promptsListChanged:kc().optional(),resourcesListChanged:kc().optional(),resourceSubscriptions:Go($t()).optional()}),Eh={notifications:lp},rE=Iu("subscriptions/listen",Eh),cf=Kt.extend({"io.modelcontextprotocol/subscriptionId":s}),t_=nu({_meta:cf,resultType:qe.default("complete")}),q_={"tools/call":bs("tools/call",A0),"tools/list":bs("tools/list",ri),"prompts/get":bs("prompts/get",{name:$t(),arguments:cc($t(),$t()).optional()}),"prompts/list":bs("prompts/list",ri),"resources/list":bs("resources/list",ri),"resources/templates/list":bs("resources/templates/list",ri),"resources/read":bs("resources/read",{uri:$t()}),"completion/complete":bs("completion/complete",nE),"server/discover":bs("server/discover",{}),"subscriptions/listen":bs("subscriptions/listen",Eh)};function zb(Ah){return nu({_meta:Jt,...Ah})}r(zb,"liftedResult");let Yl={"tools/call":zb({content:Go(we),structuredContent:Dl().optional(),isError:kc().optional()}),"tools/list":zb({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),tools:Go(kn),nextCursor:o.optional()}),"prompts/get":zb({description:$t().optional(),messages:Go(_e)}),"prompts/list":zb({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),prompts:Go(Xe),nextCursor:o.optional()}),"resources/list":zb({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),resources:Go(St),nextCursor:o.optional()}),"resources/templates/list":zb({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),resourceTemplates:Go(kt),nextCursor:o.optional()}),"resources/read":zb({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),contents:Go(bc([Tt,Ye]))}),"completion/complete":zb({completion:Fr({values:Go($t()).max(100),total:Gs().int().optional(),hasMore:kc().optional()}).loose()}),"server/discover":zb({ttlMs:Gs().int().min(0).catch(0),cacheScope:Bu(["public","private"]).catch("private"),supportedVersions:Go($t()),capabilities:Qo,instructions:$t().optional()}),"subscriptions/listen":zb({})},dh=nu({"io.modelcontextprotocol/subscriptionId":s.optional()}),X1=Fr({method:si("notifications/subscriptions/acknowledged"),params:Fr({_meta:dh.optional(),notifications:lp})}),nD=Fr({_meta:dh.optional(),requestId:s,reason:$t().optional()}),ox=Fr({method:si("notifications/cancelled"),params:nD}),eZ={"notifications/cancelled":ox,"notifications/progress":pe,"notifications/message":rt,"notifications/resources/updated":jt,"notifications/resources/list_changed":st,"notifications/tools/list_changed":ut,"notifications/prompts/list_changed":_t,"notifications/subscriptions/acknowledged":X1},Sd=r(Ah=>Fr({jsonrpc:si("2.0"),id:bc([$t(),Gs().int()]),result:Ah}).strict(),"wireResultResponse");return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:o,RequestIdSchema:s,RoleSchema:a,LoggingLevelSchema:l,TaskMetadataSchema:f,RelatedTaskMetadataSchema:g,RequestMetaSchema:_,BaseRequestParamsSchema:b,TaskAugmentedRequestParamsSchema:w,NotificationsParamsSchema:T,NotificationSchema:I,IconSchema:E,IconsSchema:R,BaseMetadataSchema:L,ImplementationSchema:U,ClientTasksCapabilitySchema:$,ServerTasksCapabilitySchema:J,ClientCapabilitiesSchema:q,ServerCapabilitiesSchema:ie,ProgressSchema:ae,ProgressNotificationParamsSchema:Ce,ProgressNotificationSchema:pe,LoggingMessageNotificationParamsSchema:ze,LoggingMessageNotificationSchema:rt,ResourceContentsSchema:Pe,TextResourceContentsSchema:Tt,BlobResourceContentsSchema:Ye,AnnotationsSchema:Fe,ResourceSchema:St,ResourceTemplateSchema:kt,ResourceListChangedNotificationSchema:st,ResourceUpdatedNotificationParamsSchema:$e,ResourceUpdatedNotificationSchema:jt,PromptArgumentSchema:Je,PromptSchema:Xe,PromptListChangedNotificationSchema:_t,TextContentSchema:Dt,ImageContentSchema:gn,AudioContentSchema:cn,ToolUseContentSchema:Fn,EmbeddedResourceSchema:on,ResourceLinkSchema:dt,ContentBlockSchema:we,PromptMessageSchema:_e,ToolAnnotationsSchema:Pt,ToolListChangedNotificationSchema:ut,ModelHintSchema:Mn,ModelPreferencesSchema:Dr,ToolChoiceSchema:gr,BooleanSchemaSchema:eo,StringSchemaSchema:to,NumberSchemaSchema:oo,UntitledSingleSelectEnumSchemaSchema:ro,TitledSingleSelectEnumSchemaSchema:Ji,LegacyTitledEnumSchemaSchema:pi,SingleSelectEnumSchemaSchema:Wi,UntitledMultiSelectEnumSchemaSchema:Ii,TitledMultiSelectEnumSchemaSchema:Rs,MultiSelectEnumSchemaSchema:ht,EnumSchemaSchema:mr,PrimitiveSchemaDefinitionSchema:mi,ElicitRequestFormParamsSchema:Ar,ResourceTemplateReferenceSchema:hi,PromptReferenceSchema:Js,RootSchema:qa,ClientCapabilities2026Schema:oa,ServerCapabilities2026Schema:Qo,RequestMetaEnvelopeSchema:gi,ToolSchema:kn,ToolResultContentSchema:Nn,SamplingMessageContentBlockSchema:Ur,SamplingMessageSchema:Vo,ResultTypeSchema:qe,ResultMetaSchema:Kt,ResultSchema:qn,PaginatedResultSchema:Yr,CallToolResultSchema:ei,ListToolsResultSchema:ki,ListPromptsResultSchema:ca,GetPromptResultSchema:ks,ListResourcesResultSchema:Ud,ListResourceTemplatesResultSchema:zd,ReadResourceResultSchema:Bm,CompleteResultSchema:Xf,CacheableResultSchema:kf,DiscoverResultSchema:qi,CreateMessageRequestParamsSchema:Tm,CreateMessageRequestSchema:ev,ListRootsRequestSchema:E0,CreateMessageResultSchema:tv,ListRootsResultSchema:z_,ElicitResultSchema:Yv,ElicitRequestURLParamsSchema:Lw,ElicitRequestParamsSchema:Tu,ElicitRequestSchema:t0,InputRequestSchema:Ub,InputResponseSchema:ta,InputRequestsSchema:af,InputResponsesSchema:lP,InputRequiredResultSchema:tE,InputResponseRequestParamsSchema:Fw,CallToolRequestSchema:la,ListToolsRequestSchema:ul,ListPromptsRequestSchema:py,GetPromptRequestSchema:X0,ListResourcesRequestSchema:jw,ListResourceTemplatesRequestSchema:Ds,ReadResourceRequestSchema:e_,CompleteRequestSchema:$_,DiscoverRequestSchema:Va,SubscriptionFilterSchema:lp,SubscriptionsListenRequestSchema:rE,SubscriptionsListenResultMetaSchema:cf,SubscriptionsListenResultSchema:t_,dispatchRequestSchemas:q_,dispatchResultSchemas:Yl,NotificationMetaSchema:dh,SubscriptionsAcknowledgedNotificationSchema:X1,CancelledNotificationParamsSchema:nD,CancelledNotificationSchema:ox,notificationSchemas2026:eZ,JSONRPCResultResponseSchema:Sd(qn),CallToolResultResponseSchema:Sd(bc([ei,tE])),ListToolsResultResponseSchema:Sd(ki),ListPromptsResultResponseSchema:Sd(ca),GetPromptResultResponseSchema:Sd(bc([ks,tE])),ListResourcesResultResponseSchema:Sd(Ud),ListResourceTemplatesResultResponseSchema:Sd(zd),ReadResourceResultResponseSchema:Sd(bc([Bm,tE])),CompleteResultResponseSchema:Sd(Xf),DiscoverResultResponseSchema:Sd(qi)}}function Nre(){return j$s??=F$s()}function U$s(e){return B$s.includes(e)}function z$s(e){return e[efn]}function oXr(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function iXr(e){return e==="public"||e==="private"}function V$s(e,t){let n=t.resultType;if(n===void 0)return{...t,resultType:"complete"};if(n==="complete"||W$s.includes(e))return t;throw new oh(Du.InternalError,`Handler for ${e} returned resultType '${String(n)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function H$s(e,t){let n=z$s(t);if(t.resultType!=="complete"||!U$s(e))return n===void 0?t:Y$s(t);let o=t,s=oXr(o.ttlMs)?o.ttlMs:K$s(n),a=iXr(o.cacheScope)?o.cacheScope:Z$s(n),l={...o,ttlMs:s,cacheScope:a};return delete l[efn],l}function G$s(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function J$s(e,t){if(t===void 0)return e;let n=e._meta;return n===void 0?{...e,_meta:{[r$]:t}}:!G$s(n)||n[r$]!==void 0?e:{...e,_meta:{...n,[r$]:t}}}function K$s(e){return e!==void 0&&oXr(e.ttlMs)?e.ttlMs:$$s}function Z$s(e){return e!==void 0&&iXr(e.cacheScope)?e.cacheScope:q$s}function Y$s(e){let t={...e};return delete t[efn],t}function uXr(){if(wut)return wut;let e=Nre();return wut={request:{"elicitation/create":Fr({method:si("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":Fr({method:si("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":Fr({method:si("roots/list"),params:nu({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},wut}function dXr(e){return X$s.includes(e)}function zpn(e){return dXr(e)?uXr().request[e]:void 0}function Q$s(e){return dXr(e)?uXr().response[e]:void 0}function fXr(e){return Object.prototype.hasOwnProperty.call(tfn,e)}function mXr(e){return Object.prototype.hasOwnProperty.call(pXr,e)}function e9s(e){return Object.prototype.hasOwnProperty.call(tfn,e)}function t9s(e){return fXr(e)?Nre().dispatchRequestSchemas[e]:void 0}function n9s(e){return e9s(e)?Nre().dispatchResultSchemas[e]:void 0}function r9s(e){return mXr(e)?Nre().notificationSchemas2026[e]:void 0}function jMe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function LMe(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:"invalid",message:String(n.error)}}function s9s(e,t){let n=t,o=!1,s=r(()=>(o||(n={...n},o=!0),n),"copy"),a=t.tools;e==="tools/list"&&Array.isArray(a)&&a.some(u=>jMe(u)&&"execution"in u)&&(s().tools=a.map(u=>{if(!jMe(u)||!("execution"in u))return u;let f={...u};return delete f.execution,f}));let l=t.capabilities;if(jMe(l)&&"tasks"in l){let u={...l};delete u.tasks,s().capabilities=u}return n}function a9s(){if(kut)return kut;let e=Nre();return kut={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},kut}function i$(e){return e!==void 0&&a$(e)?nfn:Qpn}function BYr(e){return e.revision!==void 0?i$(e.revision).era:e.era==="modern"?nfn.era:Qpn.era}function $pn(e){return hXr.some(t=>t.hasRequestMethod(e))}function qpn(e){return hXr.some(t=>t.hasNotificationMethod(e))}function ofn(e){let t=[],n=new Map,o=r((a,l,u)=>{if(a===null||typeof a!="object")return;let f=a;if(UYr in f){if(!u||l.length===0)return`${xut(l)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let _=f[UYr];if(typeof _!="string"||_.length===0)return`${xut(l)}: x-mcp-header MUST be a non-empty string`;if(!u9s.test(_))return`${xut(l)}: x-mcp-header '${_}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let b=typeof f.type=="string"?f.type:void 0;if(b===void 0||!d9s.has(b))return`${xut(l)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${b??"<none>"}`;let w=_.toLowerCase(),T=n.get(w);if(T!==void 0)return`x-mcp-header '${_}' is not case-insensitively unique (also declared as '${T}')`;n.set(w,_),t.push({path:l,headerName:_,type:b})}let g=f.properties;if(g!==null&&typeof g=="object")for(let[_,b]of Object.entries(g)){let w=o(b,[...l,_],u);if(w!==void 0)return w}for(let _ of p9s){let b=f[_];if(b===void 0)continue;let w=Array.isArray(b)?b:b!==null&&typeof b=="object"&&f9s.has(_)?Object.values(b):[b];for(let T of w){let I=o(T,[...l,`<${_}>`],!1);if(I!==void 0)return I}}},"visit"),s=o(e,[],!0);return s===void 0?{valid:!0,declarations:t}:{valid:!1,reason:s}}function xut(e){return e.length===0?"<root>":e.join(".")}function m9s(e){if(typeof e=="string")return e;if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e)?void 0:String(e)}function h9s(e){if(e.length===0||e.startsWith(vXr)&&e.endsWith(bXr)||e!==e.trim())return!0;for(let t=0;t<e.length;t++){let n=e.codePointAt(t);if(!(n===9||n>=32&&n<=126))return!0}return!1}function g9s(e){let t=new TextEncoder().encode(e),n="";for(let o of t)n+=String.fromCodePoint(o);return btoa(n)}function ifn(e){return h9s(e)?`${vXr}${g9s(e)}${bXr}`:e}function _9s(e,t){let n=e;for(let o of t){if(n===null||typeof n!="object")return;n=n[o]}return n}function SXr(e,t){let n={};for(let o of e){let s=_9s(t,o.path);if(s==null)continue;let a=m9s(s);a!==void 0&&(n[`${l9s}${o.headerName}`]=ifn(a))}return n}function Cut(e,t){return REe(e,t)}function FMe(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}function Gpn(e){if(e==null)return!1;let t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}function y9s(e,t="input"){let n=e["~standard"],o;if(n.jsonSchema)o=n.jsonSchema[t]({target:Jpn});else if(n.vendor==="zod"){if(!("_zod"in e))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");zYr||(zYr=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),o=zL(e,{target:Jpn,io:t})}else throw new Error(`Schema library "${n.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output")return o.type!==void 0?o:wXr(o)?{type:"object",...o}:o;if(o.type!==void 0&&o.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(o.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...o}}function wXr(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let n=e[t];if(Array.isArray(n)&&n.length>0)return n.every(o=>o!==null&&typeof o=="object"&&(o.type==="object"||wXr(o)))}return!1}function v9s(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}async function Wpn(e,t){let n=await e["~standard"].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(o=>v9s(o)).join(", ")}:{success:!0,data:n.value}}function b9s(e){let t=zL(e,{target:Jpn,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}function w9s(e){let t=S9s.exec(e),n=[void 0,-1,0];return t&&n.push(Number(t[1])),[!1,!0].flatMap(o=>[!1,!0].flatMap(s=>n.map(a=>jO.datetime({local:o,offset:s,precision:a}))))}function k9s(e,t){let n;switch(e){case"email":n=[$Je()];break;case"uri":n=[ape()];break;case"date":n=[jO.date()];break;case"date-time":n=w9s(t);break}return new Set(n.map(o=>b9s(o)).filter(o=>o!==void 0))}function x9s(e,t,n){return n!=="zod"?!0:k9s(e,t).has(t)}function UMe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function T9s(e){try{return y9s(e,"input")}catch(t){let n=t instanceof Error?t.message:String(t);throw new oh(Du.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${n}`)}}function sfn(e){return I9s.has(e)||e.startsWith("x-")}function A9s(e,t,n,o){if(!UMe(e))return e;let s=typeof e.type=="string"&&Object.hasOwn($Yr,e.type)?$Yr[e.type]:void 0;if(s===void 0)return e;let a={};for(let[l,u]of Object.entries(e))s.has(l)||sfn(l)?a[l]=u:l==="pattern"&&e.type==="string"&&typeof e.format=="string"?E9s.has(e.format)?(typeof u!="string"||!x9s(e.format,u,n))&&o.push(`${t}.${l}`):a[l]=u:o.push(`${t}.${l}`);return a}function P9s(e,t){let n={},o=[];for(let[s,a]of Object.entries(e))s==="properties"&&UMe(a)?n[s]=Object.fromEntries(Object.entries(a).map(([l,u])=>[l,A9s(u,`properties.${l}`,t,o)])):C9s.has(s)?n[s]=a:sfn(s)||o.push(s);if(o.length>0)throw new oh(Du.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return n}function R9s(e,t){if(!UMe(e.properties))return t;let n=Object.entries(e.properties).filter(([,o])=>!Cut(PMe,o).success).map(([o])=>`properties.${o}`);return n.length>0?n.join(", "):t}function Kpn(e,t,n=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((o,s)=>Kpn(o,t[s],`${n}[${s}]`)):!UMe(e)||!UMe(t)?[]:Object.entries(e).flatMap(([o,s])=>{let a=n?`${n}.${o}`:o;return Object.prototype.hasOwnProperty.call(t,o)?Kpn(s,t[o],a):sfn(o)?[]:[a]})}function D9s(e){if(!Gpn(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,n=P9s(T9s(e.requestedSchema),t),o=Cut(Sge.shape.requestedSchema,n);if(!o.success)throw new oh(Du.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${R9s(n,o.error.message)}`);let s=Kpn(n,o.data);if(s.length>0)throw new oh(Du.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${s.join(", ")}`);let a=(o.data.required??[]).filter(l=>!Object.prototype.hasOwnProperty.call(o.data.properties,l));if(a.length>0)throw new oh(Du.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${a.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}function O9s(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,n=typeof e.requestState=="string";if(!t&&!n)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}function kXr(e){return{autoFulfill:e?.autoFulfill??M9s,maxRounds:e?.maxRounds??N9s}}function F9s(e,t,n){let o=t!==void 0&&Object.keys(t).length>0;return!o&&n===void 0?e:{...e,...o&&{inputResponses:t},...n!==void 0&&{requestState:n}}}function j9s(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function B9s(e,t){return new Promise((n,o)=>{if(t?.aborted){o(t.reason instanceof rl?t.reason:new rl(Pc.RequestTimeout,String(t.reason)));return}let s=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e),a=r(()=>{clearTimeout(s),o(t?.reason instanceof rl?t.reason:new rl(Pc.RequestTimeout,String(t?.reason)))},"onAbort");t?.addEventListener("abort",a,{once:!0})})}function U9s(e){let t=new AbortController,n=r(()=>t.abort(e?.reason),"onOuterAbort");return e?.addEventListener("abort",n,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:r(o=>t.abort(o),"abort"),dispose:r(()=>e?.removeEventListener("abort",n),"dispose")}}async function z9s(e){let{config:t,method:n,originalParams:o,requestOptions:s,hooks:a,signal:l}=e,u=e.flowStartedAt??Date.now(),f=e.firstPayload,g=0;for(;;){if(g+=1,g>t.maxRounds)throw new rl(Pc.InputRequiredRoundsExceeded,j9s(n,t.maxRounds),{rounds:t.maxRounds,lastResult:{inputRequests:f.inputRequests,...f.requestState!==void 0&&{requestState:f.requestState}}});s.onprogress?.({progress:g,message:`Fulfilling input required by '${n}' (round ${g})`});let _=Object.entries(f.inputRequests??{}),b;if(_.length>0){let I=U9s(l);try{let E=await Promise.all(_.map(async([R,L])=>{try{return[R,await a.dispatchInputRequest(R,L,I.signal)]}catch(U){throw I.abort(U),U}}));b=Object.fromEntries(E)}finally{I.dispose()}}else await B9s(L9s,l);let w={...s.timeout!==void 0&&{timeout:s.timeout}};if(s.maxTotalTimeout!==void 0){let I=Date.now()-u,E=s.maxTotalTimeout-I;if(E<=0)throw new rl(Pc.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:s.maxTotalTimeout,totalElapsed:I});w.maxTotalTimeout=E}let T=await a.retry(F9s(o,b,f.requestState),w);if(_Xr(T)){f={inputRequests:T.inputRequests??{},...T.requestState!==void 0&&{requestState:T.requestState}};continue}return T}}function IXr(e,t){let n=e.slice(0,-6);xXr[n]=t,TXr[n]=o=>t.safeParse(o).success}function V9s(e){switch(e){case"initialize":case"notifications/initialized":return i$(void 0);case"server/discover":return i$(Iut);default:return}}function qYr(e,t){let n=e.params;if(!BMe(n))return{message:e,lifted:{}};let o=n._meta,s=BMe(o)?H9s.filter(f=>f in o):[],a=t==="request"?G9s.filter(f=>f in n):[];if(s.length===0&&a.length===0)return{message:e,lifted:{}};let l={},u={...n};if(s.length>0&&BMe(o)){let f={},g={...o};for(let _ of s)f[_]=o[_],delete g[_];l.envelope=f,Object.keys(g).length>0?u._meta=g:delete u._meta}for(let f of a)f==="inputResponses"&&(l.inputResponses=u[f]),f==="requestState"&&(l.requestState=u[f]),delete u[f];return{message:{...e,params:u},lifted:l}}function WYr(e,t){let n=e.validateResult(t,void 0);if(!(!n.ok&&n.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(o){let s=e.validateResult(t,o);return s.ok?{value:s.value}:{issues:[{message:s.reason==="invalid"?s.message:`not-in-era: ${t}`}]}}}}}function afn(e){return()=>e}function BMe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function AXr(e,t){let n={...e};for(let o in t){let s=o,a=t[s];if(a===void 0)continue;let l=n[s];n[s]=BMe(l)&&BMe(a)?{...l,...a}:a}return n}function Tut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Z9s(e){let t={},n=[];if(!Tut(e))return{accepted:t,droppedKeys:n};for(let[o,s]of Object.entries(e)){if(!Tut(s)||"method"in s||"result"in s){n.push(o);continue}t[o]=s}return{accepted:t,droppedKeys:n}}function VYr(e){throw new rl(Pc.SendFailed,`ctx.mcpReq.${e} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`)}function Y9s(e,t,n,o,s){return{sessionId:s,mcpReq:{id:e,method:t,_meta:n?._meta,requestState:afn(void 0),signal:o,send:r((()=>VYr("send")),"send"),notify:r(()=>VYr("notify"),"notify")}}}async function X9s(e,t,n,o,s){if(!Tut(o)||typeof o.method!="string")throw new rl(Pc.InvalidResult,`Invalid input request '${n}': each inputRequests entry must be an embedded request object with a method`,{key:n});let a=o.method;if(!t.hasInputRequestMethod(a))throw new rl(Pc.InvalidResult,`Invalid input request '${n}': '${a}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:n,method:a});let l=e.getRequestHandler(a);if(l===void 0)throw new rl(Pc.CapabilityNotSupported,`Cannot fulfil input request '${n}': no handler is registered for '${a}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:n,method:a});let u=Tut(o.params)?o.params:void 0;return await l({jsonrpc:"2.0",id:n,method:a,...u!==void 0&&{params:u}},e.buildContext(Y9s(n,a,u,s,e.sessionId)))}function Q9s(e,t){return{...e?.signal!==void 0&&{signal:e.signal},...e?.onprogress!==void 0&&{onprogress:e.onprogress},...e?.resetTimeoutOnProgress!==void 0&&{resetTimeoutOnProgress:e.resetTimeoutOnProgress},...e?.headers!==void 0&&{headers:e.headers},...t.timeout!==void 0&&{timeout:t.timeout},...t.maxTotalTimeout!==void 0&&{maxTotalTimeout:t.maxTotalTimeout},allowInputRequired:!0}}function PXr(e,t,n,o){let{codec:s,request:a,options:l,flowStartedAt:u}=o,f={inputRequests:n.inputRequests,...n.requestState!==void 0&&{requestState:n.requestState}},g={dispatchInputRequest:r((_,b,w)=>X9s(e,s,_,b,w),"dispatchInputRequest"),retry:r((_,b)=>o.retry(_,Q9s(l,b)),"retry")};return z9s({config:t,method:a.method,originalParams:a.params,firstPayload:f,flowStartedAt:u,signal:l?.signal,requestOptions:{...l?.timeout!==void 0&&{timeout:l.timeout},...l?.maxTotalTimeout!==void 0&&{maxTotalTimeout:l.maxTotalTimeout},...l?.onprogress!==void 0&&{onprogress:l.onprogress}},hooks:g})}function eqs(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState}}}function RXr(e){if(e)try{return nqs.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();return t===""||e.slice(t.length).includes(",")?void 0:t}}function OXr(e){return pB.parse(JSON.parse(e))}function lfn(e){return JSON.stringify(e)+`
|
|
2138
2138
|
`}function zMe(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function ufn(e=fetch,t){return t?async(n,o)=>e(n,{...t,...o,headers:o?.headers?{...zMe(t.headers),...zMe(o.headers)}:t.headers}):e}var Vpn,GF,s$,Pc,rl,JF,KYr,Zpn,YYr,E$s,A$s,P$s,eXr,tXr,D$s,but,tbl,nbl,FYr,Qpn,j$s,B$s,efn,Du,oh,aXr,cXr,Tge,lXr,$$s,q$s,W$s,X$s,wut,tfn,pXr,rbl,obl,o9s,i9s,nfn,kut,Iut,hXr,c9s,Fre,gXr,xge,Ige,_Xr,rfn,yXr,l9s,UYr,u9s,d9s,p9s,f9s,vXr,bXr,kge,ibl,sbl,zYr,Jpn,S9s,I9s,C9s,$Yr,E9s,abl,M9s,N9s,L9s,$9s,q9s,xXr,TXr,W9s,CXr,Eut,H9s,G9s,J9s,K9s,EXr,tqs,nqs,DXr,cfn,dfn=Y(()=>{hpn();gpn();NYr();tc();Vpn=Symbol.for("mcp.sdk.errorBrands");r(Lre,"stampErrorBrands");r(C2,"brandedHasInstance");GF=(function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e})({}),s$=class HYr extends Error{static{r(this,"OAuthError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return C2(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return C2(this,t)}constructor(t,n,o){super(n),this.code=t,this.errorUri=o,this.name="OAuthError",Lre(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}static fromResponse(t){return new HYr(t.error,t.error_description??t.error,t.error_uri)}},Pc=(function(e){return e.NotConnected="NOT_CONNECTED",e.AlreadyConnected="ALREADY_CONNECTED",e.NotInitialized="NOT_INITIALIZED",e.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",e.RequestTimeout="REQUEST_TIMEOUT",e.ConnectionClosed="CONNECTION_CLOSED",e.SendFailed="SEND_FAILED",e.InvalidResult="INVALID_RESULT",e.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",e.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",e.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",e.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",e.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",e.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",e.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",e.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",e.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",e.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",e.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",e})({}),rl=class extends Error{static{r(this,"SdkError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return C2(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return C2(this,e)}constructor(e,t,n){super(t),this.code=e,this.data=n,this.name="SdkError",Lre(this,new.target)}},JF=class extends rl{static{r(this,"SdkHttpError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,n){super(e,t,n),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};r(GYr,"resourceUrlFromServerUrl");r(JYr,"checkResourceAllowed");KYr="2026-07-28",Zpn=[KYr];r(a$,"isModernProtocolVersion");r(Ypn,"legacyProtocolVersions");r($Me,"modernProtocolVersions");r(ZYr,"appendTextFallbackForNonObject");YYr=["task","inputRequests","requestState"];r(I$s,"normalizeContentlessToolResult");r(C$s,"build$1");r(XYr,"buildSchemas2025");r(QYr,"isNonObjectJsonSchemaRoot");A$s=new Set(["const","enum","default","examples"]),P$s=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);r(LYr,"establishesNewBase");r(R$s,"wrapOutputSchemaForLegacy");eXr={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},tXr={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},D$s={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};r(Xpn,"registryMaps");r(nXr,"hasRequestMethod2025");r(rXr,"hasNotificationMethod2025");r(O$s,"hasResultMethod");r(M$s,"getResultSchema");r(N$s,"getRequestSchema");r(L$s,"getNotificationSchema");tbl=Object.keys(eXr),nbl=Object.keys(tXr);r(Hpn,"isPlainObject$4");r(Sut,"triState$1");FYr={ok:!1,reason:"not-in-era"};r(jYr,"toolNeedsLegacyWrap");Qpn={era:"2025-11-25",hasRequestMethod:nXr,hasNotificationMethod:rXr,validateRequest:r((e,t)=>Sut(N$s(e),t),"validateRequest"),validateResult:r((e,t)=>Sut(M$s(e),t),"validateResult"),validateNotification:r((e,t)=>Sut(L$s(e),t),"validateNotification"),hasInputRequestMethod:r(()=>!1,"hasInputRequestMethod"),validateInputRequest:r(()=>FYr,"validateInputRequest"),validateInputResponse:r(()=>FYr,"validateInputResponse"),samplingResultVariant:r(((e,t)=>{let n=XYr();return Sut(e?n.CreateMessageResultWithToolsSchema:n.CreateMessageResultSchema,t)}),"samplingResultVariant"),outboundEnvelope:r(e=>{},"outboundEnvelope"),validateEnvelopeMeta:r(e=>[],"validateEnvelopeMeta"),projectCallToolResult(e,t){let n=ZYr(e),o=n.structuredContent;if(o===void 0)return n;let s=typeof o!="object"||o===null||Array.isArray(o),a=t!==void 0&&QYr(t);return!s&&!a?n:{...n,structuredContent:{result:o}}},decodeResult(e,t){if(Hpn(t)&&"resultType"in t){let n={...t};return delete n.resultType,{kind:"complete",result:n}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;let n=t.tools;return!Array.isArray(n)||!n.some(o=>jYr(o))?t:{...t,tools:n.map(o=>jYr(o)?{...o,outputSchema:R$s(o.outputSchema)}:o)}},encodeErrorCode:r(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope:r(e=>{},"checkInboundEnvelope")};r(F$s,"build");r(Nre,"buildSchemas2026");B$s=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];r(U$s,"isCacheableResultMethod");efn=Symbol("modelcontextprotocol.resultCacheHintFallback");r(z$s,"cacheHintFallbackOf");r(oXr,"isValidCacheTtlMs");r(iXr,"isValidCacheScope");Du=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({}),oh=class sXr extends Error{static{r(this,"ProtocolError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return C2(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return C2(this,t)}constructor(t,n,o){super(n),this.code=t,this.data=o,this.name="ProtocolError",Lre(this,new.target)}static fromError(t,n,o){if(t===Du.UrlElicitationRequired&&o){let s=o;if(s.elicitations)return new cXr(s.elicitations,n)}if(t===Du.UnsupportedProtocolVersion&&o){let s=o;if(Array.isArray(s.supported)&&typeof s.requested=="string")return new Tge({supported:s.supported,requested:s.requested},n)}if(t===Du.InvalidParams||t===Du.ResourceNotFound){let s=o;if(typeof s?.uri=="string"&&(t===Du.ResourceNotFound||Object.keys(s).length===1))return new aXr(s.uri,n)}if(t===Du.MissingRequiredClientCapability&&o){let s=o;if(s.requiredCapabilities!==null&&typeof s.requiredCapabilities=="object"&&!Array.isArray(s.requiredCapabilities))return new lXr({requiredCapabilities:s.requiredCapabilities},n)}return new sXr(t,n,o)}},aXr=class extends oh{static{r(this,"ResourceNotFoundError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(Du.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},cXr=class extends oh{static{r(this,"UrlElicitationRequiredError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Du.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Tge=class extends oh{static{r(this,"UnsupportedProtocolVersionError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(Du.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},lXr=class extends oh{static{r(this,"MissingRequiredClientCapabilityError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(Du.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},$$s=0,q$s="private",W$s=["tools/call","prompts/get","resources/read"];r(V$s,"stampResultType");r(H$s,"fillCacheFields");r(G$s,"isPlainObject$3");r(J$s,"stampServerInfoMeta");r(K$s,"resolveTtlMs");r(Z$s,"resolveCacheScope");r(Y$s,"stripCacheHintFallback");X$s=["elicitation/create","sampling/createMessage","roots/list"];r(uXr,"inputSchemaMaps");r(dXr,"isInputRequestMethod2026");r(zpn,"getInputRequestSchema2026");r(Q$s,"getInputResponseSchema2026");tfn={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},pXr={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};r(fXr,"hasRequestMethod2026");r(mXr,"hasNotificationMethod2026");r(e9s,"hasResultMethod2026");r(t9s,"getRequestSchema2026");r(n9s,"getResultSchema2026");r(r9s,"getNotificationSchema2026");rbl=Object.keys(tfn),obl=Object.keys(pXr);r(jMe,"isPlainObject$2");r(LMe,"triState");o9s={ok:!1,reason:"not-in-era"},i9s=[n$,Rre];r(s9s,"enforceDeletedFields");nfn={era:"2026-07-28",hasRequestMethod:fXr,hasNotificationMethod:mXr,hasInputRequestMethod:r(e=>zpn(e)!==void 0,"hasInputRequestMethod"),validateRequest:r((e,t)=>LMe(t9s(e),t),"validateRequest"),validateResult:r((e,t)=>LMe(n9s(e),t),"validateResult"),validateNotification:r((e,t)=>LMe(r9s(e),t),"validateNotification"),validateInputRequest:r((e,t)=>LMe(zpn(e),t),"validateInputRequest"),validateInputResponse:r((e,t)=>LMe(Q$s(e),t),"validateInputResponse"),samplingResultVariant:r(()=>o9s,"samplingResultVariant"),outboundEnvelope(e){return{[n$]:e.protocolVersion,[lge]:e.clientInfo,[Rre]:e.clientCapabilities,...e.logLevel!==void 0&&{[uge]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of i9s)o in e||t.push({key:o,problem:"missing"});let n=Nre().RequestMetaEnvelopeSchema.safeParse(e);if(!n.success)for(let o of n.error.issues){let s=o.path.map(String),a=s.length>0?s.join("."):"_meta";s.length===1&&t.some(l=>l.key===a&&l.problem==="missing")||t.push({key:a,problem:o.message})}return t},projectCallToolResult:r(e=>ZYr(e),"projectCallToolResult"),inputRequestSchema:zpn,decodeResult(e,t){if(!jMe(t))return{kind:"invalid",error:new rl(Pc.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let n=t.resultType;if(n===void 0)return{kind:"invalid",error:new rl(Pc.InvalidResult,`Invalid result for ${e}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:"missing-resultType"})};if(typeof n!="string")return{kind:"invalid",error:new rl(Pc.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:n})};if(n==="input_required"){let l=t.inputRequests,u=jMe(l)?l:{},f=t.requestState;return Object.keys(u).length===0&&typeof f!="string"?{kind:"invalid",error:new rl(Pc.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:u,...typeof f=="string"&&{requestState:f}}}if(n!=="complete")return{kind:"invalid",error:new rl(Pc.UnsupportedResultType,`Unsupported result type '${n}' for ${e}`,{resultType:n,method:e})};let o=a9s(),s=Object.hasOwn(o,e)?o[e]:void 0;if(s!==void 0){let l=s.safeParse(t);if(!l.success)return{kind:"invalid",error:new rl(Pc.InvalidResult,`Invalid result for ${e}: ${l.error}`,{method:e})}}let a={...t};return delete a.resultType,{kind:"complete",result:a}},encodeResult(e,t,n){return J$s(H$s(e,V$s(e,s9s(e,t))),n)},encodeErrorCode:r(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=Nre().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(n=>n.message).join("; ")}`}};r(a9s,"getWireResultSchemas");Iut="2026-07-28";r(i$,"codecForVersion");r(BYr,"classifiedWireEra");r($pn,"isSpecRequestMethod");r(qpn,"isSpecNotificationMethod");hXr=[Qpn,nfn],c9s=SYr({AnnotationsSchema:r(()=>o$,"AnnotationsSchema"),AudioContentSchema:r(()=>_ge,"AudioContentSchema"),BaseMetadataSchema:r(()=>t$,"BaseMetadataSchema"),BaseRequestParamsSchema:r(()=>zk,"BaseRequestParamsSchema"),BlobResourceContentsSchema:r(()=>_Me,"BlobResourceContentsSchema"),BooleanSchemaSchema:r(()=>xMe,"BooleanSchemaSchema"),CallToolRequestParamsSchema:r(()=>Olt,"CallToolRequestParamsSchema"),CallToolRequestSchema:r(()=>Mlt,"CallToolRequestSchema"),CallToolResultSchema:r(()=>SMe,"CallToolResultSchema"),CancelTaskRequestSchema:r(()=>Rpn,"CancelTaskRequestSchema"),CancelTaskResultSchema:r(()=>Dpn,"CancelTaskResultSchema"),CancelledNotificationParamsSchema:r(()=>Bct,"CancelledNotificationParamsSchema"),CancelledNotificationSchema:r(()=>lMe,"CancelledNotificationSchema"),ClientCapabilitiesSchema:r(()=>qct,"ClientCapabilitiesSchema"),ClientNotificationSchema:r(()=>Mpn,"ClientNotificationSchema"),ClientRequestSchema:r(()=>Opn,"ClientRequestSchema"),ClientResultSchema:r(()=>Npn,"ClientResultSchema"),ClientTasksCapabilitySchema:r(()=>zct,"ClientTasksCapabilitySchema"),CompatibilityCallToolResultSchema:r(()=>Spn,"CompatibilityCallToolResultSchema"),CompleteRequestParamsSchema:r(()=>aut,"CompleteRequestParamsSchema"),CompleteRequestSchema:r(()=>cut,"CompleteRequestSchema"),CompleteResultSchema:r(()=>lut,"CompleteResultSchema"),ContentBlockSchema:r(()=>yge,"ContentBlockSchema"),CreateMessageRequestParamsSchema:r(()=>Hlt,"CreateMessageRequestParamsSchema"),CreateMessageRequestSchema:r(()=>Glt,"CreateMessageRequestSchema"),CreateMessageResultSchema:r(()=>Jlt,"CreateMessageResultSchema"),CreateMessageResultWithToolsSchema:r(()=>Klt,"CreateMessageResultWithToolsSchema"),CreateTaskResultSchema:r(()=>kpn,"CreateTaskResultSchema"),CursorSchema:r(()=>rMe,"CursorSchema"),DiscoverRequestSchema:r(()=>Hct,"DiscoverRequestSchema"),DiscoverResultSchema:r(()=>Mre,"DiscoverResultSchema"),ElicitRequestFormParamsSchema:r(()=>Sge,"ElicitRequestFormParamsSchema"),ElicitRequestParamsSchema:r(()=>eut,"ElicitRequestParamsSchema"),ElicitRequestSchema:r(()=>tut,"ElicitRequestSchema"),ElicitRequestURLParamsSchema:r(()=>Qlt,"ElicitRequestURLParamsSchema"),ElicitResultSchema:r(()=>out,"ElicitResultSchema"),ElicitationCompleteNotificationParamsSchema:r(()=>nut,"ElicitationCompleteNotificationParamsSchema"),ElicitationCompleteNotificationSchema:r(()=>rut,"ElicitationCompleteNotificationSchema"),EmbeddedResourceSchema:r(()=>xlt,"EmbeddedResourceSchema"),EmptyResultSchema:r(()=>cMe,"EmptyResultSchema"),EnumSchemaSchema:r(()=>Xlt,"EnumSchemaSchema"),GetPromptRequestParamsSchema:r(()=>Slt,"GetPromptRequestParamsSchema"),GetPromptRequestSchema:r(()=>wlt,"GetPromptRequestSchema"),GetPromptResultSchema:r(()=>Clt,"GetPromptResultSchema"),GetTaskPayloadRequestSchema:r(()=>Cpn,"GetTaskPayloadRequestSchema"),GetTaskPayloadResultSchema:r(()=>Epn,"GetTaskPayloadResultSchema"),GetTaskRequestSchema:r(()=>Tpn,"GetTaskRequestSchema"),GetTaskResultSchema:r(()=>Ipn,"GetTaskResultSchema"),IconSchema:r(()=>Uct,"IconSchema"),IconsSchema:r(()=>xG,"IconsSchema"),ImageContentSchema:r(()=>gge,"ImageContentSchema"),ImplementationSchema:r(()=>fge,"ImplementationSchema"),InitializeRequestParamsSchema:r(()=>Wct,"InitializeRequestParamsSchema"),InitializeRequestSchema:r(()=>uMe,"InitializeRequestSchema"),InitializeResultSchema:r(()=>Vct,"InitializeResultSchema"),InitializedNotificationSchema:r(()=>pMe,"InitializedNotificationSchema"),JSONArraySchema:r(()=>ypn,"JSONArraySchema"),JSONObjectSchema:r(()=>qv,"JSONObjectSchema"),JSONRPCErrorResponseSchema:r(()=>pge,"JSONRPCErrorResponseSchema"),JSONRPCMessageSchema:r(()=>pB,"JSONRPCMessageSchema"),JSONRPCNotificationSchema:r(()=>aMe,"JSONRPCNotificationSchema"),JSONRPCRequestSchema:r(()=>sMe,"JSONRPCRequestSchema"),JSONRPCResponseSchema:r(()=>vpn,"JSONRPCResponseSchema"),JSONRPCResultResponseSchema:r(()=>dge,"JSONRPCResultResponseSchema"),JSONValueSchema:r(()=>wG,"JSONValueSchema"),LegacyTitledEnumSchemaSchema:r(()=>CMe,"LegacyTitledEnumSchemaSchema"),ListChangedOptionsBaseSchema:r(()=>wMe,"ListChangedOptionsBaseSchema"),ListPromptsRequestSchema:r(()=>vlt,"ListPromptsRequestSchema"),ListPromptsResultSchema:r(()=>blt,"ListPromptsResultSchema"),ListResourceTemplatesRequestSchema:r(()=>Qct,"ListResourceTemplatesRequestSchema"),ListResourceTemplatesResultSchema:r(()=>elt,"ListResourceTemplatesResultSchema"),ListResourcesRequestSchema:r(()=>Yct,"ListResourcesRequestSchema"),ListResourcesResultSchema:r(()=>Xct,"ListResourcesResultSchema"),ListRootsRequestSchema:r(()=>dut,"ListRootsRequestSchema"),ListRootsResultSchema:r(()=>put,"ListRootsResultSchema"),ListTasksRequestSchema:r(()=>Apn,"ListTasksRequestSchema"),ListTasksResultSchema:r(()=>Ppn,"ListTasksResultSchema"),ListToolsRequestSchema:r(()=>Rlt,"ListToolsRequestSchema"),ListToolsResultSchema:r(()=>Dlt,"ListToolsResultSchema"),LoggingLevelSchema:r(()=>kMe,"LoggingLevelSchema"),LoggingMessageNotificationParamsSchema:r(()=>jlt,"LoggingMessageNotificationParamsSchema"),LoggingMessageNotificationSchema:r(()=>Blt,"LoggingMessageNotificationSchema"),ModelHintSchema:r(()=>Ult,"ModelHintSchema"),ModelPreferencesSchema:r(()=>zlt,"ModelPreferencesSchema"),MultiSelectEnumSchemaSchema:r(()=>Ylt,"MultiSelectEnumSchemaSchema"),NotificationSchema:r(()=>O1,"NotificationSchema"),NotificationsParamsSchema:r(()=>D1,"NotificationsParamsSchema"),NumberSchemaSchema:r(()=>bge,"NumberSchemaSchema"),PaginatedRequestParamsSchema:r(()=>Kct,"PaginatedRequestParamsSchema"),PaginatedRequestSchema:r(()=>TG,"PaginatedRequestSchema"),PaginatedResultSchema:r(()=>IG,"PaginatedResultSchema"),PingRequestSchema:r(()=>fMe,"PingRequestSchema"),PrimitiveSchemaDefinitionSchema:r(()=>PMe,"PrimitiveSchemaDefinitionSchema"),ProgressNotificationParamsSchema:r(()=>Jct,"ProgressNotificationParamsSchema"),ProgressNotificationSchema:r(()=>mMe,"ProgressNotificationSchema"),ProgressSchema:r(()=>Gct,"ProgressSchema"),ProgressTokenSchema:r(()=>nMe,"ProgressTokenSchema"),PromptArgumentSchema:r(()=>_lt,"PromptArgumentSchema"),PromptListChangedNotificationSchema:r(()=>Elt,"PromptListChangedNotificationSchema"),PromptMessageSchema:r(()=>Ilt,"PromptMessageSchema"),PromptReferenceSchema:r(()=>sut,"PromptReferenceSchema"),PromptSchema:r(()=>ylt,"PromptSchema"),ReadResourceRequestParamsSchema:r(()=>tlt,"ReadResourceRequestParamsSchema"),ReadResourceRequestSchema:r(()=>nlt,"ReadResourceRequestSchema"),ReadResourceResultSchema:r(()=>rlt,"ReadResourceResultSchema"),RelatedTaskMetadataSchema:r(()=>jct,"RelatedTaskMetadataSchema"),RequestIdSchema:r(()=>kG,"RequestIdSchema"),RequestMetaSchema:r(()=>oMe,"RequestMetaSchema"),RequestSchema:r(()=>Wv,"RequestSchema"),ResourceContentsSchema:r(()=>hMe,"ResourceContentsSchema"),ResourceLinkSchema:r(()=>Tlt,"ResourceLinkSchema"),ResourceListChangedNotificationSchema:r(()=>olt,"ResourceListChangedNotificationSchema"),ResourceRequestParamsSchema:r(()=>mge,"ResourceRequestParamsSchema"),ResourceSchema:r(()=>yMe,"ResourceSchema"),ResourceTemplateReferenceSchema:r(()=>iut,"ResourceTemplateReferenceSchema"),ResourceTemplateSchema:r(()=>Zct,"ResourceTemplateSchema"),ResourceUpdatedNotificationParamsSchema:r(()=>hlt,"ResourceUpdatedNotificationParamsSchema"),ResourceUpdatedNotificationSchema:r(()=>glt,"ResourceUpdatedNotificationSchema"),ResultMetaObjectSchema:r(()=>iMe,"ResultMetaObjectSchema"),ResultSchema:r(()=>Vv,"ResultSchema"),RoleSchema:r(()=>CG,"RoleSchema"),RootSchema:r(()=>uut,"RootSchema"),RootsListChangedNotificationSchema:r(()=>fut,"RootsListChangedNotificationSchema"),SamplingContentSchema:r(()=>Wlt,"SamplingContentSchema"),SamplingMessageContentBlockSchema:r(()=>Pre,"SamplingMessageContentBlockSchema"),SamplingMessageSchema:r(()=>Vlt,"SamplingMessageSchema"),ServerCapabilitiesSchema:r(()=>dMe,"ServerCapabilitiesSchema"),ServerNotificationSchema:r(()=>Fpn,"ServerNotificationSchema"),ServerRequestSchema:r(()=>Lpn,"ServerRequestSchema"),ServerResultSchema:r(()=>jpn,"ServerResultSchema"),ServerTasksCapabilitySchema:r(()=>$ct,"ServerTasksCapabilitySchema"),SetLevelRequestParamsSchema:r(()=>Llt,"SetLevelRequestParamsSchema"),SetLevelRequestSchema:r(()=>Flt,"SetLevelRequestSchema"),SingleSelectEnumSchemaSchema:r(()=>Zlt,"SingleSelectEnumSchemaSchema"),StringSchemaSchema:r(()=>vge,"StringSchemaSchema"),SubscribeRequestParamsSchema:r(()=>ilt,"SubscribeRequestParamsSchema"),SubscribeRequestSchema:r(()=>slt,"SubscribeRequestSchema"),SubscriptionFilterSchema:r(()=>vMe,"SubscriptionFilterSchema"),SubscriptionsAcknowledgedNotificationParamsSchema:r(()=>dlt,"SubscriptionsAcknowledgedNotificationParamsSchema"),SubscriptionsAcknowledgedNotificationSchema:r(()=>plt,"SubscriptionsAcknowledgedNotificationSchema"),SubscriptionsListenRequestParamsSchema:r(()=>llt,"SubscriptionsListenRequestParamsSchema"),SubscriptionsListenRequestSchema:r(()=>ult,"SubscriptionsListenRequestSchema"),SubscriptionsListenResultMetaSchema:r(()=>flt,"SubscriptionsListenResultMetaSchema"),SubscriptionsListenResultSchema:r(()=>mlt,"SubscriptionsListenResultSchema"),TaskAugmentedRequestParamsSchema:r(()=>Ore,"TaskAugmentedRequestParamsSchema"),TaskCreationParamsSchema:r(()=>wpn,"TaskCreationParamsSchema"),TaskMetadataSchema:r(()=>Fct,"TaskMetadataSchema"),TaskSchema:r(()=>EG,"TaskSchema"),TaskStatusNotificationParamsSchema:r(()=>hut,"TaskStatusNotificationParamsSchema"),TaskStatusNotificationSchema:r(()=>xpn,"TaskStatusNotificationSchema"),TaskStatusSchema:r(()=>mut,"TaskStatusSchema"),TextContentSchema:r(()=>hge,"TextContentSchema"),TextResourceContentsSchema:r(()=>gMe,"TextResourceContentsSchema"),TitledMultiSelectEnumSchemaSchema:r(()=>AMe,"TitledMultiSelectEnumSchemaSchema"),TitledSingleSelectEnumSchemaSchema:r(()=>IMe,"TitledSingleSelectEnumSchemaSchema"),ToolAnnotationsSchema:r(()=>Alt,"ToolAnnotationsSchema"),ToolChoiceSchema:r(()=>$lt,"ToolChoiceSchema"),ToolExecutionSchema:r(()=>Plt,"ToolExecutionSchema"),ToolListChangedNotificationSchema:r(()=>Nlt,"ToolListChangedNotificationSchema"),ToolResultContentSchema:r(()=>qlt,"ToolResultContentSchema"),ToolSchema:r(()=>bMe,"ToolSchema"),ToolUseContentSchema:r(()=>klt,"ToolUseContentSchema"),UnsubscribeRequestParamsSchema:r(()=>alt,"UnsubscribeRequestParamsSchema"),UnsubscribeRequestSchema:r(()=>clt,"UnsubscribeRequestSchema"),UntitledMultiSelectEnumSchemaSchema:r(()=>EMe,"UntitledMultiSelectEnumSchemaSchema"),UntitledSingleSelectEnumSchemaSchema:r(()=>TMe,"UntitledSingleSelectEnumSchemaSchema")}),Fre=r(e=>sMe.safeParse(e).success,"isJSONRPCRequest"),gXr=r(e=>aMe.safeParse(e).success,"isJSONRPCNotification"),xge=r(e=>dge.safeParse(e).success,"isJSONRPCResultResponse"),Ige=r(e=>pge.safeParse(e).success,"isJSONRPCErrorResponse"),_Xr=r(e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required","isInputRequiredResult"),rfn=r(e=>uMe.safeParse(e).success,"isInitializeRequest"),yXr=r(e=>pMe.safeParse(e).success,"isInitializedNotification"),l9s="Mcp-Param-",UYr="x-mcp-header",u9s=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,d9s=new Set(["string","integer","boolean","number"]);r(ofn,"scanXMcpHeaderDeclarations");p9s=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],f9s=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);r(xut,"pathName");vXr="=?base64?",bXr="?=";r(m9s,"mcpParamPrimitiveToString");r(h9s,"needsBase64");r(g9s,"utf8ToBase64");r(ifn,"encodeMcpParamValue");r(_9s,"valueAtPath");r(SXr,"buildMcpParamHeaders");kge=-32020,ibl=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[Du.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[kge,Du.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[Du.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[Du.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[Du.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[kge],conformance:["http-header-validation"],rationale:"SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[Du.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[kge],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],sbl={[Du.ParseError]:400,[Du.InvalidRequest]:400,[Du.MethodNotFound]:404,[Du.UnsupportedProtocolVersion]:400,[Du.MissingRequiredClientCapability]:400,[kge]:400};r(Cut,"parseSchema");r(FMe,"shapeKeys");r(Gpn,"isStandardSchema");zYr=!1,Jpn="draft-2020-12";r(y9s,"standardSchemaToJsonSchema");r(wXr,"isProvablyObjectShapedRoot");r(v9s,"formatIssue");r(Wpn,"validateStandardSchema");r(b9s,"zodEmittedPattern");S9s=/\\\.\\d\{(\d+)\}/;r(w9s,"datetimeReferenceSchemas");r(k9s,"referencePatternsForFormat");r(x9s,"isLibraryFormatPattern");r(UMe,"isJsonObject");r(T9s,"convertStandardElicitationSchema");I9s=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);r(sfn,"isAnnotationOnlyJsonSchemaKeyword");C9s=new Set(["$schema",...Object.keys(Sge.shape.requestedSchema.shape)]),$Yr={string:FMe([vge,TMe,IMe,CMe]),number:FMe([bge]),integer:FMe([bge]),boolean:FMe([xMe]),array:FMe([EMe,AMe])},E9s=new Set(vge.shape.format.unwrap().options);r(A9s,"walkProperty");r(P9s,"walkRequestedSchema");r(R9s,"describeUnsupportedProperties");r(Kpn,"findDroppedConstraintPaths");r(D9s,"normalizeElicitInputParams");r(O9s,"buildInputRequired");abl=Object.assign(O9s,{elicit(e){try{return{method:"elicitation/create",params:D9s(e)}}catch(t){throw t instanceof oh?new TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}}),M9s=!0,N9s=10,L9s=250;r(kXr,"resolveInputRequiredDriverConfig");r(F9s,"buildInputRequiredRetryParams");r(j9s,"inputRequiredRoundsExceededMessage");r(B9s,"sleep");r(U9s,"linkedRoundAbort");r(z9s,"runInputRequiredDriver");$9s=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],q9s={IdJagTokenExchangeResponseSchema:_ut,OAuthClientInformationFullSchema:NMe,OAuthClientInformationSchema:vut,OAuthClientMetadataSchema:yut,OAuthClientRegistrationErrorSchema:Bpn,OAuthErrorResponseSchema:MMe,OAuthMetadataSchema:wge,OAuthProtectedResourceMetadataSchema:RMe,OAuthTokenRevocationRequestSchema:Upn,OAuthTokensSchema:OMe,OpenIdProviderDiscoveryMetadataSchema:DMe,OpenIdProviderMetadataSchema:gut},xXr={},TXr={};r(IXr,"register");for(let e of $9s)IXr(e,c9s[e]);for(let[e,t]of Object.entries(q9s))IXr(e,t);W9s=Object.freeze(xXr),CXr=Object.freeze(TXr);r(V9s,"bootstrapOutboundCodec");Eut=6e4,H9s=[n$,lge,Rre,uge],G9s=["inputResponses","requestState"];r(qYr,"liftWireOnlyMaterial");r(WYr,"codecResultValidator");r(afn,"requestStateAccessor");J9s=afn(void 0),EXr=class{static{r(this,"Protocol")}_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{K9s=r((e,t)=>{e._negotiatedProtocolVersion=t},"writeNegotiatedProtocolVersion")}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Nct,this.setNotificationHandler("notifications/cancelled",t=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",t=>{this._onprogress(t)}),this.setRequestHandler("ping",t=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let n=e.params??{};return{...e,params:{...n,_meta:{...t,...n._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new rl(Pc.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new rl(Pc.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,a)=>{o?.(s,a),xge(s)||Ige(s)?this._onresponse(s):Fre(s)?this._onrequest(s,a):gXr(s)?this._onnotification(s,a):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let n=new rl(Pc.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let o of e.values())o(n);for(let o of t.values())o.abort(n)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:n}=qYr(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let l=BYr(t.classification);if(l!==o.era){this._onerror(new Error(`Era mismatch on inbound notification '${n.method}': classified as ${l} but this instance serves ${o.era}`));return}}if(qpn(n.method)&&!o.hasNotificationMethod(n.method))return;let s=this._notificationHandlers.get(n.method),a=this.fallbackNotificationHandler;s===void 0&&a===void 0||Promise.resolve().then(()=>s===void 0?a(n):s(n,o)).catch(l=>this._onerror(new Error(`Uncaught error in notification handler: ${l}`)))}_onrequest(e,t){let{message:n,lifted:o}=qYr(e,"request"),s=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(new Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let a=this._transport,l=r((E,R,L)=>{let U={jsonrpc:"2.0",id:n.id,error:{code:E,message:R,...L!==void 0&&{data:L}}};a?.send(U).catch(B=>this._onerror(new Error(`Failed to send an error response: ${B}`)))},"sendErrorResponse");if(t?.classification!==void 0){let E=BYr(t.classification);if(E!==s.era){this._onerror(new Error(`Era mismatch on inbound request '${n.method}': classified as ${E} but this instance serves ${s.era}`));let R=t.classification.revision??E;l(Du.UnsupportedProtocolVersion,`Unsupported protocol version: ${R}`,{supported:this._supportedProtocolVersions,requested:R});return}}if($pn(n.method)&&!s.hasRequestMethod(n.method)){l(Du.MethodNotFound,"Method not found");return}let u=this._requestHandlers.get(n.method)??this.fallbackRequestHandler;if(u===void 0){l(Du.MethodNotFound,"Method not found");return}let f=s.checkInboundEnvelope(o);if(f!==void 0){l(Du.InvalidParams,f);return}let g=r((E,R)=>this._notificationViaCodec(this._resolveOutboundCodec(E.method),E,{...R,relatedRequestId:n.id}),"sendNotification"),_=r((E,R,L)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(E.method),E,R,{...L,relatedRequestId:n.id}),"sendRequest"),b=new AbortController;this._requestHandlerAbortControllers.set(n.id,b);let w=o.inputResponses===void 0?void 0:Z9s(o.inputResponses),T={sessionId:a?.sessionId,mcpReq:{id:n.id,method:n.method,_meta:n.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...w!==void 0&&{inputResponses:w.accepted},...w!==void 0&&w.droppedKeys.length>0&&{droppedInputResponseKeys:w.droppedKeys},requestState:o.requestState===void 0?J9s:afn(o.requestState),signal:b.signal,send:r(((E,R,L)=>{let U=this._resolveOutboundCodec(E.method);if(this._assertOutboundRequestInEra(U,E.method),Gpn(R))return _(E,R,L);let B=WYr(U,E.method);if(B===void 0)throw new TypeError(`'${E.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return _(E,B,R)}),"send"),notify:g},http:t?.authInfo?{authInfo:t.authInfo}:void 0},I=this.buildContext(T,t);Promise.resolve().then(()=>u(n,I)).then(async E=>{if(b.signal.aborted)return;let R;try{R=s.encodeResult(n.method,E,this._outboundServerInfo())}catch(U){this._onerror(new Error(`Failed to encode result for ${n.method}: ${U}`)),l(Du.InternalError,"Internal error");return}let L={result:R,jsonrpc:"2.0",id:n.id};await a?.send(L)},async E=>{if(b.signal.aborted)return;let R=Number.isSafeInteger(E.code)?E.code:Du.InternalError,L={jsonrpc:"2.0",id:n.id,error:{code:s.encodeErrorCode(R),message:E.message??"Internal error",...E.data!==void 0&&{data:E.data}}};await a?.send(L)}).catch(E=>this._onerror(new Error(`Failed to send response: ${E}`))).finally(()=>{this._requestHandlerAbortControllers.get(n.id)===b&&this._requestHandlerAbortControllers.delete(n.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,o=Number(t),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(o),l=this._timeoutInfo.get(o);if(l&&a&&l.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(u){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),a(u);return}s(n)}_onresponse(e){let t=Number(e.id),n=this._responseHandlers.get(t);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),xge(e)?n(e):n(oh.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,n){let o=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(o,e.method),Gpn(t))return this._requestWithSchemaViaCodec(o,e,t,n);let s=WYr(o,e.method);if(s===void 0)throw new TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(o,e,s,t)}_negotiatedWireCodec(){return i$(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=V9s(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if($pn(t)&&!e.hasRequestMethod(t))throw new rl(Pc.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,n){let o=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,n)}_requestWithSchemaViaCodec(e,t,n,o){let{relatedRequestId:s,resumptionToken:a,onresumptiontoken:l,headers:u}=o??{},f=Date.now(),g,_;return new Promise((b,w)=>{let T=r(J=>{w(J)},"earlyReject");if(!this._transport){T(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(J){T(J);return}if(o?.signal?.aborted){let J=o.signal.reason;throw J instanceof rl?J:new rl(Pc.RequestTimeout,String(J))}let I=e.era===Iut&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,E=this._requestMessageId++;_=E;let R={...t,jsonrpc:"2.0",id:E};o?.onprogress&&(this._progressHandlers.set(E,o.onprogress),R.params={...t.params,_meta:{...t.params?._meta,progressToken:E}});let L=this._envelopeOutbound(R),U=!1,B=r(J=>{U||(this._progressHandlers.delete(E),I===void 0?this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:E,reason:String(J)}}),{relatedRequestId:s,resumptionToken:a,onresumptiontoken:l}).catch(q=>this._onerror(new Error(`Failed to send cancellation: ${q}`))):I.abort(),w(J instanceof rl?J:new rl(Pc.RequestTimeout,String(J))))},"cancel");this._responseHandlers.set(E,J=>{if(o?.signal?.aborted)return;if(U=!0,J instanceof Error)return w(J);let q;try{q=e.decodeResult(t.method,J.result)}catch(ae){return w(ae instanceof Error?ae:new Error(String(ae)))}if(q.kind==="invalid")return w(q.error);if(q.kind==="input_required"){if(o?.allowInputRequired===!0)return b(eqs(q));let ae={codec:e,request:t,resultSchema:n,options:o,flowStartedAt:f,retry:r((Ce,pe)=>this._requestWithSchemaViaCodec(e,Ce===void 0?{method:t.method}:{method:t.method,params:Ce},n,pe),"retry")};return b(this._resolveNonCompleteResult(q,ae))}let ie=q.result;Wpn(n,ie).then(ae=>{ae.success?b(ae.data):w(new rl(Pc.InvalidResult,`Invalid result for ${t.method}: ${ae.error}`))},w)}),g=r(()=>B(o?.signal?.reason),"onAbort"),o?.signal?.addEventListener("abort",g,{once:!0});let z=o?.timeout??Eut,$=r(()=>B(new rl(Pc.RequestTimeout,"Request timed out",{timeout:z})),"timeoutHandler");this._setupTimeout(E,z,o?.maxTotalTimeout,$,o?.resetTimeoutOnProgress??!1),this._transport.send(L,{relatedRequestId:s,resumptionToken:a,onresumptiontoken:l,headers:u,requestSignal:I?.signal}).catch(J=>{this._progressHandlers.delete(E),w(J)})}).finally(()=>{g&&o?.signal?.removeEventListener("abort",g),_!==void 0&&(this._responseHandlers.delete(_),this._cleanupTimeout(_))})}async notification(e,t){return this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,n){if(!this._transport)throw new rl(Pc.NotConnected,"Not connected");if(qpn(t.method)&&!e.hasNotificationMethod(t.method))throw new rl(Pc.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let o=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!n?.relatedRequestId){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(o,n).catch(s=>this._onerror(s))});return}await this._transport.send(o,n)}setRequestHandler(e,t,n){this.assertRequestHandlerCapability(e);let o;if(typeof t=="function"){if(!$pn(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=r((s,a)=>{let l=this._negotiatedWireCodec(),u=l.validateRequest(e,s);if(!u.ok&&u.reason==="not-in-era"&&(u=l.validateInputRequest(e,s)),!u.ok)throw u.reason==="not-in-era"?new oh(Du.InternalError,`No wire schema for ${e} in the resolved era`):new Error(u.message);return Promise.resolve(t(u.value,a))},"stored")}else if(n)o=r(async(s,a)=>{let l=await Wpn(t.params,{...s.params});if(!l.success)throw new oh(Du.InvalidParams,`Invalid params for ${e}: ${l.error}`);return n(l.data,a)},"stored");else throw new TypeError("setRequestHandler: handler is required");this._requestHandlers.set(e,this._wrapHandler(e,o))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,n){if(typeof t=="function"){if(!qpn(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(o,s)=>{let a=s.validateNotification(e,o);if(!a.ok)throw a.reason==="not-in-era"?new oh(Du.InternalError,`No wire schema for ${e} in the resolved era`):new Error(a.message);return Promise.resolve(t(a.value))});return}if(!n)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async o=>{let s=await Wpn(t.params,{...o.params});if(!s.success)throw new oh(Du.InvalidParams,`Invalid params for notification ${e}: ${s.error}`);await n(s.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};r(BMe,"isPlainObject$1");r(AXr,"mergeCapabilities");r(Tut,"isPlainObject");r(Z9s,"partitionInputResponses");r(VYr,"relatedMessagingUnavailable");r(Y9s,"synthesizeInputRequestContext");r(X9s,"dispatchInputRequest");r(Q9s,"buildRetryLegRequestOptions");r(PXr,"runInputRequiredFlow");r(eqs,"manualInputRequiredValue");tqs=qs((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,n=/\\([\u000b\u0020-\u00ff])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=s;function s(u){if(!u)throw new TypeError("argument string is required");var f=typeof u=="object"?a(u):u;if(typeof f!="string")throw new TypeError("argument string is required to be a string");var g=f.indexOf(";"),_=g!==-1?f.slice(0,g).trim():f.trim();if(!o.test(_))throw new TypeError("invalid media type");var b=new l(_.toLowerCase());if(g!==-1){var w,T,I;for(t.lastIndex=g;T=t.exec(f);){if(T.index!==g)throw new TypeError("invalid parameter format");g+=T[0].length,w=T[1].toLowerCase(),I=T[2],I.charCodeAt(0)===34&&(I=I.slice(1,-1),I.indexOf("\\")!==-1&&(I=I.replace(n,"$1"))),b.parameters[w]=I}if(g!==f.length)throw new TypeError("invalid parameter format")}return b}r(s,"parse");function a(u){var f;if(typeof u.getHeader=="function"?f=u.getHeader("content-type"):typeof u.headers=="object"&&(f=u.headers&&u.headers["content-type"]),typeof f!="string")throw new TypeError("content-type header is missing from object");return f}r(a,"getcontenttype");function l(u){this.parameters=Object.create(null),this.type=u}r(l,"ContentType")})),nqs=Mct(tqs(),1);r(RXr,"mediaTypeEssence");DXr=10*1024*1024,cfn=class{static{r(this,"ReadBuffer")}_buffer;_maxBufferSize;constructor(e){this._maxBufferSize=e?.maxBufferSize??DXr}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){for(;this._buffer;){let e=this._buffer.indexOf(`
|
|
2139
2139
|
`);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");this._buffer=this._buffer.subarray(e+1);try{return OXr(t)}catch(n){if(n instanceof SyntaxError)continue;throw n}}return null}clear(){this._buffer=void 0}};r(OXr,"deserializeMessage");r(lfn,"serializeMessage");r(zMe,"normalizeHeaders");r(ufn,"createFetchWithInit")});function pfn(e){let t=new e({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return yWs(t),t}var Put,MXr,Ld,Nf,KF,Dut,rqs,NXr,LXr,Rut,oqs,ZF,iqs,sqs,FXr,aqs,Out,Cge,qMe,Ege,Mut,cqs,jXr,lqs,uqs,dqs,ffn,pqs,mfn,BXr,fqs,mqs,hqs,gqs,_qs,yqs,vqs,bqs,hfn,Sqs,wqs,kqs,UXr,zXr,$Xr,xqs,Tqs,Iqs,gfn,Cqs,qXr,Eqs,Aqs,Pqs,Rqs,Dqs,Oqs,Mqs,Nqs,WXr,Lqs,VXr,HXr,GXr,Fqs,_fn,jqs,JXr,KXr,ZXr,Bqs,Uqs,YXr,zqs,$qs,qqs,XXr,Wqs,Vqs,QXr,Hqs,Gqs,Jqs,Kqs,Zqs,Yqs,Xqs,Qqs,eWs,tWs,nWs,rWs,oWs,iWs,sWs,aWs,cWs,lWs,uWs,dWs,pWs,fWs,mWs,eQr,hWs,gWs,_Ws,yWs,yfn,bbl,tQr=Y(()=>{hpn();gpn();Put=qs((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{static{r(this,"_CodeOrName")}};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{static{r(this,"Name")}constructor(L){if(super(),!e.IDENTIFIER.test(L))throw new Error("CodeGen: name must be a valid identifier");this.str=L}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var o=class extends t{static{r(this,"_Code")}constructor(L){super(),this._items=typeof L=="string"?[L]:L}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let L=this._items[0];return L===""||L==='""'}get str(){var L;return(L=this._str)!==null&&L!==void 0?L:this._str=this._items.reduce((U,B)=>`${U}${B}`,"")}get names(){var L;return(L=this._names)!==null&&L!==void 0?L:this._names=this._items.reduce((U,B)=>(B instanceof n&&(U[B.str]=(U[B.str]||0)+1),U),{})}};e._Code=o,e.nil=new o("");function s(L,...U){let B=[L[0]],z=0;for(;z<U.length;)u(B,U[z]),B.push(L[++z]);return new o(B)}r(s,"_"),e._=s;let a=new o("+");function l(L,...U){let B=[T(L[0])],z=0;for(;z<U.length;)B.push(a),u(B,U[z]),B.push(a,T(L[++z]));return f(B),new o(B)}r(l,"str"),e.str=l;function u(L,U){U instanceof o?L.push(...U._items):U instanceof n?L.push(U):L.push(b(U))}r(u,"addCodeArg"),e.addCodeArg=u;function f(L){let U=1;for(;U<L.length-1;){if(L[U]===a){let B=g(L[U-1],L[U+1]);if(B!==void 0){L.splice(U-1,3,B);continue}L[U++]="+"}U++}}r(f,"optimize");function g(L,U){if(U==='""')return L;if(L==='""')return U;if(typeof L=="string")return U instanceof n||L[L.length-1]!=='"'?void 0:typeof U!="string"?`${L.slice(0,-1)}${U}"`:U[0]==='"'?L.slice(0,-1)+U.slice(1):void 0;if(typeof U=="string"&&U[0]==='"'&&!(L instanceof n))return`"${L}${U.slice(1)}`}r(g,"mergeExprItems");function _(L,U){return U.emptyStr()?L:L.emptyStr()?U:l`${L}${U}`}r(_,"strConcat"),e.strConcat=_;function b(L){return typeof L=="number"||typeof L=="boolean"||L===null?L:T(Array.isArray(L)?L.join(","):L)}r(b,"interpolate");function w(L){return new o(T(L))}r(w,"stringify"),e.stringify=w;function T(L){return JSON.stringify(L).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}r(T,"safeStringify"),e.safeStringify=T;function I(L){return typeof L=="string"&&e.IDENTIFIER.test(L)?new o(`.${L}`):s`[${L}]`}r(I,"getProperty"),e.getProperty=I;function E(L){if(typeof L=="string"&&e.IDENTIFIER.test(L))return new o(`${L}`);throw new Error(`CodeGen: invalid export name: ${L}, use explicit $id name mapping`)}r(E,"getEsmExportName"),e.getEsmExportName=E;function R(L){return new o(L.toString())}r(R,"regexpCode"),e.regexpCode=R})),MXr=qs((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Put();var n=class extends Error{static{r(this,"ValueError")}constructor(f){super(`CodeGen: "code" for ${f} not defined`),this.value=f.value}},o;(function(f){f[f.Started=0]="Started",f[f.Completed=1]="Completed"})(o||(e.UsedValueState=o={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};var s=class{static{r(this,"Scope")}constructor({prefixes:f,parent:g}={}){this._names={},this._prefixes=f,this._parent=g}toName(f){return f instanceof t.Name?f:this.name(f)}name(f){return new t.Name(this._newName(f))}_newName(f){let g=this._names[f]||this._nameGroup(f);return`${f}${g.index++}`}_nameGroup(f){var g,_;if(!((_=(g=this._parent)===null||g===void 0?void 0:g._prefixes)===null||_===void 0)&&_.has(f)||this._prefixes&&!this._prefixes.has(f))throw new Error(`CodeGen: prefix "${f}" is not allowed in this scope`);return this._names[f]={prefix:f,index:0}}};e.Scope=s;var a=class extends t.Name{static{r(this,"ValueScopeName")}constructor(f,g){super(g),this.prefix=f}setValue(f,{property:g,itemIndex:_}){this.value=f,this.scopePath=(0,t._)`.${new t.Name(g)}[${_}]`}};e.ValueScopeName=a;let l=(0,t._)`\n`;var u=class extends s{static{r(this,"ValueScope")}constructor(f){super(f),this._values={},this._scope=f.scope,this.opts={...f,_n:f.lines?l:t.nil}}get(){return this._scope}name(f){return new a(f,this._newName(f))}value(f,g){var _;if(g.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let b=this.toName(f),{prefix:w}=b,T=(_=g.key)!==null&&_!==void 0?_:g.ref,I=this._values[w];if(I){let L=I.get(T);if(L)return L}else I=this._values[w]=new Map;I.set(T,b);let E=this._scope[w]||(this._scope[w]=[]),R=E.length;return E[R]=g.ref,b.setValue(g,{property:w,itemIndex:R}),b}getValue(f,g){let _=this._values[f];if(_)return _.get(g)}scopeRefs(f,g=this._values){return this._reduceValues(g,_=>{if(_.scopePath===void 0)throw new Error(`CodeGen: name "${_}" has no value`);return(0,t._)`${f}${_.scopePath}`})}scopeCode(f=this._values,g,_){return this._reduceValues(f,b=>{if(b.value===void 0)throw new Error(`CodeGen: name "${b}" has no value`);return b.value.code},g,_)}_reduceValues(f,g,_={},b){let w=t.nil;for(let T in f){let I=f[T];if(!I)continue;let E=_[T]=_[T]||new Map;I.forEach(R=>{if(E.has(R))return;E.set(R,o.Started);let L=g(R);if(L){let U=this.opts.es5?e.varKinds.var:e.varKinds.const;w=(0,t._)`${w}${U} ${R} = ${L};${this.opts._n}`}else if(L=b?.(R))w=(0,t._)`${w}${L}${this.opts._n}`;else throw new n(R);E.set(R,o.Completed)})}return w}};e.ValueScope=u})),Ld=qs((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=Put(),n=MXr();var o=Put();Object.defineProperty(e,"_",{enumerable:!0,get:r(function(){return o._},"get")}),Object.defineProperty(e,"str",{enumerable:!0,get:r(function(){return o.str},"get")}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:r(function(){return o.strConcat},"get")}),Object.defineProperty(e,"nil",{enumerable:!0,get:r(function(){return o.nil},"get")}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:r(function(){return o.getProperty},"get")}),Object.defineProperty(e,"stringify",{enumerable:!0,get:r(function(){return o.stringify},"get")}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:r(function(){return o.regexpCode},"get")}),Object.defineProperty(e,"Name",{enumerable:!0,get:r(function(){return o.Name},"get")});var s=MXr();Object.defineProperty(e,"Scope",{enumerable:!0,get:r(function(){return s.Scope},"get")}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:r(function(){return s.ValueScope},"get")}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:r(function(){return s.ValueScopeName},"get")}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:r(function(){return s.varKinds},"get")}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};var a=class{static{r(this,"Node")}optimizeNodes(){return this}optimizeNames(Je,Xe){return this}},l=class extends a{static{r(this,"Def")}constructor(Je,Xe,_t){super(),this.varKind=Je,this.name=Xe,this.rhs=_t}render({es5:Je,_n:Xe}){let _t=Je?n.varKinds.var:this.varKind,Dt=this.rhs===void 0?"":` = ${this.rhs}`;return`${_t} ${this.name}${Dt};`+Xe}optimizeNames(Je,Xe){if(Je[this.name.str])return this.rhs&&(this.rhs=Pe(this.rhs,Je,Xe)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},u=class extends a{static{r(this,"Assign")}constructor(Je,Xe,_t){super(),this.lhs=Je,this.rhs=Xe,this.sideEffects=_t}render({_n:Je}){return`${this.lhs} = ${this.rhs};`+Je}optimizeNames(Je,Xe){if(!(this.lhs instanceof t.Name&&!Je[this.lhs.str]&&!this.sideEffects))return this.rhs=Pe(this.rhs,Je,Xe),this}get names(){return rt(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},f=class extends u{static{r(this,"AssignOp")}constructor(Je,Xe,_t,Dt){super(Je,_t,Dt),this.op=Xe}render({_n:Je}){return`${this.lhs} ${this.op}= ${this.rhs};`+Je}},g=class extends a{static{r(this,"Label")}constructor(Je){super(),this.label=Je,this.names={}}render({_n:Je}){return`${this.label}:`+Je}},_=class extends a{static{r(this,"Break")}constructor(Je){super(),this.label=Je,this.names={}}render({_n:Je}){return`break${this.label?` ${this.label}`:""};`+Je}},b=class extends a{static{r(this,"Throw")}constructor(Je){super(),this.error=Je}render({_n:Je}){return`throw ${this.error};`+Je}get names(){return this.error.names}},w=class extends a{static{r(this,"AnyCode")}constructor(Je){super(),this.code=Je}render({_n:Je}){return`${this.code};`+Je}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(Je,Xe){return this.code=Pe(this.code,Je,Xe),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},T=class extends a{static{r(this,"ParentNode")}constructor(Je=[]){super(),this.nodes=Je}render(Je){return this.nodes.reduce((Xe,_t)=>Xe+_t.render(Je),"")}optimizeNodes(){let{nodes:Je}=this,Xe=Je.length;for(;Xe--;){let _t=Je[Xe].optimizeNodes();Array.isArray(_t)?Je.splice(Xe,1,..._t):_t?Je[Xe]=_t:Je.splice(Xe,1)}return Je.length>0?this:void 0}optimizeNames(Je,Xe){let{nodes:_t}=this,Dt=_t.length;for(;Dt--;){let gn=_t[Dt];gn.optimizeNames(Je,Xe)||(Tt(Je,gn.names),_t.splice(Dt,1))}return _t.length>0?this:void 0}get names(){return this.nodes.reduce((Je,Xe)=>ze(Je,Xe.names),{})}},I=class extends T{static{r(this,"BlockNode")}render(Je){return"{"+Je._n+super.render(Je)+"}"+Je._n}},E=class extends T{static{r(this,"Root")}},R=class extends I{static{r(this,"Else")}};R.kind="else";var L=class Aut extends I{static{r(this,"If")}constructor(Xe,_t){super(_t),this.condition=Xe}render(Xe){let _t=`if(${this.condition})`+super.render(Xe);return this.else&&(_t+="else "+this.else.render(Xe)),_t}optimizeNodes(){super.optimizeNodes();let Xe=this.condition;if(Xe===!0)return this.nodes;let _t=this.else;if(_t){let Dt=_t.optimizeNodes();_t=this.else=Array.isArray(Dt)?new R(Dt):Dt}if(_t)return Xe===!1?_t instanceof Aut?_t:_t.nodes:this.nodes.length?this:new Aut(Ye(Xe),_t instanceof Aut?[_t]:_t.nodes);if(!(Xe===!1||!this.nodes.length))return this}optimizeNames(Xe,_t){var Dt;if(this.else=(Dt=this.else)===null||Dt===void 0?void 0:Dt.optimizeNames(Xe,_t),!!(super.optimizeNames(Xe,_t)||this.else))return this.condition=Pe(this.condition,Xe,_t),this}get names(){let Xe=super.names;return rt(Xe,this.condition),this.else&&ze(Xe,this.else.names),Xe}};L.kind="if";var U=class extends I{static{r(this,"For")}};U.kind="for";var B=class extends U{static{r(this,"ForLoop")}constructor(Je){super(),this.iteration=Je}render(Je){return`for(${this.iteration})`+super.render(Je)}optimizeNames(Je,Xe){if(super.optimizeNames(Je,Xe))return this.iteration=Pe(this.iteration,Je,Xe),this}get names(){return ze(super.names,this.iteration.names)}},z=class extends U{static{r(this,"ForRange")}constructor(Je,Xe,_t,Dt){super(),this.varKind=Je,this.name=Xe,this.from=_t,this.to=Dt}render(Je){let Xe=Je.es5?n.varKinds.var:this.varKind,{name:_t,from:Dt,to:gn}=this;return`for(${Xe} ${_t}=${Dt}; ${_t}<${gn}; ${_t}++)`+super.render(Je)}get names(){return rt(rt(super.names,this.from),this.to)}},$=class extends U{static{r(this,"ForIter")}constructor(Je,Xe,_t,Dt){super(),this.loop=Je,this.varKind=Xe,this.name=_t,this.iterable=Dt}render(Je){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(Je)}optimizeNames(Je,Xe){if(super.optimizeNames(Je,Xe))return this.iterable=Pe(this.iterable,Je,Xe),this}get names(){return ze(super.names,this.iterable.names)}},J=class extends I{static{r(this,"Func")}constructor(Je,Xe,_t){super(),this.name=Je,this.args=Xe,this.async=_t}render(Je){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(Je)}};J.kind="func";var q=class extends T{static{r(this,"Return")}render(Je){return"return "+super.render(Je)}};q.kind="return";var ie=class extends I{static{r(this,"Try")}render(Je){let Xe="try"+super.render(Je);return this.catch&&(Xe+=this.catch.render(Je)),this.finally&&(Xe+=this.finally.render(Je)),Xe}optimizeNodes(){var Je,Xe;return super.optimizeNodes(),(Je=this.catch)===null||Je===void 0||Je.optimizeNodes(),(Xe=this.finally)===null||Xe===void 0||Xe.optimizeNodes(),this}optimizeNames(Je,Xe){var _t,Dt;return super.optimizeNames(Je,Xe),(_t=this.catch)===null||_t===void 0||_t.optimizeNames(Je,Xe),(Dt=this.finally)===null||Dt===void 0||Dt.optimizeNames(Je,Xe),this}get names(){let Je=super.names;return this.catch&&ze(Je,this.catch.names),this.finally&&ze(Je,this.finally.names),Je}},ae=class extends I{static{r(this,"Catch")}constructor(Je){super(),this.error=Je}render(Je){return`catch(${this.error})`+super.render(Je)}};ae.kind="catch";var Ce=class extends I{static{r(this,"Finally")}render(Je){return"finally"+super.render(Je)}};Ce.kind="finally";var pe=class{static{r(this,"CodeGen")}constructor(Je,Xe={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...Xe,_n:Xe.lines?`
|
|
@@ -15356,7 +15356,7 @@ ${znc}${_?` (traceId: ${_})`:""}
|
|
|
15356
15356
|
`),1;let b=B3e(t);if(b?.type==="known"&&b.name==="help")return e.stdout.write(`${z3e(b.args,await Lei(s))}
|
|
15357
15357
|
`),0;if(b?.type==="known"&&b.name==="skill"&&!b.skillName)return await MTt(e,o,s,[]);if(b?.type==="known"&&b.name==="login")return b.args.length>0?(e.stderr.write(`Usage: /login
|
|
15358
15358
|
`),1):await vTt(e,o,s,!1);if(b?.type==="known"&&b.name==="logout")return b.args.length>0?(e.stderr.write(`Usage: /logout
|
|
15359
|
-
`),1):await bTt(e,o,s);let w=b?.type==="known"&&b.name==="skill"?U3e(b.skillName,b.task):t,T,I,E,R,L,U,B=r(()=>{U?.(),U=void 0},"stopObservingEvents"),z,$=new AbortController,J=Math.max(1,Math.trunc(s.shutdownCleanupTimeoutMs??nGe)),q=r(async()=>{let ae=I;E??=(async()=>{await FL(async()=>ae?.close?.(),J),await FL(async()=>R?.close(),J),await FL(async()=>L?.(),J),z?.dispose()})(),await E},"closeApp"),ie=rGe({abort:r(ae=>$.abort(new Error(`CLI received ${ae}`)),"abort"),cleanup:q,cleanupTimeoutMs:s.shutdownCleanupTimeoutMs,exitProcess:s.exitProcess,process:s.shutdownProcess});try{let ae=s.env??process.env,Ce=(s.cwd??process.cwd)(),pe=(s.loadDotenv??rA)({cwd:Ce,env:ae});if(pe.error)throw new Error(`Failed to load environment file: ${pe.path}`,{cause:pe.error});let ze=await OTt(u,Ce,ae,s),rt=s.createZCodeApp?void 0:await Qg(),Pe=s.createZCodeApp??rt?.createZCodeApp;if(!Pe)throw new Error("ZCode app factory is unavailable.");let Tt=Lnc(o),Ye;if(Tt&&(Ye=s.mapSessionEvent??rt?.mapSessionEvent,!Ye))throw new Error("Event streaming is unavailable: the bootstrap module did not load.");let Fe=xei({...Ye?{mapSessionEvent:Ye}:{},options:o,stderr:e.stderr,stdout:e.stdout}),St=s.prepareZCodeTelemetryEnv??rt?.prepareZCodeTelemetryEnv;St&&(L=s.shutdownZCodeTelemetry??rt?.shutdownZCodeTelemetry);let kt=St?await St(ae,{cliVersion:a,productVersion:ae.ZCODE_APP_VERSION}):ae,st=s.startProcessProviderRegistryRuntime??rt?.startProcessProviderRegistryRuntime;if(!st)throw new Error("Provider Registry runtime is unavailable.");z=await st(kt,s.skipUserConfig?{}:{standalone:{...gPe(e.stderr),...s.userConfigPath?{legacyCliUserConfigFilePath:s.userConfigPath}:{}}});let jt=(s.createProviderEndpointRoutingPort??rt?.createDefaultProviderEndpointRoutingPort)?.({appVersion:a,env:ae,workingDirectory:Ce});if(R=ATt(o,s),I=await Pe({browserControlPort:R?.browserControlPort,env:kt,permissionBroker:wei(),...jt?{providerEndpointRoutingPort:jt}:{},providerRegistry:z.runtime.registryService,configuredDefaultModelSelection:z.configuredDefaultModelSelection,...z.providerRuntimeHeadersPort?{providerRuntimeHeadersPort:z.providerRuntimeHeadersPort}:{},resume:ze!==void 0,runtimeConfig:{...l?{mode:l}:{},...f?{toolDisallowlist:f}:{},...g?{midConversationSystem:{mode:"force"}}:{},memory:{extractionEnabled:o.memoryBench===!0},modelStreaming:"on",presentationSurface:_,workingDirectory:Ce},sessionId:ze,uiDetectedLocale:o.detectedLocale,uiLocale:o.locale,version:a}),$.signal.aborted){let on=I;throw I=void 0,await FL(async()=>on.close?.(),J),$.signal.reason}if(T=I.traceId,o.memoryBench&&!I.runtime.isProjectMemoryEnabled())throw new Error(Unc);if(b&&await Wnc(b,s))return await Gnc(e,o,I,t,l,T,$.signal,s);U=RTt(I.runtime)?.({onSessionEvent:Fe.observe});let Xe=Iei(I.runtime),_t=await I.submitPrompt(n.length>0?{text:w,attachments:n.map(on=>({type:$nc(on),path:on}))}:w,{abortSignal:$.signal,...U?{}:{onEvent:Fe.observe}});Fe.beginWaitPhase(_t.turnId?String(_t.turnId):void 0),T=_t.traceId??T,Fe.hasWorkflowActivity()&&Xe&&await Tei({runtime:Xe,signal:$.signal}),o.memoryBench&&(await I.runtime.drainMemoryExtractions(null),$.signal.throwIfAborted()),B();let Dt=[_t.response,...Fe.waitPhaseTurnResponses()].filter(on=>on.trim().length>0),gn=Dt.at(-1)??_t.response,cn=Dt.length>1,Fn=await Knc({bootstrapModule:rt,deps:s,events:_t.events,workingDirectory:Ce});return Tt?(e.stdout.write(`${JSON.stringify({type:"result",sessionId:I.sessionId,traceId:T,..._t.turnId?{turnId:_t.turnId}:{},response:gn,...cn?{turnResponses:Dt}:{},..._t.usage?{usage:{..._t.usage}}:{},eventCount:_t.events.length,projection:{status:_t.projection.status,turnCount:_t.projection.turnCount,totalTokenCount:_t.projection.totalTokenCount,contextUsed:_t.projection.contextUsed??null,contextWindow:_t.projection.contextWindow??null}})}
|
|
15359
|
+
`),1):await bTt(e,o,s);let w=b?.type==="known"&&b.name==="skill"?U3e(b.skillName,b.task):t,T,I,E,R,L,U,B=r(()=>{U?.(),U=void 0},"stopObservingEvents"),z,$=new AbortController,J=Math.max(1,Math.trunc(s.shutdownCleanupTimeoutMs??nGe)),q=r(async()=>{let ae=I;E??=(async()=>{await FL(async()=>ae?.close?.(),J),await FL(async()=>R?.close(),J),await FL(async()=>L?.(),J),z?.dispose()})(),await E},"closeApp"),ie=rGe({abort:r(ae=>$.abort(new Error(`CLI received ${ae}`)),"abort"),cleanup:q,cleanupTimeoutMs:s.shutdownCleanupTimeoutMs,exitProcess:s.exitProcess,process:s.shutdownProcess});try{let ae=s.env??process.env,Ce=(s.cwd??process.cwd)(),pe=(s.loadDotenv??rA)({cwd:Ce,env:ae});if(pe.error)throw new Error(`Failed to load environment file: ${pe.path}`,{cause:pe.error});let ze=await OTt(u,Ce,ae,s),rt=s.createZCodeApp?void 0:await Qg(),Pe=s.createZCodeApp??rt?.createZCodeApp;if(!Pe)throw new Error("ZCode app factory is unavailable.");let Tt=Lnc(o),Ye;if(Tt&&(Ye=s.mapSessionEvent??rt?.mapSessionEvent,!Ye))throw new Error("Event streaming is unavailable: the bootstrap module did not load.");let Fe=xei({...Ye?{mapSessionEvent:Ye}:{},options:o,stderr:e.stderr,stdout:e.stdout}),St=s.prepareZCodeTelemetryEnv??rt?.prepareZCodeTelemetryEnv;St&&(L=s.shutdownZCodeTelemetry??rt?.shutdownZCodeTelemetry);let kt=St?await St(ae,{cliVersion:a,productVersion:ae.ZCODE_APP_VERSION}):ae,st=s.startProcessProviderRegistryRuntime??rt?.startProcessProviderRegistryRuntime;if(!st)throw new Error("Provider Registry runtime is unavailable.");z=await st(kt,s.skipUserConfig?{}:{standalone:{...gPe(e.stderr),...s.userConfigPath?{legacyCliUserConfigFilePath:s.userConfigPath}:{}}});let jt=(s.createProviderEndpointRoutingPort??rt?.createDefaultProviderEndpointRoutingPort)?.({appVersion:a,env:ae,workingDirectory:Ce});if(R=ATt(o,s),I=await Pe({browserControlPort:R?.browserControlPort,env:kt,permissionBroker:wei(),...jt?{providerEndpointRoutingPort:jt}:{},providerRegistry:z.runtime.registryService,configuredDefaultModelSelection:z.configuredDefaultModelSelection,...z.providerRuntimeHeadersPort?{providerRuntimeHeadersPort:z.providerRuntimeHeadersPort}:{},resume:ze!==void 0,runtimeConfig:{...l?{mode:l}:{},...f?{toolDisallowlist:f}:{},...g?{midConversationSystem:{mode:"force"}}:{},memory:{extractionEnabled:o.memoryBench===!0},modelStreaming:"on",presentationSurface:_,workingDirectory:Ce},sessionId:ze,uiDetectedLocale:o.detectedLocale,uiLocale:o.locale,version:a}),$.signal.aborted){let on=I;throw I=void 0,await FL(async()=>on.close?.(),J),$.signal.reason}if(process.env.ZCODE_CLI_PROMPT_MODEL)await I.setModel(process.env.ZCODE_CLI_PROMPT_MODEL,{transient:true});if(T=I.traceId,o.memoryBench&&!I.runtime.isProjectMemoryEnabled())throw new Error(Unc);if(b&&await Wnc(b,s))return await Gnc(e,o,I,t,l,T,$.signal,s);U=RTt(I.runtime)?.({onSessionEvent:Fe.observe});let Xe=Iei(I.runtime),_t=await I.submitPrompt(n.length>0?{text:w,attachments:n.map(on=>({type:$nc(on),path:on}))}:w,{abortSignal:$.signal,...U?{}:{onEvent:Fe.observe}});Fe.beginWaitPhase(_t.turnId?String(_t.turnId):void 0),T=_t.traceId??T,Fe.hasWorkflowActivity()&&Xe&&await Tei({runtime:Xe,signal:$.signal}),o.memoryBench&&(await I.runtime.drainMemoryExtractions(null),$.signal.throwIfAborted()),B();let Dt=[_t.response,...Fe.waitPhaseTurnResponses()].filter(on=>on.trim().length>0),gn=Dt.at(-1)??_t.response,cn=Dt.length>1,Fn=await Knc({bootstrapModule:rt,deps:s,events:_t.events,workingDirectory:Ce});return Tt?(e.stdout.write(`${JSON.stringify({type:"result",sessionId:I.sessionId,traceId:T,..._t.turnId?{turnId:_t.turnId}:{},response:gn,...cn?{turnResponses:Dt}:{},..._t.usage?{usage:{..._t.usage}}:{},eventCount:_t.events.length,projection:{status:_t.projection.status,turnCount:_t.projection.turnCount,totalTokenCount:_t.projection.totalTokenCount,contextUsed:_t.projection.contextUsed??null,contextWindow:_t.projection.contextWindow??null}})}
|
|
15360
15360
|
`),0):Nei(o)?(e.stdout.write(e0({sessionId:I.sessionId,traceId:T,..._t.turnId?{turnId:_t.turnId}:{},response:gn,...cn?{turnResponses:Dt}:{},..._t.usage?{usage:{..._t.usage}}:{},eventCount:_t.events.length,...Fn?{workspaceHookTrust:{workspacePath:Fn.workspacePath,workspaceIdentity:Fn.workspaceIdentity,bundleDigest:Fn.bundleDigest,reasonCode:Fn.reasonCode,items:Fn.items.map(on=>({reviewItemId:on.reviewItemId,event:on.event,matcher:on.matcher,displayCommand:on.displayCommand,sourcePath:on.sourcePath,configuredEnabled:on.configuredEnabled,hookDeclarationDigest:on.hookDeclarationDigest,trustState:on.trustState}))}}:{},projection:{status:_t.projection.status,turnCount:_t.projection.turnCount,totalTokenCount:_t.projection.totalTokenCount,contextUsed:_t.projection.contextUsed??null,contextWindow:_t.projection.contextWindow??null}})),0):(Fn&&Ync(e,Fn),e.stdout.write(`${Dt.join(`
|
|
15361
15361
|
|
|
15362
15362
|
`)}
|
|
@@ -15417,7 +15417,7 @@ Commands:
|
|
|
15417
15417
|
Scopes: user (default), project. \`zcode plugin\` is an alias of \`zcode plugins\`.`;r(Zei,"runPluginsCommand");r(nrc,"runPluginsListCommand");r(rrc,"runPluginsInstallCommand");r(orc,"runPluginsUpdateCommand");r(irc,"reportInstallOutcome");r(Yei,"runPluginsSetCommand");r(src,"runPluginsDisableCommand");r(arc,"runPluginsUninstallCommand");r(crc,"runPluginsValidateCommand")});function urc(e=process.env){let t=e.ZCODE_STORAGE_DIR?.trim()||(0,dse.join)((0,eti.homedir)(),".zcode");return(0,dse.join)(t,"clipboard")}function tti(e={}){let t=e.platform??process.platform,n=e.maxBytes??lrc,o=e.runCommand??mrc,s=e.tempDirectory??urc(e.processEnv);return async(a={})=>t==="darwin"?await drc({maxBytes:n,runCommand:o,signal:a.abortSignal,tempDirectory:s}):t==="linux"?await prc({maxBytes:n,runCommand:o,signal:a.abortSignal}):t==="win32"?await frc({maxBytes:n,runCommand:o,signal:a.abortSignal,tempDirectory:s}):null}async function drc(e){await(0,M4.mkdir)(e.tempDirectory,{recursive:!0});let t=await(0,M4.mkdtemp)((0,dse.join)(e.tempDirectory,"zcode-clipboard-")),n=(0,dse.join)(t,"clipboard.png");try{return(await e.runCommand("osascript",["-e","set png_data to (the clipboard as \xABclass PNGf\xBB)","-e",`set fp to open for access POSIX file ${hrc(n)} with write permission`,"-e","write png_data to fp","-e","close access fp"],{maxBytes:e.maxBytes,signal:e.signal})).exitCode!==0?null:await nti(n,"image/png",e.maxBytes)}finally{await(0,M4.rm)(t,{force:!0,recursive:!0})}}async function prc(e){let t=[{args:["--type","image/png"],file:"wl-paste",mediaType:"image/png"},{args:["--type","image/jpeg"],file:"wl-paste",mediaType:"image/jpeg"},{args:["--type","image/gif"],file:"wl-paste",mediaType:"image/gif"},{args:["--type","image/webp"],file:"wl-paste",mediaType:"image/webp"},{args:["-selection","clipboard","-t","image/png","-o"],file:"xclip",mediaType:"image/png"},{args:["-selection","clipboard","-t","image/jpeg","-o"],file:"xclip",mediaType:"image/jpeg"},{args:["-selection","clipboard","-t","image/gif","-o"],file:"xclip",mediaType:"image/gif"},{args:["-selection","clipboard","-t","image/webp","-o"],file:"xclip",mediaType:"image/webp"}];for(let n of t){let o=await e.runCommand(n.file,n.args,{maxBytes:e.maxBytes,signal:e.signal}),s=rti(o.stdout,n.mediaType,e.maxBytes);if(o.exitCode===0&&s)return s}return null}async function frc(e){await(0,M4.mkdir)(e.tempDirectory,{recursive:!0});let t=await(0,M4.mkdtemp)((0,dse.join)(e.tempDirectory,"zcode-clipboard-")),n=(0,dse.join)(t,"clipboard.png"),o=["Add-Type -AssemblyName System.Windows.Forms;","$img = Get-Clipboard -Format Image;","if ($null -eq $img) { exit 2 }",`$img.Save(${grc(n)}, [System.Drawing.Imaging.ImageFormat]::Png);`].join(" ");try{return(await e.runCommand("powershell.exe",["-NoProfile","-NonInteractive","-Command",o],{maxBytes:e.maxBytes,signal:e.signal})).exitCode!==0?null:await nti(n,"image/png",e.maxBytes)}finally{await(0,M4.rm)(t,{force:!0,recursive:!0})}}async function nti(e,t,n){let o=await(0,M4.readFile)(e);return rti(o,t,n)}function rti(e,t,n){return e.byteLength===0||e.byteLength>n?null:{dataUrl:`data:${t};base64,${e.toString("base64")}`,mediaType:t,sizeBytes:e.byteLength}}async function mrc(e,t,n){return await new Promise(o=>{let s;try{s=(0,Qei.spawn)(e,t,{signal:n.signal,stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{o({exitCode:-1,stdout:Buffer.alloc(0)});return}let a=[],l=0,u=!1,f=r(g=>{u||(u=!0,o(g))},"finish");s.stdout?.on("data",g=>{if(l+=g.byteLength,l>n.maxBytes){s.kill();return}a.push(g)}),s.on("error",()=>f({exitCode:-1,stdout:Buffer.alloc(0)})),s.on("close",(g,_)=>{f({exitCode:g,signal:_,stdout:Buffer.concat(a)})})})}function hrc(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function grc(e){return`'${e.replace(/'/g,"''")}'`}var Qei,M4,eti,dse,lrc,oti=Y(()=>{"use strict";Qei=require("node:child_process"),M4=require("node:fs/promises"),eti=require("node:os"),dse=require("node:path"),lrc=20*1024*1024;r(urc,"resolveDefaultClipboardDirectory");r(tti,"createNodeClipboardImageReader");r(drc,"readMacClipboardImage");r(prc,"readLinuxClipboardImage");r(frc,"readWindowsClipboardImage");r(nti,"readImageFile");r(rti,"bufferToClipboardImage");r(mrc,"runCommandBuffer");r(hrc,"appleScriptString");r(grc,"powershellString")});function sti(e={}){let t=e.maxBytes??_rc,n=e.platform??process.platform,o=e.runCommand??Irc;return async s=>{let a=Trc(s,t);if(a.byteLength===0)return;let l=wrc(e.stdout,a),u=await krc({input:s,platform:n,runCommand:o});if(!l&&!u)throw new Error("No text clipboard target accepted the selected text.")}}function wrc(e,t){if(!e)return!1;try{return e.write(`${vrc}${yrc};${t.toString("base64")}${brc}`),!0}catch{return!1}}async function krc(e){for(let t of xrc(e.platform))if((await e.runCommand(t.file,t.args,{input:e.input})).exitCode===0)return!0;return!1}function xrc(e){return e==="darwin"?[{args:[],file:"pbcopy"}]:e==="linux"?[{args:[],file:"wl-copy"},{args:["-selection","clipboard"],file:"xclip"},{args:["--clipboard","--input"],file:"xsel"}]:e==="win32"?[{args:["-NoProfile","-NonInteractive","-Command",Src],file:"powershell.exe"}]:[]}function Trc(e,t){let n=Buffer.from(e,"utf8");if(n.byteLength>t)throw new Error(`Clipboard text exceeds ${t} bytes.`);return n}async function Irc(e,t,n){return await new Promise(o=>{let s;try{s=(0,iti.spawn)(e,t,{stdio:["pipe","ignore","ignore"],windowsHide:!0})}catch{o({exitCode:-1});return}let a=!1,l=r(u=>{a||(a=!0,o(u))},"finish");s.stdin?.on("error",()=>{}),s.stdin?.end(n.input),s.on("error",()=>l({exitCode:-1})),s.on("close",(u,f)=>l({exitCode:u,signal:f}))})}var iti,_rc,yrc,vrc,brc,Src,ati=Y(()=>{"use strict";iti=require("node:child_process"),_rc=1024*1024,yrc="c",vrc="\x1B]52;",brc="\x07",Src="Set-Clipboard -Value ([Console]::In.ReadToEnd())";r(sti,"createNodeClipboardTextWriter");r(wrc,"writeOsc52");r(krc,"writeNativeClipboardText");r(xrc,"nativeClipboardCommands");r(Trc,"assertClipboardTextSize");r(Irc,"runCommandText")});async function BTt(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return e.listCustomCommands?await e.listCustomCommands({env:t,logger:e.logger,workingDirectory:n}):await(await Qg()).listZCodeCustomCommands({env:t,logger:e.logger,workingDirectory:n})}async function cti(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)();return e.loadCustomCommand?await e.loadCustomCommand({env:n,logger:e.logger,name:t,workingDirectory:o}):await(await Qg()).loadZCodeCustomCommand({env:n,logger:e.logger,name:t,workingDirectory:o})}async function lti(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return await(e.listSkills??(await Qg()).listZCodeSkills)({env:t,logger:e.logger,workingDirectory:n})}async function uti(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return(await(e.listSessions??(await Qg()).listZCodeSessions)({directory:n,env:t,limit:50})).map(a=>({directory:a.directory,id:a.id,parentId:a.parentID,title:a.title,updatedAt:a.time.updated}))}async function dti(e){try{return await e.getSessionMetadata?.()??{}}catch(t){if(Crc(t))throw t;return{}}}function Crc(e){return e instanceof Error?e.name==="SqliteSessionMigrationError":!1}var j2n=Y(()=>{"use strict";b9();r(BTt,"listCustomCommandsForTui");r(cti,"loadCustomCommandForTui");r(lti,"listSkillsForTui");r(uti,"listSessionsForTui");r(dti,"loadInitialTuiSessionMetadata");r(Crc,"isStartupGateError")});function pti(e){let t=new Set,n,o=r(()=>{n?.(),n=void 0},"detach"),s=r(()=>{if(o(),t.size===0)return;n=e.readSubscriber(e.currentRuntime())?.({onSessionEvent:r(l=>{for(let u of t)u(l)},"onSessionEvent")})},"reattach");return{addSink:r(a=>(t.add(a),t.size===1&&s(),()=>{t.delete(a),t.size===0&&o()}),"addSink"),reattach:s,detach:o,isAttached:r(()=>n!==void 0,"isAttached")}}var fti=Y(()=>{"use strict";r(pti,"createTuiSessionEventRelay")});var mti,hti=Y(()=>{"use strict";TTt();mti=r((e,t)=>{const $zTuiBridge=e,$zTuiGetApp=t;$zTuiBridge.loadSessionTranscript=async()=>await(await $zTuiGetApp()).loadSessionTranscript?.()??[],$zTuiBridge.loadSessionContextMessages=async()=>await(await $zTuiGetApp()).loadSessionContextMessages?.()??[],$zTuiBridge.readGoal=async()=>await(await $zTuiGetApp()).readTarget?.()??null,$zTuiBridge.readTodos=async()=>await(await $zTuiGetApp()).readTodos?.()??[],$zTuiBridge.readRuntimeProjection=async()=>{let $zRuntimeProjectionBridge=await $zTuiGetApp();return await require(require("node:path").join(__dirname,"cli-config.cjs")).readTuiRuntimeProjection($zRuntimeProjectionBridge,$zTuiBridge)},$zTuiBridge.$zRestorePersistedBackgroundTasks=async $zApp=>await require(require("node:path").join(__dirname,"cli-config.cjs")).restoreTuiBackgroundTasks($zApp,(kKo(),H_r(),{collectChildSessionIds:bKo,projectSubagents:SKo,projectChildEvents:e=>new Ate().reduce(e)})),$zTuiBridge.readSessionUsage=async()=>await(await $zTuiGetApp()).readSessionUsage?.()??null,$zTuiBridge.cancelBackgroundTask=async e=>await(await $zTuiGetApp()).cancelBackgroundTask?.(e)??null,$zTuiBridge.previewFileRewind=async e=>{let t=await $zTuiGetApp();return await t.runtime?.previewWorkspaceFileRewind?.({targetMessageIds:e})??null},$zTuiBridge.applyFileRewind=async e=>{let t=await $zTuiGetApp();return await t.runtime?.applyWorkspaceFileRewind?.({targetMessageIds:e})??null},$zTuiBridge.setCustomSessionTitle=async e=>{let t=await $zTuiGetApp();let r=t.runtime?.setCustomSessionTitle?.bind(t.runtime)??t.setCustomSessionTitle?.bind(t);if(!r)throw new Error("Session renaming is unavailable in this runtime.");return await r({title:e.title,traceContext:e.traceContext??t.runtime?.rootTraceContext})},$zTuiBridge.readCustomSessionTitle=async()=>{let t=await $zTuiGetApp(),o=t.sessionStore??t.runtime?.sessionStore,r=await o?.getSession?.(t.sessionId);return r?.titleSource==="custom"&&typeof r.title==="string"?r.title:void 0},$zTuiBridge.setMode=async e=>{return await(await $zTuiGetApp()).setMode(e)},$zTuiBridge.readExecutionState=async()=>await(await $zTuiGetApp()).readExecutionState(),$zTuiBridge.setPlanEnabled=async e=>await(await $zTuiGetApp()).setPlanEnabled(e),$zTuiBridge.setTransientModel=async e=>{if(e==="main"){e=await $zTuiBridge.readDefaultModel();if(!e)throw new Error("No default model is configured.")}let t=await $zTuiGetApp(),r=await t.setModel(e);return{...r,thoughtLevel:t.getThoughtLevel(),effortOptions:t.listThoughtLevels()}},$zTuiBridge.readSessionModel=async()=>{let $zSessionModelApp=await $zTuiGetApp(),s=await $zSessionModelApp.readSessionModelState();if(s?.selection&&!s.issue)await $zSessionModelApp.setModel(s.selection,{transient:!0});return s},$zTuiBridge.sendBackgroundTaskMessage=async e=>await require(require("node:path").join(__dirname,"cli-config.cjs")).sendTuiBackgroundTaskMessage(await $zTuiGetApp(),$zTuiBridge,e),$zTuiBridge.interruptTurn=async e=>{let t=await $zTuiGetApp(),r=e?.reservationId??"tui-steer-interrupt",o=(Array.isArray(e?.pendingInputIds)?e.pendingInputIds:[]).filter(Boolean),n=[],i=async()=>{for(let a of n)await t.releaseQueueItemReservation?.(a,r);n=[]};try{if(t.reserveQueueItem&&t.releaseQueueItemReservation)for(let a of o)if(await t.reserveQueueItem(a,r))n.push(a);else{await i();break}let a=t.runtime?.stopActiveForegroundExecution?.({preserveQueueAutoDrainOnCancel:o.length>0&&n.length===o.length,reason:e?.reason??"TUI steer interrupt"})??{kind:"unsupported"};if(a.kind==="stopped"&&e?.waitForIdle===!0&&t.runtime?.getActiveForegroundExecutionId){let u=Date.now()+5e3;for(;t.runtime.getActiveForegroundExecutionId()!==void 0;){if(Date.now()>=u)throw new Error("Timed out waiting for background result processing to stop.");await new Promise(l=>setTimeout(l,25))}}return a.kind!=="stopped"&&await i(),a}catch(a){await i();throw a}},$zTuiBridge.promoteQueuedInput=async(e,t,r)=>{let o=await $zTuiGetApp(),n=r?.pendingInputReservationId??r?.queryId??r?.inputId??"tui-promotion",i=(Array.isArray(t)?t:[t]).filter(Boolean);if(i.length===0||!o.reserveQueueItem||!o.markQueueItemPromoting||!o.releaseQueueItemReservation||!o.removeQueueItem)return $zTuiBridge.sendInput(e,{...r,delivery:"start_turn"});let a=[],u=!1;try{for(let l of i){if(await o.markQueueItemPromoting(l,n)){a.push(l);continue}if(!await o.reserveQueueItem(l,n))throw new Error("TUI queued input is already reserved: "+l);a.push(l);if(!await o.markQueueItemPromoting(l,n))throw new Error("TUI queued input promotion failed: "+l)}let c=await $zTuiBridge.sendInput(e,{...r,delivery:"start_turn"});if(c?.kind==="rejected")return c;u=!0;for(let l of a)if(!await o.removeQueueItem(l,{reason:"promoted",reservationId:n}))throw new Error("TUI queued input promotion commit failed: "+l);return c}finally{if(!u)for(let l of a)await o.releaseQueueItemReservation(l,n)}},$zTuiBridge.$zSendInputWithoutBackgroundRestore=$zTuiBridge.sendInput,$zTuiBridge.sendInput=async(...$zArgs)=>{let $zApp=await $zTuiGetApp();await $zTuiBridge.$zRestorePersistedBackgroundTasks?.($zApp);return await $zTuiBridge.$zSendInputWithoutBackgroundRestore.apply($zTuiBridge,$zArgs)},e.recallPreviousInput=async n=>await(await t()).recallPreviousInputHistory?.(n)??null,e.getSessionMetadata=async()=>{let n=await t();return{locale:n.getLocale?.(),model:n.getModel?.(),theme:n.getTheme?.(),thoughtLevel:n.getThoughtLevel?.()}},e.reloadModelOptions=async()=>await(await t()).reloadModels(),e.readDefaultModel=async()=>{await t();let $zSelection=await(await e.$zReadProviderRegistryRuntime()).modelSelectionConfigRepository.read();return $zSelection?$zSelection.providerId+"/"+$zSelection.modelId:void 0},e.setDefaultModel=async $zModel=>{let $zApp=await t(),$zIndex=$zModel.indexOf("/"),$zSelection={providerId:$zModel.slice(0,$zIndex),modelId:$zModel.slice($zIndex+1)};if($zIndex<=0||!$zApp.getModelOption($zSelection))throw new Error("Unknown default model: "+$zModel);await(await e.$zReadProviderRegistryRuntime()).modelSelectionConfigRepository.saveConfiguredDefault($zSelection);return await e.setTransientModel($zModel)},e.listModelOptions=async()=>(await t()).listModels?.()??[],e.listEffortOptions=async()=>{let n=await t();return await j3e(n)??[]},e.listMcpServers=async()=>(await t()).listMcpServers?.()??{},e.listWorkflowRuns=async()=>await(await t()).listDynamicWorkflowRuns?.({})??[],e.replayWorkflowRuns=async n=>await(await t()).replayDynamicWorkflowRuns?.(n)??[]},"attachTuiAppQueries")});async function _ti(e,t,n,o){let s=e.env??process.env,a=(e.cwd??process.cwd)(),l=(e.loadDotenv??rA)({cwd:a,env:s});if(l.error)throw new Error(`Failed to load environment file: ${l.path}`,{cause:l.error});let u=await OTt(n,a,s,e),f=e.createZCodeApp?void 0:await Qg(),g=e.createZCodeApp??f?.createZCodeApp;if(!g)throw new Error("ZCode app factory is unavailable.");let _=e.prepareZCodeTelemetryEnv??f?.prepareZCodeTelemetryEnv;_&&(o.shutdownTelemetry=e.shutdownZCodeTelemetry??f?.shutdownZCodeTelemetry);let b=_?await _(s,{cliVersion:t,productVersion:s.ZCODE_APP_VERSION}):s,w=e.startProcessProviderRegistryRuntime??f?.startProcessProviderRegistryRuntime;if(!w)throw new Error("Provider Registry runtime is unavailable.");o.providerRegistryRuntimePromise??=w(b,e.skipUserConfig?{}:{standalone:{...gPe(),...e.userConfigPath?{legacyCliUserConfigFilePath:e.userConfigPath}:{}}});let T=await o.providerRegistryRuntimePromise,I=T?.modelSelectionConfigRepository?await T.modelSelectionConfigRepository.read():T?.configuredDefaultModelSelection,E=e.createProviderEndpointRoutingPort??f?.createDefaultProviderEndpointRoutingPort;return o.providerEndpointRoutingPort??=E?.({appVersion:t,env:s,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:a}),{appEnv:b,configuredDefaultModelSelection:I,createAppFactory:g,providerRegistryRuntime:T,sessionId:u,workingDirectory:a}}var gti,yti=Y(()=>{"use strict";b9();jQ();NXe();A2n();gti=r(()=>({providerEndpointRoutingPort:void 0,providerRegistryRuntimePromise:void 0,shutdownTelemetry:void 0}),"createTuiProcessRuntimeState");r(_ti,"prepareTuiAppRuntime")});async function vti(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)(),s=(e.loadDotenv??rA)({cwd:o,env:n});if(s.error)throw new Error(`Failed to load environment file: ${s.path}`,{cause:s.error});return await(e.loginZCodeCli??(await Qg()).loginZCodeCli)({abortSignal:t?.abortSignal,env:n,onAuthorizeUrl:t?.onAuthorizeUrl})}async function bti(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)(),s=(e.loadDotenv??rA)({cwd:o,env:n});if(s.error)throw new Error(`Failed to load environment file: ${s.path}`,{cause:s.error});return await(e.loginBigmodelCodingPlan??(await Qg()).loginBigmodelCodingPlan)({abortSignal:t?.abortSignal,env:n,onAuthorizeUrl:t?.onAuthorizeUrl})}async function Sti(e,t){return await(e.configureCodingPlanApiKey??(await Qg()).configureCodingPlanApiKey)({apiKey:t.apiKey,env:e.env??process.env,providerId:t.providerId})}async function wti(e){let t=e.env??process.env,n=(e.cwd??process.cwd)(),o=(e.loadDotenv??rA)({cwd:n,env:t});if(o.error)throw new Error(`Failed to load environment file: ${o.path}`,{cause:o.error});return await(e.logoutZCodeCli??(await Qg()).logoutZCodeCli)({env:t})}var kti=Y(()=>{"use strict";b9();jQ();r(vti,"loginForTui");r(bti,"loginBigmodelForTui");r(Sti,"configureApiKeyForTui");r(wti,"logoutForTui")});var xti,Tti,XK,B2n=Y(()=>{"use strict";xti={},Tti=r(e=>({current:e,override:e}),"createCliModeState"),XK=r(e=>e.current??e.override??"build","currentCliMode")});function U2n(e,t,n){return{kind:"started_turn",result:{...e,locale:e.locale??t.getLocale?.(),mode:n,model:e.model??t.getModel?.(),theme:e.theme??t.getTheme?.(),thoughtLevel:e.thoughtLevel??t.getThoughtLevel?.()}}}var Iti=Y(()=>{"use strict";r(U2n,"withTuiMetadata")});function Cti(e,t,n,o={continueSession:!1},s,a,l=Myt,u,f=!1,g,_){let b,w=s,T=gti(),I,E=new WeakMap,R=new WeakMap,L,U=Math.max(1,Math.trunc(e.shutdownCleanupTimeoutMs??nGe)),B={requestPermission:r(async(Pe,Tt)=>{let Ye=L;return Ye?await Ye(Pe,Tt):{decision:"deny",reason:`No interactive approval handler configured for ${Pe.toolName}`,resolvedAt:new Date}},"requestPermission")},z=r(async(Pe=b)=>{if(!Pe)return;let Tt=Pe,Ye=E.get(Tt);Ye||(Ye=(async()=>{await FL(async()=>Pe.close?.(),U),await FL(async()=>R.get(Tt)?.close(),U)})(),E.set(Tt,Ye)),await Ye},"closeApp"),$=pti({currentRuntime:r(()=>b?.runtime,"currentRuntime"),readSubscriber:RTt}),J=r(async Pe=>{let Tt=b,Ye=await Pe();return b=Ye,Tt&&Tt!==Ye&&await z(Tt),$.reattach(),t.current=b.getMode?.()??XK(t),b},"replaceApp"),q=r(async Pe=>{if(I)throw new Error("TUI prompt handler is closed");let{appEnv:Tt,configuredDefaultModelSelection:Ye,createAppFactory:Fe,providerRegistryRuntime:St,sessionId:kt,workingDirectory:st}=await _ti(e,n,Pe,T),$e=T.providerEndpointRoutingPort,jt=ATt({browserExecutable:_,browserUse:g},e),Je;try{Je=await Fe({browserControlPort:jt?.browserControlPort,env:Tt,projectConfigPath:e.projectConfigPath,...$e?{providerEndpointRoutingPort:$e}:{},providerRegistry:St.runtime.registryService,configuredDefaultModelSelection:Ye,...St.providerRuntimeHeadersPort?{providerRuntimeHeadersPort:St.providerRuntimeHeadersPort}:{},resume:kt!==void 0,runtimeConfig:{...t.override?{mode:t.override}:{},...u?{toolDisallowlist:u}:{},...f?{midConversationSystem:{mode:"force"}}:{},modelStreaming:"on",titleGeneration:xti,workingDirectory:st},permissionBroker:B,sessionId:kt,skipUserConfig:e.skipUserConfig,uiDetectedLocale:a,uiLocale:w,userConfigPath:e.userConfigPath,version:n})}catch(Xe){throw await FL(async()=>jt?.close(),U),Xe}if(jt&&R.set(Je,jt),I)throw await z(Je),new Error("TUI prompt handler is closed");return t.current=Je.getMode?.()??t.override??t.current??"build",Je},"createApp"),ie=r(async()=>(b??=await q(o),t.current=b.getMode?.()??XK(t),b),"getApp"),ae=r(async Pe=>await J(async()=>await q(Pe?{continueSession:!1,resumeSessionId:Pe}:{continueSession:!0})),"resumeApp"),Ce=r(async()=>await J(async()=>await q({continueSession:!1})),"newApp"),pe=r(async Pe=>{if(t.override=Pe,b){let Tt=b;if(Tt.setMode){let Ye=await Tt.setMode(Pe);return t.current=Ye.mode,Ye.mode}Tt.runtime.updateConfig({mode:Pe})}return t.current=Pe,Pe},"setCliMode"),ze=$3e({forkApp:r(async Pe=>{let Ye=await(await ie()).forkFromCheckpoint?.({targetCheckpointId:Pe});if(!Ye)throw new Error("Forking is not available in this client.");return await J(async()=>await q({continueSession:!1,resumeSessionId:Ye.forkedSessionId})),{copiedMessageCount:Ye.copiedMessageCount,forkedSessionId:Ye.forkedSessionId,response:`${Ye.response}
|
|
15418
15418
|
Switched to forked session ${Ye.forkedSessionId}.`,restoredFileCount:Ye.restoredFileCount??Ye.restoredFiles?.length??0}},"forkApp"),getApp:ie,getMode:r(()=>XK(t),"getMode"),getLocale:r(()=>b?.getLocale?.()??YRn(w,a)??l,"getLocale"),hasConfiguredCodingPlanAccess:k2n(e),listCustomCommands:r(()=>BTt(e),"listCustomCommands"),listSessions:r(()=>uti(e),"listSessions"),listSkills:r(()=>lti(e),"listSkills"),configureApiKey:r(Pe=>Sti(e,Pe),"configureApiKey"),login:r(Pe=>vti(e,Pe),"login"),loginBigmodel:r(Pe=>bti(e,Pe),"loginBigmodel"),loadCustomCommand:r(Pe=>cti(e,Pe),"loadCustomCommand"),newApp:Ce,recordInputHistory:r(async(Pe,Tt)=>{await b?.recordInputHistory?.(Pe,Tt)},"recordInputHistory"),resumeApp:ae,logout:r(()=>wti(e),"logout"),setLocale:r(async Pe=>{if(b?.setLocale){let Ye=await b.setLocale(Pe);return w=Pe,Ye}return w=Pe,{configPath:(await yOe(e.userConfigPath??U7(),Pe)).path,locale:YRn(Pe,a)??"en-US",requestedLocale:Pe}},"setLocale"),setMode:pe}),rt=r(async(Pe,Tt)=>{let Ye=L;L=Tt.requestPermission;try{return await ze(Pe,Tt)}finally{L=Ye}},"submitPrompt");return rt.setMode=async Pe=>({mode:await pe(Pe)}),rt.sendInput=async(Pe,Tt)=>{let Ye=L;L=Tt?.requestPermission;try{let Fe=await ie();if(Fe.sendInput){let St=await Fe.sendInput(Pe,Tt);return St.kind!=="started_turn"?St:U2n(await(St.result??St.completion),Fe,XK(t))}return U2n(await Fe.submitPrompt(Pe,Tt),Fe,XK(t))}finally{L=Ye}},rt.listSkills=async()=>await lti(e),rt.$zReadProviderRegistryRuntime=()=>T.providerRegistryRuntimePromise,mti(rt,ie),rt.subscribeSessionEvents=Pe=>{let Tt=$.addSink(Pe);return ie().then(()=>$.reattach(),()=>{}),Tt},rt.getMainSessionId=()=>{let Tt=b?.runtime?.getSessionId?.();return typeof Tt=="string"&&Tt.length>0?Tt:void 0},rt.close=async()=>{I??=(async()=>{await z(),await FL(async()=>T.shutdownTelemetry?.(),U),(await T.providerRegistryRuntimePromise)?.dispose()})(),await I},rt}var Eti=Y(()=>{"use strict";vw();eN();ETt();XRn();I2n();DTt();fti();hti();yti();Tde();kti();j2n();B2n();CTt();Iti();r(Cti,"createTuiSubmitPrompt")});var Ati,Pti,Y1,QK,cP,Rti,Dti,Erc,Arc,Oti,Mti,Prc,Rrc,Drc,Orc,Mrc,Nrc,Nti=Y(()=>{"use strict";Ati=require("node:crypto"),Pti=require("node:fs"),Y1=require("node:fs/promises"),QK=require("node:os"),cP=require("node:path"),Rti=require("node:url"),Dti="zcode-tui-runtime/",Erc=`${Dti}manifest.json`,Arc="node_modules/@zcode/tui/dist/index.js",Oti="manifest.json",Mti=r(async()=>{let e=await import("node:sea");if(!e.isSea())return await import("@zcode/tui");let t=await Prc(e);return await import((0,Rti.pathToFileURL)((0,cP.join)(t,Arc)).href)},"loadTuiRuntime"),Prc=r(async e=>{let t=Rrc(e),n=(0,cP.join)(Orc(),"0.16.9",t.target,t.hash),o=(0,cP.join)(n,Oti);if(await Drc(o,t))return n;let s=`${n}.tmp-${process.pid}-${Date.now()}`;await(0,Y1.rm)(s,{force:!0,recursive:!0}),await(0,Y1.mkdir)(s,{recursive:!0});for(let a of t.files){let l=e.getRawAsset(`${Dti}${a.path}`),u=Buffer.from(l);if((0,Ati.createHash)("sha256").update(u).digest("hex")!==a.sha256)throw new Error(`SEA TUI asset hash mismatch for ${a.path}`);let g=(0,cP.join)(s,a.path);await(0,Y1.mkdir)((0,cP.dirname)(g),{recursive:!0}),await(0,Y1.writeFile)(g,u),await(0,Y1.chmod)(g,a.mode??Nrc(a.path))}return await(0,Y1.writeFile)(Mrc(s),JSON.stringify(t,null,2)),await(0,Y1.rm)(n,{force:!0,recursive:!0}),await(0,Y1.mkdir)((0,cP.dirname)(n),{recursive:!0}),await(0,Y1.rename)(s,n),n},"ensureSeaTuiRuntime"),Rrc=r(e=>{let t=e.getAsset(Erc,"utf8"),n=JSON.parse(t);if(n.version!==1||!n.hash||!Array.isArray(n.files))throw new Error("Invalid SEA TUI runtime manifest.");return n},"readManifest"),Drc=r(async(e,t)=>{if(!(0,Pti.existsSync)(e))return!1;try{let n=JSON.parse(await(0,Y1.readFile)(e,"utf8"));return n.hash===t.hash&&n.target===t.target}catch{return!1}},"isCacheCurrent"),Orc=r(()=>{let e=(0,QK.homedir)();return(0,QK.platform)()==="darwin"&&e?(0,cP.join)(e,"Library","Caches","zcode","sea-assets"):(0,QK.platform)()==="win32"?(0,cP.join)(process.env.LOCALAPPDATA??(0,cP.join)(e||(0,QK.tmpdir)(),"AppData","Local"),"zcode","Cache","sea-assets"):(0,cP.join)(process.env.XDG_CACHE_HOME??(0,cP.join)(e||(0,QK.tmpdir)(),".cache"),"zcode","sea-assets")},"cacheBaseDirectory"),Mrc=r(e=>(0,cP.join)(e,Oti),"markerPathForDirectory"),Nrc=r(e=>/\.(?:dll|dylib|node|so)$/i.test(e)?493:420,"modeForPath")});function Lti({deps:e,options:t,workingDirectory:n}){let o=K0({cliOverrides:Lrc(t.locale),env:e.env??process.env,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:n});return e8(o.config.ui.locale,t.detectedLocale)}var Lrc,Fti=Y(()=>{"use strict";vw();eN();Lrc=r(e=>e?{ui:{locale:e}}:void 0,"localeCliOverrides");r(Lti,"resolveTuiStartupLocale")});function Bti(e){let t=e.fileSystemPort??hH(),n=(0,pN.resolve)(e.workspaceDirectory);return async o=>{let s=zrc(o.token);if(!s)return{items:[],truncated:!1};let a=(0,pN.resolve)(n,s.directoryToken);if(!Vrc(n,a))return{items:[],truncated:!1};try{let u=(await t.listDirectory({path:a},{signal:o.abortSignal})).entries.flatMap(g=>{if(g.kind!=="directory"&&g.kind!=="file")return[];if(g.kind==="directory"&&Urc.has(g.name))return[];if(!s.query.startsWith(".")&&g.name.startsWith("."))return[];if(!$rc(g.name,s.query))return[];let _=Wrc(n,g.path);return _?[{kind:g.kind,path:g.kind==="directory"?`${_}/`:_}]:[]}).sort((g,_)=>qrc(g,_,s.query)),f=Math.max(1,Math.floor(o.limit??Frc));return{items:u.slice(0,f),truncated:u.length>f}}catch{return{items:[],truncated:!1}}}}function zrc(e){let t=e.replace(/^@/u,"");if(t.startsWith("/")||t.startsWith("\\")||(0,pN.isAbsolute)(t)||Brc.test(t))return;let n=t.replace(jrc,"/");if(n.split("/").some(s=>s===".."))return;let o=n.lastIndexOf("/");return o<0?{directoryToken:"",query:n}:{directoryToken:n.slice(0,o+1),query:n.slice(o+1)}}function $rc(e,t){return t.length===0?!0:e.toLowerCase().includes(t.toLowerCase())}function qrc(e,t,n){if(e.kind!==t.kind)return e.kind==="directory"?-1:1;let o=jti(e.path),s=jti(t.path),a=n.toLowerCase(),l=o.toLowerCase().startsWith(a),u=s.toLowerCase().startsWith(a);return l!==u?l?-1:1:e.path.localeCompare(t.path)}function jti(e){let t=e.endsWith("/")?e.slice(0,-1):e,n=t.lastIndexOf("/");return n<0?t:t.slice(n+1)}function Wrc(e,t){let n=(0,pN.relative)(e,t);if(!(!n||n.startsWith("..")||(0,pN.isAbsolute)(n)))return n.split(pN.sep).join("/")}function Vrc(e,t){let n=(0,pN.relative)(e,t);return n===""||!n.startsWith("..")&&!(0,pN.isAbsolute)(n)}var pN,Frc,jrc,Brc,Urc,Uti=Y(()=>{"use strict";yme();pN=require("node:path"),Frc=50,jrc=/[\\/]+/gu,Brc=/^[a-zA-Z]:[\\/]/u,Urc=new Set([".bzr",".git",".hg",".jj",".sl",".svn","node_modules"]);r(Bti,"createWorkspacePathSuggestionProvider");r(zrc,"parseWorkspacePathToken");r($rc,"matchesPathQuery");r(qrc,"compareWorkspacePathSuggestion");r(jti,"basenameFromSuggestion");r(Wrc,"toWorkspaceRelativePath");r(Vrc,"isPathInside")});async function $ti(e){let t=e.maxOutputBytes??Krc,n=e.timeoutMs??Jrc,s=await(e.runCommand??Yrc)(Hrc,["-C",e.workspaceDirectory,...Grc],{maxOutputBytes:t,timeoutMs:n}).catch(()=>({exitCode:-1,stdout:""}));if(s.exitCode!==0)return;let a=s.stdout.trim().split(/\r?\n/,1)[0]?.trim();if(!(!a||a===Zrc))return a}async function Yrc(e,t,n){return await new Promise(o=>{let s;try{s=(0,zti.spawn)(e,t,{stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{o({exitCode:-1,stdout:""});return}let a="",l=!1,u=setTimeout(()=>{s.kill(),f({exitCode:-1,stdout:a})},n.timeoutMs),f=r(g=>{l||(l=!0,clearTimeout(u),o(g))},"finish");s.stdout?.on("data",g=>{a+=g.toString("utf8"),Buffer.byteLength(a,"utf8")>n.maxOutputBytes&&(s.kill(),f({exitCode:-1,stdout:a}))}),s.on("error",()=>f({exitCode:-1,stdout:a})),s.on("close",g=>f({exitCode:g,stdout:a}))})}var zti,Hrc,Grc,Jrc,Krc,Zrc,qti=Y(()=>{"use strict";zti=require("node:child_process"),Hrc="git",Grc=["symbolic-ref","--quiet","--short","HEAD"],Jrc=750,Krc=512,Zrc="HEAD";r($ti,"resolveWorkspaceGitBranch");r(Yrc,"runGitCommand")});var Wti,Vti=Y(()=>{"use strict";ms();oti();ati();ETt();Tde();j2n();CTt();Eti();Nti();Fti();Uti();qti();B2n();Wti=r(async(e,t,n,o,s,a,l,u=!1)=>{try{let f=Tti(s),g=n.runTui??(await Mti()).runTui,_=(n.cwd??process.cwd)(),b=n.env??process.env,w=OCe(b)==="development",T=await(n.resolveWorkspaceGitBranch??$ti)({workspaceDirectory:_}).catch(()=>{}),I=Lti({deps:n,options:t,workingDirectory:_}),E=Cti(n,f,o,a,t.locale,t.detectedLocale,I,l,u,t.browserUse,t.browserExecutable),R=rGe({cleanup:r(async()=>{await E.close?.()},"cleanup"),cleanupTimeoutMs:n.shutdownCleanupTimeoutMs,exitProcess:n.exitProcess,process:n.shutdownProcess});try{let L=await fei(n),U=L?{locale:I}:await dti(E),B=L||!U.model?[]:await E.listModelOptions?.().catch(()=>[]),z=L||!U.model?[]:await E.listEffortOptions?.().catch(()=>[]),$=await BTt(n).catch(()=>{});return await g({initialMode:XK(f),initialModel:U.model,initialThoughtLevel:U.thoughtLevel,loginRequired:L,locale:U.locale??I,theme:U.theme??"auto",developerMode:w,version:o,workspaceDirectory:_,workspaceGitBranch:T,noColor:t.noColor,readClipboardImage:n.readClipboardImage??tti(),effortOptions:z,modelOptions:B,listWorkspacePathSuggestions:Bti({workspaceDirectory:_}),listMcpServers:E.listMcpServers,listWorkflowRuns:E.listWorkflowRuns,replayWorkflowRuns:E.replayWorkflowRuns,reduceWorkflowRuns:($zState,$zEvent)=>{zhr();return oQe($zState,$zEvent)},getMainSessionId:E.getMainSessionId,writeClipboardText:n.writeClipboardText??sti({stdout:e.stdout}),stderr:e.stderr,stdin:e.stdin,stdout:e.stdout,loadSessionTranscript:E.loadSessionTranscript,loadSessionContextMessages:E.loadSessionContextMessages,readGoal:E.readGoal,readTodos:E.readTodos,readRuntimeProjection:E.readRuntimeProjection,readSessionUsage:E.readSessionUsage,cancelBackgroundTask:E.cancelBackgroundTask,previewFileRewind:E.previewFileRewind,applyFileRewind:E.applyFileRewind,setCustomSessionTitle:E.setCustomSessionTitle,readCustomSessionTitle:E.readCustomSessionTitle,interruptTurn:E.interruptTurn,promoteQueuedInput:E.promoteQueuedInput,listSkills:E.listSkills,readDefaultModel:E.readDefaultModel,setDefaultModel:E.setDefaultModel,reloadModelOptions:E.reloadModelOptions,listModelOptions:E.listModelOptions,readExecutionState:E.readExecutionState,setPlanEnabled:E.setPlanEnabled,setTransientModel:E.setTransientModel,readSessionModel:E.readSessionModel,sendBackgroundTaskMessage:E.sendBackgroundTaskMessage,recallPreviousInput:E.recallPreviousInput,sendInput:E.sendInput,setMode:E.setMode,slashCommands:v2n($),submitPrompt:E,subscribeSessionEvents:E.subscribeSessionEvents})}finally{R(),await E.close?.()}}catch(f){let g=f instanceof Error?f.message:String(f);return e.stderr.write(`Error: ${g}
|
|
15419
15419
|
`),t.verbose&&f instanceof Error&&f.stack&&e.stderr.write(`${f.stack}
|
|
15420
|
-
`),1}},"runTuiCommand")});var Jti={};Ng(Jti,{run:()=>Toc});var S9,Xrc,Qrc,eoc,toc,noc,roc,ooc,ioc,soc,aoc,coc,zTt,Hti,loc,uoc,Gti,doc,poc,foc,moc,hoc,goc,_oc,yoc,voc,boc,Soc,woc,UTt,koc,xoc,Toc,Kti=Y(()=>{"use strict";Dqt();adt();Y0();Y0();eN();jQ();L2o();WXo();XRn();b9();ZXo();oQo();cQo();n2n();F8t();X8t();mQo();jei();Xei();P2n();Vti();S9="0.16.9",Xrc="--target requires non-empty text.",Qrc="yolo",eoc="--force-mcs can only be used with --prompt, --target, or tui.",toc="--target-replace requires --target.",noc='--target cannot be used with --prompt. Use either --target <objective> or --prompt "/goal <objective>".',roc=new Set(["--disallowedTools","--disallowed-tools"]),ooc="--browser-executable requires --browser-use=headless.",ioc="--browser-use=headless can only be used with --prompt, --target, or tui.",soc="--surface can only be used with --prompt, --target, app-server, or agent-server.",aoc="--memory-bench can only be used with -p/--prompt.",coc=r(e=>({...e.all===!0?{all:!0}:{},...e.available===!0?{available:!0}:{},...e["keep-data"]===!0?{keepData:!0}:{},...typeof e.scope=="string"?{scope:e.scope}:{},...Array.isArray(e.sparse)?{sparse:e.sparse}:{}}),"pluginsCommandFlags"),zTt=r(e=>e[0]??"tui","commandName"),Hti=r(e=>typeof e.prompt=="string"||e.targetRequest!==void 0||zTt(e.positionals)==="tui","isForceMcsSupportedInvocation"),loc=r(e=>{let t=zTt(e.positionals);return typeof e.prompt=="string"||e.targetRequest!==void 0||t==="app-server"||t==="agent-server"},"isPresentationSurfaceSupportedInvocation"),uoc=r((e,t,n,o,s,a)=>({browserExecutable:s,browserUse:o,detectedLocale:n,force:e.force===!0,json:e.json===!0,locale:t,...e["memory-bench"]===!0?{memoryBench:!0}:{},noColor:e["no-color"]===!0,...a?{outputFormat:a}:{},verbose:e.verbose===!0}),"globalOptions"),Gti=["text","json","stream-json"],doc=r(e=>{if(e!==void 0){if(Gti.includes(e))return e;throw new Error(`--output-format must be one of ${Gti.join(", ")} (received: ${e}).`)}},"normalizeOutputFormat"),poc=r(e=>{if(e!==void 0){if(L6e(e))return e;throw new Error(S4().cli.errors.localeUnsupported(e))}},"normalizeLocaleOption"),foc=r(e=>{if(e===void 0)return;let t=e.toLowerCase();if(t==="build"||t==="edit"||t==="yolo")return t;throw new Error(`Unsupported --mode value: ${e}. Supported modes: build, edit, yolo. Use /plan in the TUI to toggle planning.`)},"normalizePromptMode"),moc=r(e=>{if(e!==void 0){if(e.toLowerCase()==="headless")return"headless";throw new Error(`Unsupported --browser-use value: ${e}. Supported value: headless.`)}},"normalizeBrowserUse"),hoc=r(e=>{if(e===void 0||e.toLowerCase()==="terminal")return"terminal";if(e.toLowerCase()==="desktop")return"zcode_desktop";throw new Error(`Unsupported --surface value: ${e}. Supported surfaces: terminal, desktop.`)},"normalizePresentationSurface"),goc=r(e=>{let t=[],n=[];for(let o=0;o<e.length;o+=1){let s=e[o],a=s.match(/^(--disallowedTools|--disallowed-tools)=(.*)$/);if(a){n.push(a[2]??"");continue}if(!roc.has(s)){t.push(s);continue}let l=!1;for(;o+1<e.length&&!_oc(e[o+1]);)n.push(e[o+1]),o+=1,l=!0;if(!l)throw new Error(`${s} requires at least one tool.`)}return{args:t,toolDisallowlist:yoc(n)}},"extractDisallowedToolsArgs"),_oc=r(e=>e==="--"||/^-[^-]?|^--/.test(e),"isCliOptionToken"),yoc=r(e=>{let t=[],n=new Set;for(let o of e)for(let s of voc(o)){let a=boc(s);!a||n.has(a)||(n.add(a),t.push(a))}return t.length>0?t:void 0},"normalizeCliToolRuleList"),voc=r(e=>{let t=[],n="",o=!1,s=r(()=>{let a=n.trim();a&&t.push(a),n=""},"flush");for(let a of e)switch(a){case"(":o=!0,n+=a;break;case")":o=!1,n+=a;break;case",":o?n+=a:s();break;case" ":o?n+=a:s();break;default:n+=a;break}return s(),t},"splitCliToolRules"),boc=r(e=>e?e==="web_search"?"WebSearch":e.startsWith("web_search(")?`WebSearch${e.slice(10)}`:e:"","normalizeCliToolRule"),Soc=r(e=>{let t=e.target,n=e["target-replace"]===!0;if(t===void 0){if(n)throw new Error(toc);return}let o=t.trim();if(o.length===0)throw new Error(Xrc);return{objective:o,replaceExisting:n}},"normalizeTargetRequest"),woc=r(e=>e.replaceExisting?`/goal replace ${e.objective}`:`/goal ${e.objective}`,"buildHeadlessTargetCommand"),UTt=r((e,t,n)=>{e.write(N2o(S9,t,n))},"writeHelp"),koc=r((e,t,n)=>{let o=wTn(),s={cli:{name:aZn,processName:L8t,version:S9},runtime:{arch:o.arch,cwd:n,execPath:o.execPath,node:o.node,platform:o.platform,processTitle:process.title,sea:o.sea},packaging:{default:"node-bundle",sea:"optional"}};if(t.json)return e.stdout.write(e0(s)),0;let a=bTn(e.stdout,t.noColor);return e.stdout.write(`${STn.bold("zcode doctor",a)}
|
|
15420
|
+
`),1}},"runTuiCommand")});var Jti={};Ng(Jti,{run:()=>Toc});var S9,Xrc,Qrc,eoc,toc,noc,roc,ooc,ioc,soc,aoc,coc,zTt,Hti,loc,uoc,Gti,doc,poc,foc,moc,hoc,goc,_oc,yoc,voc,boc,Soc,woc,UTt,koc,xoc,Toc,Kti=Y(()=>{"use strict";Dqt();adt();Y0();Y0();eN();jQ();L2o();WXo();XRn();b9();ZXo();oQo();cQo();n2n();F8t();X8t();mQo();jei();Xei();P2n();Vti();S9="0.16.9",Xrc="--target requires non-empty text.",Qrc="yolo",eoc="--force-mcs can only be used with --prompt, --target, or tui.",toc="--target-replace requires --target.",noc='--target cannot be used with --prompt. Use either --target <objective> or --prompt "/goal <objective>".',roc=new Set(["--disallowedTools","--disallowed-tools"]),ooc="--browser-executable requires --browser-use=headless.",ioc="--browser-use=headless can only be used with --prompt, --target, or tui.",soc="--surface can only be used with --prompt, --target, app-server, or agent-server.",aoc="--memory-bench can only be used with -p/--prompt.",coc=r(e=>({...e.all===!0?{all:!0}:{},...e.available===!0?{available:!0}:{},...e["keep-data"]===!0?{keepData:!0}:{},...typeof e.scope=="string"?{scope:e.scope}:{},...Array.isArray(e.sparse)?{sparse:e.sparse}:{}}),"pluginsCommandFlags"),zTt=r(e=>e[0]??"tui","commandName"),Hti=r(e=>typeof e.prompt=="string"||e.targetRequest!==void 0||zTt(e.positionals)==="tui","isForceMcsSupportedInvocation"),loc=r(e=>{let t=zTt(e.positionals);return typeof e.prompt=="string"||e.targetRequest!==void 0||t==="app-server"||t==="agent-server"},"isPresentationSurfaceSupportedInvocation"),uoc=r((e,t,n,o,s,a)=>({browserExecutable:s,browserUse:o,detectedLocale:n,force:e.force===!0,json:e.json===!0,locale:t,...e["memory-bench"]===!0?{memoryBench:!0}:{},noColor:e["no-color"]===!0,...a?{outputFormat:a}:{},verbose:e.verbose===!0}),"globalOptions"),Gti=["text","json","stream-json"],doc=r(e=>{if(e!==void 0){if(Gti.includes(e))return e;throw new Error(`--output-format must be one of ${Gti.join(", ")} (received: ${e}).`)}},"normalizeOutputFormat"),poc=r(e=>{if(e!==void 0){if(L6e(e))return e;throw new Error(S4().cli.errors.localeUnsupported(e))}},"normalizeLocaleOption"),foc=r(e=>{if(e===void 0)return;let t=e.toLowerCase();if(t==="build"||t==="edit"||t==="yolo")return t;throw new Error(`Unsupported --mode value: ${e}. Supported modes: build, edit, yolo. Use /plan in the TUI to toggle planning.`)},"normalizePromptMode"),moc=r(e=>{if(e!==void 0){if(e.toLowerCase()==="headless")return"headless";throw new Error(`Unsupported --browser-use value: ${e}. Supported value: headless.`)}},"normalizeBrowserUse"),hoc=r(e=>{if(e===void 0||e.toLowerCase()==="terminal")return"terminal";if(e.toLowerCase()==="desktop")return"zcode_desktop";throw new Error(`Unsupported --surface value: ${e}. Supported surfaces: terminal, desktop.`)},"normalizePresentationSurface"),goc=r(e=>{let t=[],n=[];for(let o=0;o<e.length;o+=1){let s=e[o],a=s.match(/^(--disallowedTools|--disallowed-tools)=(.*)$/);if(a){n.push(a[2]??"");continue}if(!roc.has(s)){t.push(s);continue}let l=!1;for(;o+1<e.length&&!_oc(e[o+1]);)n.push(e[o+1]),o+=1,l=!0;if(!l)throw new Error(`${s} requires at least one tool.`)}return{args:t,toolDisallowlist:yoc(n)}},"extractDisallowedToolsArgs"),_oc=r(e=>e==="--"||/^-[^-]?|^--/.test(e),"isCliOptionToken"),yoc=r(e=>{let t=[],n=new Set;for(let o of e)for(let s of voc(o)){let a=boc(s);!a||n.has(a)||(n.add(a),t.push(a))}return t.length>0?t:void 0},"normalizeCliToolRuleList"),voc=r(e=>{let t=[],n="",o=!1,s=r(()=>{let a=n.trim();a&&t.push(a),n=""},"flush");for(let a of e)switch(a){case"(":o=!0,n+=a;break;case")":o=!1,n+=a;break;case",":o?n+=a:s();break;case" ":o?n+=a:s();break;default:n+=a;break}return s(),t},"splitCliToolRules"),boc=r(e=>e?e==="web_search"?"WebSearch":e.startsWith("web_search(")?`WebSearch${e.slice(10)}`:e:"","normalizeCliToolRule"),Soc=r(e=>{let t=e.target,n=e["target-replace"]===!0;if(t===void 0){if(n)throw new Error(toc);return}let o=t.trim();if(o.length===0)throw new Error(Xrc);return{objective:o,replaceExisting:n}},"normalizeTargetRequest"),woc=r(e=>e.replaceExisting?`/goal replace ${e.objective}`:`/goal ${e.objective}`,"buildHeadlessTargetCommand"),UTt=r((e,t,n)=>{e.write(N2o(S9,t,n))},"writeHelp"),koc=r((e,t,n)=>{let o=wTn(),s={cli:{name:aZn,processName:L8t,version:S9},runtime:{arch:o.arch,cwd:n,execPath:o.execPath,node:o.node,platform:o.platform,processTitle:process.title,sea:o.sea},packaging:{default:"node-bundle",sea:"optional"},configuration:require(require("node:path").join(__dirname,"cli-config.cjs")).inspectRuntimeConfiguration(n,$zOptions=>{_Hr();return K0($zOptions)})};if(t.json)return e.stdout.write(e0(s)),s.configuration.ok?0:1;let a=bTn(e.stdout,t.noColor);return e.stdout.write(`${STn.bold("zcode doctor",a)}
|
|
15421
15421
|
`),e.stdout.write(`version: ${s.cli.version}
|
|
15422
15422
|
`),e.stdout.write(`process: ${s.runtime.processTitle}
|
|
15423
15423
|
`),e.stdout.write(`node: ${s.runtime.node}
|
|
@@ -15426,7 +15426,7 @@ Switched to forked session ${Ye.forkedSessionId}.`,restoredFileCount:Ye.restored
|
|
|
15426
15426
|
`),e.stdout.write(`default artifact: ${s.packaging.default}
|
|
15427
15427
|
`),t.verbose&&(e.stdout.write(`execPath: ${s.runtime.execPath}
|
|
15428
15428
|
`),e.stdout.write(`cwd: ${s.runtime.cwd}
|
|
15429
|
-
`)),
|
|
15429
|
+
`)),require(require("node:path").join(__dirname,"cli-config.cjs")).writeConfigurationDoctor(e.stdout,s.configuration)},"runDoctor"),xoc=r(async(e,t,n,o,s=!1)=>{try{let a=W8t(n.env??process.env),l=(n.cwd??process.cwd)(),u=TZn(a)?(n.loadDotenv??rA)({cwd:l,env:a}):{keys:[],loaded:!1};if(NCe(a),u.error)throw new Error(`Failed to load environment file: ${u.path}`,{cause:u.error});return await(n.runZCodeProtocolAgent??(await Qg()).runZCodeProtocolAgent)({lifecycle:n.protocolLifecycle,cwd:l,env:a,input:n.protocolInput??e.stdin,output:e.stdout,presentationSurface:o,prepareStorageOnly:s,version:S9}),0}catch(a){let l=a instanceof Error?a.message:String(a);return e.stderr.write(`Error: ${l}
|
|
15430
15430
|
`),t.verbose&&a instanceof Error&&a.stack&&e.stderr.write(`${a.stack}
|
|
15431
15431
|
`),1}},"runZCodeProtocolCommand"),Toc=r(async(e,t={})=>{if(e.argv[0]==="__internal-search")return KXo(e.argv.slice(1),{cwd:(t.cwd??process.cwd)(),stderr:e.stderr,stdin:e.stdin,stdout:e.stdout});if(BCe(e.argv))return await tGe(e,e.argv.slice(1));if(pQo(e.argv))return await fQo(e,e.argv.slice(1));if(e.argv[0]==="hooks")return await qXo(e,t,S9);let n,o;try{let U=goc(e.argv);n=Rqt(U.args),o=U.toolDisallowlist}catch(U){let B=U instanceof Error?U.message:String(U);return e.stderr.write(`${B}
|
|
15432
15432
|
|