zcode-app-cli 3.14.4-32 → 3.14.5-34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -2
- package/bin/zcode.js +62 -6
- package/docs/CONFIGURATION.md +46 -3
- package/docs/CONFIGURATION.zh-CN.md +33 -2
- package/package.json +1 -1
- package/vendor/cli-config.cjs +82 -2
- package/vendor/extraction.json +29 -4
- package/vendor/node_modules/@zcode/tui/dist/index.js +64 -8
- package/vendor/packages/node-repl-host/dist/mcp/server.js +1 -1
- package/vendor/zcode.cjs +6 -6
- package/zcode-runtime.lock.json +3 -3
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={}){e={...e,filePath:e.filePath??(e.env??process.env).ZCODE_CLI_CREDENTIALS_FILE?.trim()};if(e.filePath)return eYr(e.filePath);let t=e.env??process.env,n=e.baseDir??t[t$s]??(0,Cct.homedir)();return(0,XOe.join)(eYr(n),".zcode","v2","credentials.json")}async function npn(e){let t;try{t=await(0,tYr.readFile)(e,"utf-8")}catch(n){if(o$s(n)==="ENOENT")return{};throw new Error(`Unable to read shared ZCode credentials: ${e}`,{cause:n})}try{return r$s(JSON.parse(t))}catch(n){let o=await Gqt(e).catch(()=>{}),s=o?` Backup: ${o}`:"";throw new Error(`Shared ZCode credentials are corrupt: ${e}.${s}`,{cause:n})}}async function e$(e,t){await lw(e,async()=>{let o=await npn(e);await t(o),await qL(e,`${JSON.stringify(o,null,2)}
|
|
2136
|
+
`):e}function _7s(e,t,n){let o=_Gr(e);if(o!==void 0){for(let a of o)Eat(n);return o}let s=(0,Bk.join)(e,"cache",Yp);try{let a=[];for(let l of(0,WF.readdirSync)(s,{withFileTypes:!0})){if(Eat(n),!l.isDirectory())continue;let u=(0,Bk.join)(s,l.name);for(let f of(0,WF.readdirSync)(u,{withFileTypes:!0}))f.isDirectory()&&a.push((0,Bk.join)(u,f.name))}return a}catch(a){return Cat(a)?[]:(t.push({code:"plugin_root_not_found",message:a instanceof Error?a.message:`Failed to scan ${s}`,path:s,severity:"warning"}),[])}}function y7s(e,t){if(!$v(e.rootPath))return t.push({code:"plugin_root_not_found",message:`Plugin root does not exist: ${e.rootPath}`,path:e.rootPath,severity:"warning"}),null;let n=v7s(e.rootPath);if(!n)return t.push({code:"plugin_manifest_not_found",message:`Plugin manifest not found: ${e.rootPath}`,path:e.rootPath,severity:"error"}),null;let o=b7s(n,t);return o?{id:`${o.name}@${e.marketplace}`,manifest:o,manifestPath:n,marketplace:e.marketplace,rootPath:e.rootPath,source:e.source}:null}function v7s(e){let t=(0,Bk.join)(e,qzs);if(bw(t))return t;let n=(0,Bk.join)(e,Wzs);if(bw(n))return n;let o=(0,Bk.join)(e,Vzs);return bw(o)?o:null}function b7s(e,t){try{let n=JSON.parse((0,WF.readFileSync)(e,"utf8"));if(!fu(n))throw new Error("Manifest must be a JSON object");let o=typeof n.name=="string"?n.name.trim():"";if(!Kzs.test(o))throw new Error(`Invalid plugin name: ${o}`);return{...n,name:o,version:typeof n.version=="string"?n.version:Hzs}}catch(n){return t.push({code:"plugin_manifest_invalid",message:n instanceof Error?n.message:`Invalid plugin manifest: ${e}`,path:e,severity:"error"}),null}}function S7s(){return{commandRoots:[],diagnostics:[],hooks:{},mcpServers:{},plugins:[],skillRoots:[]}}function w7s(e=[]){return{commandRoots:[],hooks:{},hookDetails:e,mcpServers:{},skillCount:0,skillRoots:[]}}function k7s(e,t,n){return e.enabledPlugins[t]??n}var WF,Bk,qzs,Wzs,Vzs,Hzs,Gzs,Jzs,Kzs,Zzs,Yzs,Kdn,GOe=Y(()=>{"use strict";WF=require("node:fs"),Bk=require("node:path");nr();q7();kat();Rat();Dun();Mun();Edn();Mat();Edn();Mat();sdn();EZr();qzs=(0,Bk.join)(".zcode-plugin","plugin.json"),Wzs=(0,Bk.join)(".claude-plugin","plugin.json"),Vzs=(0,Bk.join)(".codex-plugin","plugin.json"),Hzs="0.0.0",Gzs=1e3,Jzs=10,Kzs=/^[a-z0-9][a-z0-9._-]{0,127}$/,Zzs=["channels","lspServers","outputStyles","settings"],Yzs=new Set(Object.values(Tl)),Kdn=class{static{r(this,"NodePluginAdapter")}options;constructor(t){this.options=t}async discoverPlugins(t,n){return this.discoverPluginsSync(t,n)}discoverPluginsSync(t,n){if(!t.config.enabled)return S7s();let o=[],s=(0,Bk.join)(t.storageRoot||this.options.storageRoot,"data"),a=this.resolveCandidates(t,o,n),l=[],u={},f={},g=[],_=new Set,b=[],w=Gzs;for(let T of a){Eat(n);let I=y7s(T,o);if(!I||I.source==="official"&&t.config.suppressedBuiltins.includes(I.id))continue;if(_.has(I.id)){o.push({code:"plugin_duplicate_id",message:`Duplicate plugin ignored: ${I.id}`,path:I.rootPath,pluginId:I.id,severity:"warning"});continue}_.add(I.id),n7s(I,o);let E=T.defaultEnabled||(t.officialPluginsEnabledByDefault?.has(I.id)??!1),R=k7s(t.config,I.id,E),L=(0,Bk.join)(s,$7(I.id)),U=gre({diagnostics:o,loaded:I}),B=t7s(I),z=s7s({dataPath:L,diagnostics:o,loaded:I,runnable:B}),$=R?e7s({dataPath:L,diagnostics:o,env:t.env??{},hookEvents:B?z.events:{},hookDetails:z.details,loaded:I,mcpServerDefinitions:U,options:t.config.options[I.id]??{},priority:w,workingDirectory:t.workingDirectory}):w7s(z.details);w+=Jzs,Object.assign(f,$.mcpServers),AZr(u,$.hooks),b.push(...$.skillRoots),l.push(...$.commandRoots),g.push(Qzs(I,$,L,R,Object.keys(U),t.config.options[I.id]??{}))}return{commandRoots:l,diagnostics:o,hooks:u,mcpServers:f,plugins:g,skillRoots:b}}resolveCandidates(t,n,o){let s=[];for(let a of t.config.dirs)s.push({defaultEnabled:!0,marketplace:OZn,rootPath:(0,Bk.resolve)(a),source:"inline"});for(let a of t.officialPluginRoots??[])s.push({defaultEnabled:!1,marketplace:Yp,rootPath:(0,Bk.resolve)(a),source:"official"});s.push(..._7s(t.storageRoot,n,o).map(a=>({defaultEnabled:!1,marketplace:Yp,rootPath:a,source:"official"})));for(let a of X7(t.storageRoot))s.push({defaultEnabled:!1,marketplace:a.marketplace,rootPath:ydn(t.storageRoot,a),source:"cache"});return s}};r(Xzs,"createNodePluginAdapter");r(wct,"discoverNodePluginsSync");r(Qzs,"createPluginMetadata");r(e7s,"resolveEnabledComponents");r(t7s,"canRunPluginHooks");r(n7s,"warnUnsupportedComponents");r(r7s,"resolveSkillRoots");r(o7s,"warnEmptyDeclaredSkillRoots");r(i7s,"resolveCommandRoots");r(s7s,"inspectPluginHooks");r(a7s,"parsePluginHookEvents");r(c7s,"toPluginHookDetail");r(Zdn,"createHookPluginContext");r(l7s,"attachPluginToHook");r(AZr,"mergeHookEvents");r(u7s,"mergeHookInspection");r(PZr,"emptyHookInspection");r(d7s,"countSkillFiles");r(RZr,"resolveComponentRoots");r(p7s,"materializeCommandMetadataRoot");r(f7s,"normalizeGeneratedCommandName");r(m7s,"trimRelativePrefix");r(h7s,"applyCommandMetadataFrontmatter");r(g7s,"stripMarkdownFrontmatter");r(_7s,"scanOfficialCache");r(y7s,"loadPlugin");r(v7s,"findManifest");r(b7s,"readManifest");r(S7s,"emptyOutcome");r(w7s,"emptyComponents");r(k7s,"resolveEnabled")});function OZr(e){let t=e.appId??I7s,n=e.appSecret?.trim()??"",o=e.authorizeUrl??Hpe(process.env,x7s),s=e.tokenUrl??Hpe(process.env,T7s);return{buildAuthorizeUrl(a){let l=new URLSearchParams({appId:t,redirect:a.redirectUri,state:a.state});return`${o}?${l.toString()}`},async exchangeCode(a,l){if(!n)throw new kct("BigModel OAuth appSecret is required.");let u=await e.httpClient.request({body:new TextEncoder().encode(JSON.stringify({appId:t,appSecret:n,authCode:a.code})),headers:{"Content-Type":E7s},maxResponseBytes:64*1024,method:"POST",trace:e.trace,url:s},l),f=JSON.parse(new TextDecoder().decode(u.body)),g=f.data?.accessToken?.trim()??"";if(!g)throw new kct(f.msg??"BigModel token response is missing accessToken.");return{accessToken:g,...f.data?.refreshToken?{refreshToken:f.data.refreshToken}:{}}}}}function MZr(){return(0,DZr.randomBytes)(C7s).toString("hex")}var DZr,x7s,T7s,I7s,C7s,E7s,kct,NZr=Y(()=>{"use strict";DZr=require("node:crypto");ms();x7s="/login",T7s="/api/auth/tokenByAuthCode",I7s="zcode",C7s=32,E7s="application/json",kct=class extends Error{static{r(this,"BigmodelOAuthError")}constructor(t,n={}){super(t,n),this.name="BigmodelOAuthError"}};r(OZr,"createBigmodelOAuthClient");r(MZr,"createBigmodelOAuthState")});async function Ydn(e,t={}){let n=t.platform??process.platform,o=P7s(n,e),s=t.spawnProcess??LZr.spawn;try{let a=s(o.executable,o.args,{detached:n!=="win32",stdio:"ignore",windowsHide:!0});return await R7s(a,o.executable,t.timeoutMs)}catch(a){return{command:o.executable,opened:!1,reason:a instanceof Error?a.message:String(a)}}}function P7s(e,t){return require(require("node:path").join(__dirname,"cli-config.cjs")).browserOpenCommand(e,t)}function R7s(e,t,n=A7s){return new Promise(o=>{let s=!1,a,l=r(u=>{s||(s=!0,clearTimeout(a),e.removeAllListeners("error"),e.removeAllListeners("spawn"),u.opened&&e.unref(),o(u))},"settle");a=setTimeout(()=>{l({command:t,opened:!0})},n),e.once("spawn",()=>{l({command:t,opened:!0})}),e.once("error",u=>{l({command:t,opened:!1,reason:u.message})})})}var LZr,A7s,FZr=Y(()=>{"use strict";LZr=require("node:child_process"),A7s=1e3;r(Ydn,"openUrlInBrowser");r(P7s,"browserOpenCommand");r(R7s,"waitForBrowserSpawn")});function $Zr(e){return{async resolve(t,n){let o=t.accessToken.trim();if(!o)throw new yG("OAuth access token is required.");if(t.family==="bigmodel")return BZr({authorization:o,host:XAe(process.env),httpClient:e.httpClient,trace:e.trace},n);let s=await M7s(e,o,n);return BZr({authorization:`Bearer ${s}`,host:UZr,httpClient:e.httpClient,requireSecretKey:!0,trace:e.trace},n)}}}async function M7s(e,t,n){let o=await JOe(e.httpClient,{body:new TextEncoder().encode(JSON.stringify({token:t})),headers:{"Content-Type":zZr},method:"POST",trace:e.trace,url:`${UZr}/api/auth/z/login`},n),s=o?.access_token?.trim()??o?.accessToken?.trim()??"";if(!s)throw new yG("Z.AI biz token response is missing access_token.");return s}async function BZr(e,t){let n=await JOe(e.httpClient,{headers:xct(e.authorization),method:"GET",trace:e.trace,url:`${e.host}/api/biz/customer/getCustomerInfo`},t),o=N7s(n);if(!o)throw new yG("Unable to resolve organization and project.");let s=`${e.host}/api/biz/v1/organization/${o.organizationId}/projects/${o.projectId}/api_keys`,u=((await JOe(e.httpClient,{headers:xct(e.authorization),method:"GET",trace:e.trace,url:s},t)??[]).find(_=>_.name===jZr)??await JOe(e.httpClient,{body:new TextEncoder().encode(JSON.stringify({name:jZr})),headers:xct(e.authorization),method:"POST",trace:e.trace,url:s},t))?.apiKey?.trim()??"";if(!u)throw new yG("API key response is missing apiKey.");let g=(await JOe(e.httpClient,{headers:xct(e.authorization),method:"GET",trace:e.trace,url:`${s}/copy/${encodeURIComponent(u)}`},t))?.secretKey?.trim()??"";if(!g){if(e.requireSecretKey)throw new yG("API key copy response is missing secretKey.");return u}return`${u}.${g}`}async function JOe(e,t,n){let o=await e.request({maxResponseBytes:65536,...t},n),s=JSON.parse(new TextDecoder().decode(o.body));if(!L7s(s.code))throw new yG(s.msg??`Remote business error ${s.code}`);return s.data??null}function xct(e){return{Authorization:e,"Content-Type":zZr}}function N7s(e){let t=e?.organizations??[],n=t.find(a=>a.organizationName?.includes(D7s))??t[0],o=n?.projects??[],s=o.find(a=>a.projectName?.includes(O7s))??o[0];return!n?.organizationId||!s?.projectId?null:{organizationId:n.organizationId,projectId:s.projectId}}function L7s(e){return e==null||e===0||e===200||e==="0"||e==="200"}var UZr,zZr,jZr,D7s,O7s,yG,qZr=Y(()=>{"use strict";ms();UZr="https://api.z.ai",zZr="application/json",jZr="zcode-api-key",D7s="\u9ED8\u8BA4\u673A\u6784",O7s="\u9ED8\u8BA4\u9879\u76EE",yG=class extends Error{static{r(this,"CodingPlanApiKeyError")}constructor(t,n={}){super(t,n),this.name="CodingPlanApiKeyError"}};r($Zr,"createCodingPlanApiKeyResolver");r(M7s,"resolveZaiBizToken");r(BZr,"resolveBizApiKey");r(JOe,"requestRemoteData");r(xct,"createBizAuthHeaders");r(N7s,"pickOrgAndProject");r(L7s,"isSuccessfulRemoteCode")});function Xdn(e){let t=z7s(e.baseUrl??F7s),n=new TextEncoder;return{async init(o,s){let a=await WZr(e.httpClient,{body:n.encode(JSON.stringify({provider:j7s})),headers:{Authorization:`Bearer ${o.pollToken}`,"Content-Type":U7s},method:"POST",trace:e.trace,url:`${t}/oauth/cli/init`},s);return $7s(a.data)},async poll(o,s){let a=encodeURIComponent(o.flowId),l=await WZr(e.httpClient,{headers:{Authorization:`Bearer ${o.pollToken}`},method:"GET",trace:e.trace,url:`${t}/oauth/cli/poll/${a}`},s);return q7s(l.data)}}}function HZr(){return(0,VZr.randomBytes)(B7s).toString("hex")}function z7s(e){return e.replace(/\/+$/u,"")}async function WZr(e,t,n){let o=await e.request({maxResponseBytes:65536,...t},n),s=new TextDecoder().decode(o.body),a=V7s(s,o.status),l=KOe(a);if(!l||typeof l.code!="number")throw new Q7("Invalid OAuth response envelope",{httpStatus:o.status});let u=typeof l.msg=="string"?l.msg:void 0;if(o.status<200||o.status>=300)throw new Q7(u??`OAuth HTTP error ${o.status}`,{businessCode:l.code,httpStatus:o.status});if(l.code!==0)throw new Q7(u??`OAuth business error ${l.code}`,{businessCode:l.code,httpStatus:o.status});return{code:l.code,data:l.data,msg:u}}function $7s(e){let t=KOe(e);if(!t||typeof t.flow_id!="string"||typeof t.poll_token!="string"||typeof t.authorize_url!="string"||typeof t.expires_at!="number"||typeof t.poll_interval_sec!="number")throw new Q7("Invalid OAuth init response data");return{authorize_url:t.authorize_url,expires_at:t.expires_at,flow_id:t.flow_id,poll_interval_sec:t.poll_interval_sec,poll_token:t.poll_token}}function q7s(e){let t=KOe(e),n=t?.status;if(n==="pending"||n==="failed")return{status:n};if(n==="ready"&&t)return W7s(t);throw new Q7("Invalid OAuth poll response data")}function W7s(e){let t=KOe(e.user),n=KOe(e.zai);if(typeof e.token!="string"||!t||typeof t.user_id!="string"||!n||typeof n.access_token!="string")throw new Q7("Invalid OAuth ready response data");return{status:"ready",token:e.token,user:{...typeof t.avatar=="string"?{avatar:t.avatar}:{},...typeof t.email=="string"?{email:t.email}:{},...typeof t.name=="string"?{name:t.name}:{},user_id:t.user_id},zai:{access_token:n.access_token}}}function V7s(e,t){try{return JSON.parse(e)}catch{let r=typeof t=="number"&&(t<200||t>=300)?`OAuth HTTP error ${t} (empty or non-JSON response)`:"OAuth response is not valid JSON";throw new Q7(r,{httpStatus:t})}}function KOe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}var VZr,F7s,j7s,B7s,U7s,Q7,GZr=Y(()=>{"use strict";VZr=require("node:crypto"),F7s="https://zcode.z.ai/api/v1",j7s="zai",B7s=32,U7s="application/json",Q7=class extends Error{static{r(this,"ZaiCliOAuthError")}businessCode;httpStatus;constructor(t,n={}){super(t),this.name="ZaiCliOAuthError",this.businessCode=n.businessCode,this.httpStatus=n.httpStatus}};r(Xdn,"createZaiCliOAuthClient");r(HZr,"createZaiCliOAuthPollToken");r(z7s,"normalizeBaseUrl");r(WZr,"requestJsonEnvelope");r($7s,"parseInitData");r(q7s,"parsePollData");r(W7s,"parseReadyData");r(V7s,"parseJson");r(KOe,"asRecord")});function ZZr(e={}){let t=K7s(Z7s(e.env??process.env));return{decrypt(n){if(!J7s(n))return n;let s=n.slice(Qdn.length).split("."),[a,l,u]=s;if(!a||!l||!u||s.length!==3)throw new Error("Credential decrypt failed: invalid ciphertext format");let f=Buffer.from(a,"base64url"),g=Buffer.from(l,"base64url"),_=Buffer.from(u,"base64url");if(f.length!==KZr)throw new Error("Credential decrypt failed: invalid IV length");if(g.length!==H7s)throw new Error("Credential decrypt failed: invalid auth tag length");try{let b=(0,vG.createDecipheriv)(JZr,t,f);return b.setAuthTag(g),Buffer.concat([b.update(_),b.final()]).toString("utf-8")}catch(b){throw new Error("Credential decrypt failed: key mismatch or corrupted ciphertext",{cause:b})}},encrypt(n){let o=(0,vG.randomBytes)(KZr),s=(0,vG.createCipheriv)(JZr,t,o),a=Buffer.concat([s.update(n,"utf-8"),s.final()]),l=s.getAuthTag();return[Qdn,o.toString("base64url"),".",l.toString("base64url"),".",a.toString("base64url")].join("")}}}function J7s(e){return e.startsWith(Qdn)}function K7s(e){return(0,vG.createHash)("sha256").update(e).digest()}function Z7s(e){let t=e[G7s]?.trim();if(t)return t;let n="unknown";try{n=(0,oge.userInfo)().username}catch{}return`zcode-credential-fallback:${(0,oge.platform)()}:${(0,oge.homedir)()}:${n}`}var vG,oge,Qdn,JZr,KZr,H7s,G7s,epn=Y(()=>{"use strict";vG=require("node:crypto"),oge=require("node:os"),Qdn="enc:v1:",JZr="aes-256-gcm",KZr=12,H7s=16,G7s="ZCODE_CREDENTIAL_SECRET";r(ZZr,"createZCodeCredentialCipher");r(J7s,"isEncryptedZCodeCredentialValue");r(K7s,"deriveCipherKey");r(Z7s,"resolveCredentialSecret")});function Q7s(e,t){let n=new Error(`OAuth authorization was rejected by the authorization server: ${e}`);return n.code=X7s,n.oauthError=e,t&&(n.oauthErrorDescription=t),n}async function YOe(e){let t=r(()=>{},"resolveCallback"),n=r(()=>{},"rejectCallback"),o=!1,s=new Promise((f,g)=>{t=f,n=g}),a=(0,XZr.createServer)((f,g)=>{try{let _=new URL(f.url??"/",`http://${tpn}`);if(_.pathname!==e.callbackPath){ige(g,404,ZOe);return}if((_.searchParams.get("state")??"")!==e.state){ige(g,400,ZOe);return}let w=_.searchParams.get("error");if(w){ige(g,400,ZOe),o||(o=!0,n(Q7s(w,_.searchParams.get("error_description"))));return}let T=_.searchParams.get("authCode")??_.searchParams.get("code")??"";if(!T){ige(g,400,ZOe),o||(o=!0,n(new Error("OAuth callback is missing an authorization code.")));return}ige(g,200,Y7s),o||(o=!0,t({code:T,url:_.toString()}))}catch(_){ige(g,500,ZOe),o||(o=!0,n(_ instanceof Error?_:new Error(String(_))))}});await new Promise((f,g)=>{a.once("error",g),a.listen(0,tpn,()=>{a.off("error",g),f()})});let l=a.address();if(!e$s(l))throw await YZr(a),new Error("Unable to resolve localhost callback server address.");let u=`http://${tpn}:${l.port}${e.callbackPath}`;return{callbackPath:e.callbackPath,callbackUrl:u,close:r(async()=>{await YZr(a)},"close"),waitForCallback:r(()=>s,"waitForCallback")}}function ige(e,t,n){e.writeHead(t,{"Content-Type":"text/plain; charset=utf-8"}),e.end(n)}function YZr(e){return e.listening?new Promise((t,n)=>{e.close(o=>{if(o){n(o);return}t()})}):Promise.resolve()}function e$s(e){return typeof e=="object"&&e!==null&&"port"in e}var XZr,tpn,Y7s,ZOe,X7s,Tct=Y(()=>{"use strict";XZr=require("node:http"),tpn="127.0.0.1",Y7s="Authorization successful! You may close this window and return to the CLI.",ZOe="Authorization failed. You may close this window and return to the CLI.",X7s="MCP_OAUTH_CALLBACK_DENIED";r(Q7s,"createCallbackDeniedError");r(YOe,"createLocalhostOAuthCallbackServer");r(ige,"writeText");r(YZr,"closeServer");r(e$s,"isAddressInfo")});function jM(e={}){let t=e.env??process.env,n=n$s(e),o=e.cipher??ZZr({env:t});return{filePath:n,async clearZaiLoginCredentials(){await e$(n,async s=>{let a=s[R1.activeProvider],l=a?o.decrypt(a):null;delete s[R1.zaiAccessToken],delete s[R1.zaiRefreshToken],delete s[R1.zaiUserInfo],delete s[R1.zcodeJwtToken],l===QZr&&delete s[R1.activeProvider]})},async delete(s){let a=VF(s);await e$(n,l=>{delete l[a]})},async deleteIfValue(s,a){let l=VF(s),u=bG(a),f=!1;return await e$(n,g=>{let _=g[l];_===void 0||o.decrypt(_)!==u||(delete g[l],f=!0)}),f},async deleteIfValues(s){let a=Object.entries(s).map(([u,f])=>[VF(u),bG(f)]);if(a.length===0)return{};let l={};return await e$(n,u=>{for(let[f,g]of a){let _=u[f],b=_!==void 0&&o.decrypt(_)===g;l[f]=b,b&&delete u[f]}}),l},async deleteManyIfValue(s,a,l){let u=VF(s),f=bG(a),g=l.map(VF),_=!1;return await e$(n,b=>{let w=b[u];if(!(w===void 0||o.decrypt(w)!==f)){for(let T of g)delete b[T];_=!0}}),_},async load(s){let l=(await npn(n))[VF(s)];return l===void 0?null:o.decrypt(l)},async loadMany(s){let a=s.map(VF),l=await npn(n);return Object.fromEntries(a.map(u=>{let f=l[u];return[u,f===void 0?null:o.decrypt(f)]}))},onDidChange(s){let a=Ict.get(n);return a||(a=new Set,Ict.set(n,a)),a.add(s),()=>{a?.delete(s),a?.size===0&&Ict.delete(n)}},async save(s,a){let l=VF(s),u=o.encrypt(bG(a));await e$(n,f=>{f[l]=u})},async saveMany(s){let a=Object.entries(s).map(([l,u])=>[VF(l),o.encrypt(bG(u))]);await e$(n,l=>{for(let[u,f]of a)l[u]=f})},async saveReplacing(s,a,l){let u=VF(s),f=o.encrypt(bG(a)),g=l.map(VF);await e$(n,_=>{_[u]=f;for(let b of g)b!==u&&delete _[b]})},async saveZaiLoginCredentials(s){let a={activeProvider:o.encrypt(QZr),accessToken:o.encrypt(bG(s.accessToken)),jwtToken:o.encrypt(bG(s.jwtToken)),userInfo:o.encrypt(JSON.stringify(s.user))};await e$(n,l=>{l[R1.activeProvider]=a.activeProvider,l[R1.zaiAccessToken]=a.accessToken,l[R1.zcodeJwtToken]=a.jwtToken,l[R1.zaiUserInfo]=a.userInfo})}}}function n$s(e={}){e={...e,filePath:e.filePath??(e.env??process.env).ZCODE_CLI_CREDENTIALS_FILE?.trim()};if(e.filePath)return eYr(e.filePath);let t=e.env??process.env,n=e.baseDir??t[t$s]??(0,Cct.homedir)();return(0,XOe.join)(eYr(n),".zcode","v2","credentials.json")}async function npn(e){let t;try{t=await(0,tYr.readFile)(e,"utf-8")}catch(n){if(o$s(n)==="ENOENT")return{};throw new Error(`Unable to read shared ZCode credentials: ${e}`,{cause:n})}try{return r$s(JSON.parse(t))}catch(n){let o=await Gqt(e).catch(()=>{}),s=o?` Backup: ${o}`:"";throw new Error(`Shared ZCode credentials are corrupt: ${e}.${s}`,{cause:n})}}async function e$(e,t){await lw(e,async()=>{let o=await npn(e);await t(o),await qL(e,`${JSON.stringify(o,null,2)}
|
|
2137
2137
|
`)});let n=[...Ict.get(e)??[]];await Promise.allSettled(n.map(o=>o()))}function r$s(e){if(!i$s(e))throw new Error("Credential record must be an object");let t={};for(let[n,o]of Object.entries(e)){if(typeof o!="string")throw new Error(`Credential record value must be a string: ${n}`);t[n]=o}return t}function o$s(e){if(typeof e!="object"||e===null||!("code"in e))return;let t=e.code;return typeof t=="string"?t:void 0}function VF(e){let t=e.trim();if(t.length===0)throw new Error("Credential key must not be empty");return t}function bG(e){if(e.length===0)throw new Error("Credential value must not be empty");return e}function eYr(e){return e==="~"?(0,Cct.homedir)():e.startsWith("~/")?(0,XOe.join)((0,Cct.homedir)(),e.slice(2)):(0,XOe.resolve)(e)}function i$s(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var tYr,Cct,XOe,t$s,QZr,Ict,R1,Ect=Y(()=>{"use strict";tYr=require("node:fs/promises"),Cct=require("node:os"),XOe=require("node:path");bz();epn();t$s="ZCODE_DATA_BASE_DIR",QZr="zai",Ict=new Map,R1={activeProvider:"oauth:active_provider",bigmodelAccessToken:"oauth:bigmodel:access_token",bigmodelRefreshToken:"oauth:bigmodel:refresh_token",bigmodelUserInfo:"oauth:bigmodel:user_info",zaiAccessToken:"oauth:zai:access_token",zaiRefreshToken:"oauth:zai:refresh_token",zaiUserInfo:"oauth:zai:user_info",zcodeJwtToken:"zcodejwttoken"};r(jM,"createSharedZCodeCredentialStore");r(n$s,"resolveSharedZCodeCredentialsPath");r(npn,"readRawCredentialRecord");r(e$,"mutateRawCredentialRecord");r(r$s,"parseCredentialRecord");r(o$s,"getErrorCode");r(VF,"validateCredentialKey");r(bG,"validateCredentialValue");r(eYr,"resolveUserPath");r(i$s,"isRecord")});var rpn=Y(()=>{"use strict";NZr();FZr();qZr();GZr();epn();Tct();Ect()});function nYr(e,t){return{id:e,generation:t,type:"cdp",name:"ZCode Headless Chromium",capabilities:{browser:[],tab:[]},apiSupportOverrides:{"BrowserUser.openTabs":!1,"BrowserUser.history":!1,"PlaywrightAPI.waitForEvent":!1,"PlaywrightDownload.path":!1,"PlaywrightFileChooser.setFiles":!1,"PlaywrightLocator.downloadMedia":!1,"PlaywrightLocator.evaluate":!1,"CUAAPI.downloadMedia":!1,"DomCUAAPI.downloadMedia":!1},metadata:{provider:"zcode-cli",launchMode:"managed",headless:"true"}}}var rYr=Y(()=>{"use strict";r(nYr,"createManagedCdpDescriptor")});function c$s(e){return[e.PROGRAMFILES,e["PROGRAMFILES(X86)"],e.LOCALAPPDATA].filter(t=>!!t?.trim()).flatMap(t=>[(0,sge.join)(t,"Google","Chrome","Application","chrome.exe"),(0,sge.join)(t,"Chromium","Application","chrome.exe"),(0,sge.join)(t,"Microsoft","Edge","Application","msedge.exe")])}function oYr(e,t){try{return!(0,SG.existsSync)(e)||!(0,SG.statSync)(e).isFile()?!1:(t!=="win32"&&(0,SG.accessSync)(e,SG.constants.X_OK),!0)}catch{return!1}}function Act(e,t=process.platform){if(e===void 0)return;if(!(0,sge.isAbsolute)(e))throw new Error(`Browser executable path must be absolute: ${e}`);let n=e;if(!oYr(n,t))throw new Error(`Browser executable is missing or not executable: ${n}`);return n}function opn(e,t={}){let n=t.platform??process.platform,o=Act(t.executablePath,n);if(o)return o;let s=e.chromium.executablePath(),l=[...s?[s]:[],...n==="darwin"?a$s:n==="win32"?c$s(t.env??process.env):s$s].find(u=>oYr(u,n));if(l)return l;throw new Error("No installed Chrome or Chromium executable was found. Install Chromium or pass --browser-executable <absolute-path>.")}async function iYr(){return await import("playwright-core")}var SG,sge,s$s,a$s,ipn=Y(()=>{"use strict";SG=require("node:fs"),sge=require("node:path"),s$s=["/usr/bin/google-chrome-stable","/usr/bin/google-chrome","/usr/bin/chromium","/usr/bin/chromium-browser","/snap/bin/chromium"],a$s=["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"];r(c$s,"windowsBrowserPaths");r(oYr,"isUsableExecutable");r(Act,"validateExplicitBrowserExecutable");r(opn,"resolveInstalledBrowserExecutable");r(iYr,"loadPlaywrightChromium")});function Pct(e){return e===void 0?3e3:Math.min(3e3,Math.max(1,Math.floor(e)))}function l$s(e,t){return e.locator(t)}function sYr(e){return(e??[]).map(t=>t==="ControlOrMeta"?process.platform==="darwin"?"Meta":"Control":t)}async function spn(e,t,n,o,s){let a=await e.context().newCDPSession(e);try{let l=n==="function"?`(${t})(${JSON.stringify(o)})`:t,u=await a.send("Runtime.evaluate",{expression:l,awaitPromise:!0,returnByValue:!0,timeout:s});if(u.exceptionDetails){let f=u.exceptionDetails.exception?.description??u.exceptionDetails.text??"Playwright evaluate failed";throw new Error(`playwright.evaluate failed: ${f}`)}return u.result?.value}finally{await a.detach().catch(()=>{})}}async function u$s(e,t){let n=l$s(e,t.selector),o=Pct(t.timeoutMs);switch(t.operation){case"allTextContents":return await n.allTextContents();case"count":return await n.count();case"getAttribute":return await n.getAttribute(t.attribute??"",{timeout:o});case"innerText":return await n.innerText({timeout:o});case"isEnabled":return await n.isEnabled({timeout:o});case"isVisible":return await n.isVisible();case"textContent":return await n.textContent({timeout:o});case"click":await n.click({button:t.button,force:t.force,modifiers:sYr(t.modifiers),timeout:o});return;case"dblclick":await n.dblclick({button:t.button,force:t.force,modifiers:sYr(t.modifiers),timeout:o});return;case"fill":t.replace===!1?await n.pressSequentially(String(t.value??""),{timeout:o}):await n.fill(String(t.value??""),{timeout:o});return;case"press":await n.press(String(t.value??""),{timeout:o});return;case"selectOption":{let s=(t.selections??[]).map(a=>a.index!==void 0?{index:a.index}:a.label!==void 0?{label:a.label}:{value:a.value??""});await n.selectOption(s,{timeout:o});return}case"setChecked":await n.setChecked(t.checked??!0,{force:t.force,timeout:o});return;case"waitFor":await n.waitFor({state:t.state??"visible",timeout:o});return;case"downloadMedia":case"evaluate":throw new Error(`Playwright locator operation '${t.operation}' is unavailable`)}}async function aYr(e,t){switch(t.name){case"domSnapshot":return{ok:!0,value:await e.locator("html").ariaSnapshot({timeout:3e3})};case"elementInfo":return{ok:!0,value:await e.evaluate(({x:n,y:o,includeNonInteractable:s})=>document.elementsFromPoint(n,o).filter(a=>s||a.matches("a,button,input,select,textarea,[role],[tabindex]")).map(a=>{let l=a.getBoundingClientRect(),u=(a.innerText||a.textContent||"").trim();return{tagName:a.tagName.toLowerCase(),role:a.getAttribute("role"),visibleText:u||null,ariaName:a.getAttribute("aria-label")||u||null,testId:a.getAttribute("data-testid"),boundingBox:{x:l.x,y:l.y,width:l.width,height:l.height},preview:a.outerHTML.slice(0,300),selector:{primary:a.id?`#${a.id}`:a.tagName.toLowerCase(),candidates:[]}}}),t)};case"elementScreenshot":{let n="data-zcode-element-screenshot";if(await e.evaluate(({x:s,y:a,includeNonInteractable:l,markerAttribute:u})=>{let f=document.elementsFromPoint(s,a).filter(_=>l||_.matches("a,button,input,select,textarea,[role],[tabindex]")),g=0;for(let _ of f){let b=_.getBoundingClientRect();if(b.width<=0||b.height<=0)continue;let w=document.createElement("div");w.setAttribute(u,""),Object.assign(w.style,{border:"2px solid #ff2d55",boxSizing:"border-box",height:`${b.height}px`,left:`${b.left}px`,pointerEvents:"none",position:"fixed",top:`${b.top}px`,width:`${b.width}px`,zIndex:"2147483647"}),document.documentElement.append(w),g+=1}return g},{...t,markerAttribute:n})===0)throw new Error("No matching element was found at the requested point");try{return{ok:!0,image:{base64:(await e.screenshot({type:"png"})).toString("base64"),mimeType:"image/png"}}}finally{await e.evaluate(s=>document.querySelectorAll(`[${s}]`).forEach(a=>a.remove()),n).catch(()=>{})}}case"evaluate":return{ok:!0,value:await spn(e,t.expression,t.expressionKind,t.arg,Pct(t.timeoutMs))};case"waitForLoadState":if((t.state??"load")==="networkidle")throw new Error("playwright_wait_for_load_state does not support networkidle");return await e.waitForLoadState(t.state??"load",{timeout:Pct(t.timeoutMs)}),{ok:!0};case"waitForURL":if(t.waitUntil==="networkidle")throw new Error("playwright_wait_for_url does not support networkidle");return await e.waitForURL(t.url,{timeout:Pct(t.timeoutMs),waitUntil:t.waitUntil??"load"}),{ok:!0};case"locator":{let n=await u$s(e,t);return n===void 0?{ok:!0}:{ok:!0,value:n}}case"waitForEvent":case"downloadPath":case"fileChooserSetFiles":throw new Error(`Playwright action '${t.name}' is unavailable`)}}var cYr=Y(()=>{"use strict";r(Pct,"timeoutMs");r(l$s,"locatorFor");r(sYr,"modifiers");r(spn,"evaluatePage");r(u$s,"runLocatorAction");r(aYr,"executeManagedPlaywrightAction")});function d$s(e){let t="a[href],button,input,textarea,select,[role],[onclick],[tabindex],summary,label,[contenteditable]",n="body,main,nav,header,footer,aside,section,article,h1,h2,h3,h4,h5,h6,p,ul,ol,li,dl,dt,dd,blockquote,pre,code,table,caption,thead,tbody,tfoot,tr,th,td,form,fieldset,legend,figure,figcaption,img,canvas,svg,a[href],button,input,textarea,select,option,summary,label,[role],[aria-label],[contenteditable]",o=[],s=new WeakMap,a=window.innerWidth||document.documentElement.clientWidth||0,l=window.innerHeight||document.documentElement.clientHeight||0,u=r(B=>{let z=window.getComputedStyle(B),$=B.getBoundingClientRect();return z.display==="none"||z.visibility==="hidden"||z.opacity==="0"||$.width<=0&&$.height<=0},"hidden"),f=r((B,z)=>String(B??"").trim().replace(/\s+/g," ").slice(0,z),"text"),g=r((B,z)=>{if(z==="a"&&B.hasAttribute("href"))return"link";if(z==="button")return"button";if(z==="select")return"combobox";if(z==="textarea")return"textbox";if(z!=="input")return"";let $=(B.getAttribute("type")||"text").toLowerCase();return $==="checkbox"?"checkbox":$==="radio"?"radio":["button","submit","reset"].includes($)?"button":$==="search"?"searchbox":"textbox"},"implicitRole"),_=r(B=>f(B.getAttribute("aria-label")||B.getAttribute("alt")||B.getAttribute("title")||B.getAttribute("placeholder")||B.innerText||B.textContent,120),"accessibleName"),b=r(B=>{let z={};for(let $ of["id","href","name","type","placeholder","title","alt","role","aria-label","data-testid","data-test","data-qa"]){let J=f(B.getAttribute($),240);J&&(z[$]=J)}return z},"attributes"),w=r(B=>{if(B.id&&/^[A-Za-z][A-Za-z0-9_-]*$/.test(B.id))return`#${B.id}`;let z=[],$=B;for(let J=0;$&&J<6;J+=1){let q=$.tagName.toLowerCase(),ie=$.parentElement?[...$.parentElement.children].filter(ae=>ae.tagName===$?.tagName):[];z.unshift(`${q}:nth-of-type(${ie.indexOf($)+1})`),$=$.parentElement}return z.join(" > ")},"selector"),T=r(B=>{let z=[],$=B;for(;$;){let J=$.tagName.toLowerCase(),q=$.parentElement?[...$.parentElement.children].filter(ie=>ie.tagName===$?.tagName):[];z.unshift(`${J}[${q.indexOf($)+1}]`),$=$.parentElement}return`/${z.join("/")}`},"xpath"),I=r(B=>B.top<l&&B.bottom>0&&B.left<a&&B.right>0,"inViewport"),E=[...document.querySelectorAll(t)].filter(B=>e.includeHidden||!u(B)),R=E.slice(0,e.maxElements).map((B,z)=>{let $=`e${z+1}`;o.push(B),s.set(B,$);let J=B.getBoundingClientRect(),q=B.tagName.toLowerCase(),ie=B.getAttribute("role")||g(B,q),ae=_(B),Ce=f(B.innerText,100),pe=b(B),ze="value"in B?f(String(B.value),240):"",rt=B.parentElement,Pe;for(;rt&&!Pe;)Pe=s.get(rt),rt=rt.parentElement;return{ref:$,tag:q,...ie?{role:ie}:{},...ae?{name:ae}:{},...Ce?{text:Ce}:{},...ze?{value:ze}:{},..."disabled"in B&&B.disabled?{disabled:!0}:{},..."checked"in B?{checked:!!B.checked}:{},selector:w(B),xpath:T(B),rect:{x:Math.round(J.x),y:Math.round(J.y),width:Math.round(J.width),height:Math.round(J.height)},inViewport:I(J),...Pe?{parentRef:Pe}:{},...Object.keys(pe).length>0?{attributes:pe}:{}}}),L=[...document.querySelectorAll(n)].filter(B=>e.includeHidden||!u(B)),U=L.slice(0,e.maxDomNodes).map(B=>{let z=B.getBoundingClientRect(),$=B.tagName.toLowerCase(),J=B.getAttribute("role")||g(B,$),q=_(B),ie=/^(h[1-6]|p|li|dt|dd|blockquote|pre|code|caption|th|td|label|summary|button|a|option|legend|figcaption)$/.test($)?f(B.innerText||B.textContent,300):"",ae=0;for(let ze=B.parentElement;ze&&ze!==document.body;ze=ze.parentElement)ae+=1;let Ce=s.get(B),pe=b(B);return{tag:$,depth:ae,inViewport:I(z),...Ce?{ref:Ce}:{},...J?{role:J}:{},...q?{name:q}:{},...ie?{text:ie}:{},...Object.keys(pe).length>0?{attributes:pe}:{}}});return{refElements:o,snapshot:{url:location.href,title:document.title,elements:R,truncated:E.length>e.maxElements,dom:U,domTruncated:L.length>e.maxDomNodes}}}async function cpn(e,t=200,n=!1){let o=await e.evaluateHandle(d$s,{includeHidden:n,maxDomNodes:300,maxElements:Math.max(1,Math.floor(t))}),s=await o.getProperty("snapshot"),a=await o.getProperty("refElements"),l=await s.jsonValue(),u=new Map;for(let[g,_]of await a.getProperties()){let b=_.asElement();if(!b||!/^\d+$/u.test(g)){await _.dispose();continue}u.set(`e${Number(g)+1}`,b)}let f=apn.get(e);return apn.set(e,u),await Promise.all([...f?.values()??[]].map(async g=>g.dispose())),await Promise.all([s.dispose(),a.dispose(),o.dispose()]),l}async function lpn(e,t){let n=apn.get(e)?.get(t);return n&&await n.evaluate(s=>s.isConnected).catch(()=>!1)?n:void 0}async function lYr(e,t){let n=await lpn(e,t);if(!n)return;await n.scrollIntoViewIfNeeded();let o=await n.boundingBox();return o?{x:Math.round(o.x+o.width/2),y:Math.round(o.y+o.height/2)}:void 0}var apn,uYr=Y(()=>{"use strict";apn=new WeakMap;r(d$s,"collectSnapshot");r(cpn,"captureManagedCdpSnapshot");r(lpn,"resolveSnapshotElement");r(lYr,"resolveSnapshotRef")});function pYr(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"||t.href==="about:blank"}catch{return!1}}function p$s(e){return e==="ControlOrMeta"?process.platform==="darwin"?"Meta":"Control":e}async function age(e,t,n){let o=(t??[]).map(p$s);for(let s of o)await e.keyboard.down(s);try{await n()}finally{for(let s of o.reverse())await e.keyboard.up(s)}}async function Ere(e,t){let n=await lpn(e,t);if(!n)throw new Error(`Browser ref '${t}' is stale or unavailable. Take a fresh snapshot before retrying.`);return n}async function QOe(e,t,n){if(t){let o=await lYr(e,t);if(!o)throw new Error(`Browser ref '${t}' is stale or unavailable`);return o}if(n)return n;throw new Error("Browser action requires a ref or x/y coordinates")}async function eMe(e){let t=await e.context().newCDPSession(e);try{let n=await t.send("Page.getNavigationHistory"),o=n.currentIndex??0,s=n.entries?.length??1,a=e.viewportSize(),l=await e.evaluate(()=>({scrollX:Math.round(window.scrollX),scrollY:Math.round(window.scrollY)})).catch(()=>({scrollX:0,scrollY:0}));return{url:e.url(),title:await e.title().catch(()=>""),canGoBack:o>0,canGoForward:o+1<s,...l,...a?{viewportWidth:a.width,viewportHeight:a.height}:{}}}finally{await t.detach().catch(()=>{})}}async function f$s(e,t){if(t.length===0)return;let n=t.map(s=>s==="ControlOrMeta"?process.platform==="darwin"?"Meta":"Control":s),o=n.slice(0,-1);for(let s of o)await e.keyboard.down(s);try{await e.keyboard.press(n.at(-1)??"")}finally{for(let s of o.reverse())await e.keyboard.up(s)}}async function dYr(e,t){if(t.length===0)throw new Error("Browser drag requires a non-empty path");let[n,...o]=t;await e.mouse.move(n.x,n.y),await e.mouse.down();try{for(let s of o)await e.mouse.move(s.x,s.y,{steps:4})}finally{await e.mouse.up()}}async function fYr(e,t){switch(t.method){case"navigate":return pYr(t.url)?(await e.goto(t.url,{timeout:Rct,waitUntil:"load"}),{ok:!0,state:await eMe(e)}):{ok:!1,error:{code:"navigation_blocked",message:`Navigation URL is not allowed: ${t.url}`}};case"back":return await e.goBack({timeout:Rct,waitUntil:"load"}),{ok:!0,state:await eMe(e)};case"forward":return await e.goForward({timeout:Rct,waitUntil:"load"}),{ok:!0,state:await eMe(e)};case"reload":return await e.reload({timeout:Rct,waitUntil:"load"}),{ok:!0,state:await eMe(e)};case"getState":return{ok:!0,state:await eMe(e)};case"snapshot":return{ok:!0,snapshot:await cpn(e,t.maxElements,t.includeHidden)};case"screenshot":return{ok:!0,image:{base64:(t.ref?await(await Ere(e,t.ref)).screenshot({type:"png"}):await e.screenshot({type:"png",fullPage:t.fullPage,clip:t.clip})).toString("base64"),mimeType:"image/png"}};case"click":{let n=await QOe(e,t.ref,t.x!==void 0&&t.y!==void 0?{x:t.x,y:t.y}:void 0);return await age(e,t.modifiers,async()=>{await e.mouse.click(n.x,n.y,{button:t.button,clickCount:t.doubleClick?2:1})}),{ok:!0}}case"fill":return await(await Ere(e,t.ref)).fill(t.value),{ok:!0};case"type":return t.ref&&await(await Ere(e,t.ref)).focus(),await e.keyboard.type(t.text),{ok:!0};case"press":return t.ref?await(await Ere(e,t.ref)).press(t.key):await age(e,t.modifiers,async()=>e.keyboard.press(t.key)),{ok:!0};case"cuaKeypress":return await f$s(e,t.keys),{ok:!0};case"scroll":return t.ref&&await(await Ere(e,t.ref)).evaluate(n=>n.scrollIntoView()),await e.evaluate(({x:n,y:o})=>window.scrollBy(n,o),{x:t.x??0,y:t.y??0}),{ok:!0};case"cuaScroll":return await age(e,t.modifiers,async()=>{await e.mouse.move(t.x,t.y),await e.mouse.wheel(t.scrollX,t.scrollY)}),{ok:!0};case"domCuaScroll":{let n=t.nodeId?await QOe(e,t.nodeId,void 0):await e.evaluate(()=>({x:window.innerWidth/2,y:window.innerHeight/2}));return await e.mouse.move(n.x,n.y),await e.mouse.wheel(t.scrollX,t.scrollY),{ok:!0}}case"hover":{let n=await QOe(e,t.ref,t.x!==void 0&&t.y!==void 0?{x:t.x,y:t.y}:void 0);return await age(e,t.modifiers,async()=>e.mouse.move(n.x,n.y)),{ok:!0}}case"select":return await(await Ere(e,t.ref)).selectOption(t.values),{ok:!0};case"check":return await(await Ere(e,t.ref)).setChecked(t.checked??!0),{ok:!0};case"drag":{let n=await QOe(e,t.fromRef,t.from),o=await QOe(e,t.toRef,t.to);return await age(e,t.modifiers,async()=>dYr(e,[n,o])),{ok:!0}}case"cuaDrag":return await age(e,t.modifiers,async()=>dYr(e,t.path)),{ok:!0};case"elementInfo":return{ok:!0,element:(await cpn(e)).elements.find(o=>t.x>=o.rect.x&&t.x<=o.rect.x+o.rect.width&&t.y>=o.rect.y&&t.y<=o.rect.y+o.rect.height)};case"evaluate":return{ok:!0,value:await spn(e,t.expression,"string",void 0,3e3)};case"waitFor":{let n=Math.min(3e3,Math.max(1,t.timeoutMs??3e3));if(t.selector)await e.locator(t.selector).waitFor({timeout:n,state:"visible"});else if(t.text)await e.getByText(t.text).waitFor({timeout:n,state:"visible"});else if(t.textGone)await e.getByText(t.textGone).waitFor({timeout:n,state:"hidden"});else throw new Error("waitFor requires selector, text, or textGone");return{ok:!0}}case"playwright":return await aYr(e,t.action);case"playwrightWaitForTimeout":return await new Promise(n=>setTimeout(n,t.timeoutMs)),{ok:!0};default:return{ok:!1,error:{code:"capability_unsupported",message:`Browser command '${t.method}' is unavailable in the managed CDP page runtime`}}}}var Rct,upn=Y(()=>{"use strict";cYr();uYr();Rct=3e4;r(pYr,"isAllowedManagedBrowserUrl");r(p$s,"normalizedModifier");r(age,"withModifiers");r(Ere,"elementForRef");r(QOe,"pointFor");r(eMe,"readManagedPageState");r(f$s,"pressKeys");r(dYr,"dragPath");r(fYr,"executeManagedPageCommand")});function HF(){return new DOMException("Browser command cancelled","AbortError")}async function dpn(e,t){if(t.aborted)throw HF();return await new Promise((n,o)=>{let s=r(()=>o(HF()),"onAbort");t.addEventListener("abort",s,{once:!0}),e.then(n,o).finally(()=>t.removeEventListener("abort",s))})}function mYr(e){return e.method==="playwright"&&e.action.name==="locator"?["click","dblclick","fill","press","selectOption","setChecked"].includes(e.action.operation):e.method==="playwright"&&e.action.name==="evaluate"?!0:["navigate","back","forward","reload","click","fill","type","press","cuaKeypress","scroll","cuaScroll","domCuaScroll","hover","select","check","drag","cuaDrag","handleDialog","close","newTab","evaluate"].includes(e.method)}function hYr(e){return e instanceof Error&&e.name==="AbortError"?"cancelled":e instanceof Error&&e.name==="TimeoutError"?"timeout":e instanceof Error&&/unavailable|closed|disconnected/iu.test(e.message)?"backend_unavailable":"execution_error"}var gYr=Y(()=>{"use strict";r(HF,"abortError");r(dpn,"raceWithAbort");r(mYr,"hasSideEffects");r(hYr,"classifyError")});var yYr,_Yr,Dct,vYr=Y(()=>{"use strict";yYr=require("node:crypto"),_Yr={width:1280,height:720},Dct=class{static{r(this,"ManagedCdpSession")}context;#e=new Map;#t=new Map;#n;constructor(t){this.context=t;for(let n of t.pages())this.registerPage(n);t.on("page",n=>this.registerPage(n))}get tabIds(){return[...this.#t.keys()]}get activeTabId(){return this.#n}async createTab(){let t=await this.context.newPage(),n=this.tabForPage(t)??this.registerPage(t);return this.#n=n.id,await t.bringToFront(),n}async ensureTab(t){if(t){let s=this.#t.get(t);if(!s||s.page.isClosed())throw new Error(`Browser tab '${t}' is unavailable`);return s}let n=this.#n?this.#t.get(this.#n):void 0;return n&&!n.page.isClosed()?n:[...this.#t.values()].find(s=>!s.page.isClosed())??await this.createTab()}async activateTab(t){let n=await this.ensureTab(t);return this.#n=n.id,await n.page.bringToFront(),n}async closeTab(t){let n=await this.ensureTab(t);this.#t.delete(n.id),this.#e.delete(n.id),n.page.isClosed()||await n.page.close({runBeforeUnload:!1}),this.#n===n.id&&(this.#n=[...this.#t.keys()].at(-1))}async listTabs(){let t=[];for(let n of this.#t.values())n.page.isClosed()||t.push({tabId:n.id,url:n.page.url(),title:await n.page.title().catch(()=>""),viewport:n.page.viewportSize()??_Yr,...n.id===this.#n?{active:!0}:{},lifecycle:"active"});return t}dialogFor(t){return this.#e.get(t)}clearDialog(t){this.#e.delete(t)}async setViewport(t,n){await(await this.ensureTab(t)).page.setViewportSize(n??_Yr)}async close(){this.#e.clear(),this.#t.clear(),this.context.browser()?.isConnected()&&await this.context.close().catch(()=>{})}registerPage(t){let n=this.tabForPage(t);if(n)return n;let o={id:`tab:${(0,yYr.randomUUID)()}`,page:t};return this.#t.set(o.id,o),this.#n??=o.id,t.on("dialog",s=>this.#e.set(o.id,s)),t.on("close",()=>{this.#t.delete(o.id),this.#e.delete(o.id),this.#n===o.id&&(this.#n=[...this.#t.keys()].at(-1))}),o}tabForPage(t){return[...this.#t.values()].find(n=>n.page===t)}}});function bYr(e={}){let t={...e,executablePath:Act(e.executablePath,e.platform)},n=new fpn(t);return{browserControlPort:n,close:r(async()=>n.close(),"close")}}function Are(e,t){return new Promise(n=>{let o=!1,s,a=r(l=>{o||(o=!0,s&&clearTimeout(s),n(l))},"finish");s=setTimeout(()=>a(!1),t),e.then(()=>a(!0),()=>a(!0))})}var ppn,m$s,fpn,mpn=Y(()=>{"use strict";ppn=require("node:crypto");rYr();ipn();upn();gYr();vYr();ipn();upn();m$s=1500,fpn=class{static{r(this,"ManagedCdpBrowserControlPort")}#e=`cdp:${(0,ppn.randomUUID)()}`;#t;#n;#r;#o=new Set;#i=new Map;#c=new Map;#s=new Map;#a;#l=!1;#d=1;#u;constructor(t){this.#n=t,this.#t=t.loadPlaywright??iYr,this.#r=Math.max(1,Math.trunc(t.closeTimeoutMs??m$s))}async list(t){return await this.ensureBrowser(t.signal),[this.descriptor()]}async execute(t){let n=Date.now();if(t.browserId!==this.#e||t.browserGeneration!==this.#d)return this.errorResult("backend_unavailable",`Browser backend '${t.browserId}' generation ${t.browserGeneration} is stale`,n);let o=(0,ppn.randomUUID)(),s=new AbortController,a=r(()=>s.abort(t.signal?.reason??HF()),"forwardAbort");t.signal?.addEventListener("abort",a,{once:!0}),t.signal?.aborted&&a(),this.#i.set(o,{controller:s,sessionId:t.sessionId,turnId:t.turnId});let l=!1;try{if(s.signal.aborted)throw HF();await this.ensureBrowser(s.signal);let u=await this.ensureSession(t.sessionId);if(s.signal.aborted)throw HF();l=!0;let f=await dpn(this.executeSessionCommand(u,t.command),s.signal);return await this.withMeta(u,t.command,f,n)}catch(u){let f=hYr(u);return this.errorResult(f,u instanceof Error?u.message:String(u),n,f==="cancelled"&&l&&mYr(t.command)?"uncertain":void 0)}finally{t.signal?.removeEventListener("abort",a),this.#i.delete(o)}}async turnEnded(t){for(let n of this.#i.values())n.sessionId===t.sessionId&&n.turnId===t.turnId&&n.controller.abort(HF())}async closeSession(t){this.#o.add(t.sessionId);for(let s of this.#i.values())s.sessionId===t.sessionId&&s.controller.abort(HF());let n=this.#c.get(t.sessionId);n&&(await Are(n,this.#r)||n.then(async()=>{this.#s.size===0&&await this.closeBrowser()},async()=>{this.#s.size===0&&await this.closeBrowser()}));let o=this.#s.get(t.sessionId);this.#s.delete(t.sessionId),o&&await Are(o.close(),this.#r),this.#s.size===0&&await this.closeBrowser()}async close(){if(this.#l)return;this.#l=!0;let t=this.#u;for(let n of this.#i.values())n.controller.abort(HF());this.#i.clear(),this.#o.clear(),await Promise.all([...this.#c.values()].map(async n=>{await Are(n,this.#r)})),await Promise.all([...this.#s.values()].map(async n=>{await Are(n.close(),this.#r)})),this.#s.clear(),await this.closeBrowser(),t&&await Are(t.then(async n=>this.closeBrowserInstance(n)),this.#r)}descriptor(){return nYr(this.#e,this.#d)}async ensureBrowser(t){if(this.#l)throw new Error("Managed CDP browser runtime is closed");if(t?.aborted)throw HF();if(this.#a?.isConnected())return this.#a;this.#u??=(async()=>{let o;try{o=await this.#t()}catch(l){throw new Error("Managed headless Chromium is unavailable: failed to load the pinned Playwright runtime.",{cause:l})}let s=opn(o,this.#n),a;try{a=await o.chromium.launch({executablePath:s,headless:!0,args:["--no-first-run","--no-default-browser-check"]})}catch(l){throw new Error("Managed headless Chromium is unavailable: launch failed. Verify the browser executable and OS sandbox/runtime dependencies.",{cause:l})}if(this.#l)throw await this.closeBrowserInstance(a),new Error("Managed CDP browser runtime is closed");return a.on("disconnected",()=>{this.#a===a&&(this.#a=void 0,this.#s.clear(),this.#d+=1)}),this.#a=a,a})().finally(()=>{this.#u=void 0});let n=t?await dpn(this.#u,t):await this.#u;if(t?.aborted)throw await this.closeBrowserInstance(n),HF();return n}async ensureSession(t){if(this.#o.has(t))throw new Error(`Browser session '${t}' is closing`);let n=this.#s.get(t);if(n)return n;let o=this.#c.get(t);if(o)return await o;let s=(async()=>{let a=await this.ensureBrowser(),l=this.#d,u=await a.newContext({acceptDownloads:!1,viewport:{width:1280,height:720}});if(this.#l||this.#o.has(t)||this.#a!==a||this.#d!==l||!a.isConnected())throw await Are(u.close(),this.#r),new Error("Managed CDP browser context became unavailable during creation");let f=new Dct(u);return this.#s.set(t,f),f})();this.#c.set(t,s);try{return await s}finally{this.#c.get(t)===s&&this.#c.delete(t)}}async executeSessionCommand(t,n){switch(n.method){case"list":return{ok:!0,tabs:await t.listTabs()};case"newTab":{let o=await t.createTab();return{ok:!0,tab:(await t.listTabs()).find(s=>s.tabId===o.id)}}case"activateTab":{let o=await t.activateTab(n.tabId);return{ok:!0,tab:(await t.listTabs()).find(s=>s.tabId===o.id)}}case"close":return await t.closeTab(n.tabId),{ok:!0};case"browserViewportSet":return await t.setViewport(n.tabId,{width:n.width,height:n.height}),{ok:!0};case"browserViewportReset":return await t.setViewport(n.tabId,null),{ok:!0};case"getDialog":{let o=await t.ensureTab(n.tabId),s=t.dialogFor(o.id),a=s?.type();return{ok:!0,dialog:s&&a&&["alert","confirm","prompt","beforeunload"].includes(a)?{type:a,message:s.message(),...s.defaultValue()?{defaultPrompt:s.defaultValue()}:{}}:null}}case"handleDialog":{let o=await t.ensureTab(n.tabId),s=t.dialogFor(o.id);if(!s)throw new Error("No JavaScript dialog is pending for this tab");return n.accept?await s.accept(n.promptText):await s.dismiss(),t.clearDialog(o.id),{ok:!0}}case"nameSession":return{ok:!0};case"listUserTabs":return{ok:!0,userTabs:[]};case"browserVisibilityGet":case"browserVisibilitySet":case"capabilities":case"claimTab":case"finalize":case"finalizeTabs":case"markDeliverable":case"markHandoff":case"turnEnded":case"closeSession":case"cancelRequest":return{ok:!1,error:{code:"capability_unsupported",message:`Browser command '${n.method}' is unavailable in managed headless CDP`}};default:{let o=await t.ensureTab("tabId"in n?n.tabId:void 0);return await fYr(o.page,n)}}}async withMeta(t,n,o,s){let a="tabId"in n?n.tabId:t.activeTabId,l=a?await t.ensureTab(a).catch(()=>{}):void 0;return{...o,elapsedMs:Date.now()-s,meta:{browserUse:!0,backendType:"cdp",browserId:this.#e,browserGeneration:this.#d,openTabIds:t.tabIds,...l?{tabId:l.id,currentUrl:l.page.url(),lifecycle:"active"}:{}}}}errorResult(t,n,o,s){return{ok:!1,error:{code:t,message:n,...s?{sideEffect:s}:{}},elapsedMs:Date.now()-o}}async closeBrowser(){let t=this.#a;this.#a=void 0,t&&await this.closeBrowserInstance(t)}async closeBrowserInstance(t){t.isConnected()&&await Are(t.close(),this.#r)}};r(bYr,"createManagedCdpBrowserRuntime");r(Are,"waitForPromise")});var h$s,Oct,g$s,_$s,y$s,v$s,qs,SYr,b$s,Mct,hpn=Y(()=>{h$s=Object.create,Oct=Object.defineProperty,g$s=Object.getOwnPropertyDescriptor,_$s=Object.getOwnPropertyNames,y$s=Object.getPrototypeOf,v$s=Object.prototype.hasOwnProperty,qs=r((e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),"__commonJSMin"),SYr=r((e,t)=>{let n={};for(var o in e)Oct(n,o,{get:e[o],enumerable:!0});return t&&Oct(n,Symbol.toStringTag,{value:"Module"}),n},"__exportAll"),b$s=r((e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(var s=_$s(t),a=0,l=s.length,u;a<l;a++)u=s[a],!v$s.call(e,u)&&u!==n&&Oct(e,u,{get:(f=>t[f]).bind(null,u),enumerable:!(o=g$s(t,u))||o.enumerable});return e},"__copyProps"),Mct=r((e,t,n)=>(n=e!=null?h$s(y$s(e)):{},b$s(t||!e||!e.__esModule?Oct(n,"default",{value:e,enumerable:!0}):n,e)),"__toESM")});function kYr(e){return typeof e=="string"&&wYr.has(e.replace(/#$/,""))}function xYr(e,t){if(!("$schema"in e)||typeof e.$schema!="string")return"2020-12";let n=e.$schema.replace(/#$/,"");if(S$s.has(n))return"2020-12";if(wYr.has(n))return"2019-09";if(w$s.has(n)||k$s.has(n))return"draft-7";throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}var S$s,wYr,w$s,k$s,gpn=Y(()=>{S$s=new Set(["https://json-schema.org/draft/2020-12/schema","http://json-schema.org/draft/2020-12/schema"]),wYr=new Set(["https://json-schema.org/draft/2019-09/schema","http://json-schema.org/draft/2019-09/schema"]),w$s=new Set(["https://json-schema.org/draft-07/schema","http://json-schema.org/draft-07/schema"]),k$s=new Set(["https://json-schema.org/draft-06/schema","http://json-schema.org/draft-06/schema"]);r(kYr,"declares2019Dialect");r(xYr,"declaredDialect")});var cge,Nct,Lct,n$,lge,r$,Rre,tMe,uge,Dre,wG,qv,ypn,nMe,rMe,Fct,jct,oMe,zk,Ore,Wv,D1,O1,iMe,Vv,kG,sMe,aMe,dge,pge,pB,vpn,cMe,Bct,lMe,Uct,xG,t$,fge,x$s,T$s,zct,$ct,qct,Wct,uMe,dMe,Vct,pMe,Hct,Mre,fMe,Gct,Jct,mMe,Kct,TG,IG,hMe,gMe,bpn,_Me,CG,o$,yMe,Zct,Yct,Xct,Qct,elt,mge,tlt,nlt,rlt,olt,ilt,slt,alt,clt,vMe,llt,ult,dlt,plt,flt,mlt,hlt,glt,_lt,ylt,vlt,blt,Slt,wlt,hge,gge,_ge,klt,xlt,Tlt,yge,Ilt,Clt,Elt,Alt,Plt,bMe,Rlt,Dlt,SMe,Spn,Olt,Mlt,Nlt,wMe,kMe,Llt,Flt,jlt,Blt,Ult,zlt,$lt,qlt,Wlt,Pre,Vlt,Hlt,Glt,Jlt,Klt,xMe,vge,bge,TMe,IMe,CMe,Zlt,EMe,AMe,Ylt,Xlt,PMe,Sge,Qlt,eut,tut,nut,rut,out,iut,sut,aut,cut,lut,uut,dut,put,fut,wpn,mut,EG,kpn,hut,xpn,Tpn,Ipn,Cpn,Epn,Apn,Ppn,Rpn,Dpn,Opn,Mpn,Npn,Lpn,Fpn,jpn,Uk,RMe,wge,gut,DMe,OMe,_ut,MMe,_pn,yut,vut,NMe,Bpn,Upn,TYr=Y(()=>{tc();cge="2025-11-25",Nct=[cge,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Lct="io.modelcontextprotocol/related-task",n$="io.modelcontextprotocol/protocolVersion",lge="io.modelcontextprotocol/clientInfo",r$="io.modelcontextprotocol/serverInfo",Rre="io.modelcontextprotocol/clientCapabilities",tMe="io.modelcontextprotocol/subscriptionId",uge="io.modelcontextprotocol/logLevel",Dre="2.0",wG=mV(()=>bc([$t(),Gs(),kc(),Bj(),cc($t(),wG),Go(wG)])),qv=cc($t(),wG),ypn=Go(wG),nMe=bc([$t(),Gs().int()]),rMe=$t(),Fct=Fr({ttl:Gs().optional()}),jct=Fr({taskId:$t()}),oMe=nu({progressToken:nMe.optional(),[Lct]:jct.optional()}),zk=Fr({_meta:oMe.optional()}),Ore=zk.extend({task:Fct.optional()}),Wv=Fr({method:$t(),params:zk.loose().optional()}),D1=Fr({_meta:oMe.optional()}),O1=Fr({method:$t(),params:D1.loose().optional()}),iMe=nu({get[r$](){return fge.optional().catch(void 0)}}),Vv=nu({_meta:iMe.optional()}),kG=bc([$t(),Gs().int()]),sMe=Fr({jsonrpc:si(Dre),id:kG,...Wv.shape}).strict(),aMe=Fr({jsonrpc:si(Dre),...O1.shape}).strict(),dge=Fr({jsonrpc:si(Dre),id:kG,result:Vv}).strict(),pge=Fr({jsonrpc:si(Dre),id:kG.optional(),error:Fr({code:Gs().int(),message:$t(),data:Dl().optional()})}).strict(),pB=bc([sMe,aMe,dge,pge]),vpn=bc([dge,pge]),cMe=Vv.strict(),Bct=D1.extend({requestId:kG.optional(),reason:$t().optional()}),lMe=O1.extend({method:si("notifications/cancelled"),params:Bct}),Uct=Fr({src:$t(),mimeType:$t().optional(),sizes:Go($t()).optional(),theme:Bu(["light","dark"]).optional()}),xG=Fr({icons:Go(Uct).optional()}),t$=Fr({name:$t(),title:$t().optional()}),fge=t$.extend({...t$.shape,...xG.shape,version:$t(),websiteUrl:$t().optional(),description:$t().optional()}),x$s=$L(Fr({applyDefaults:kc().optional()}),qv),T$s=hz(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,$L(Fr({form:x$s.optional(),url:qv.optional()}),qv.optional())),zct=nu({list:qv.optional(),cancel:qv.optional(),requests:nu({sampling:nu({createMessage:qv.optional()}).optional(),elicitation:nu({create:qv.optional()}).optional()}).optional()}),$ct=nu({list:qv.optional(),cancel:qv.optional(),requests:nu({tools:nu({call:qv.optional()}).optional()}).optional()}),qct=Fr({experimental:cc($t(),qv).optional(),sampling:Fr({context:qv.optional(),tools:qv.optional()}).optional(),elicitation:T$s.optional(),roots:Fr({listChanged:kc().optional()}).optional(),tasks:zct.optional(),extensions:cc($t(),qv).optional()}),Wct=zk.extend({protocolVersion:$t(),capabilities:qct,clientInfo:fge}),uMe=Wv.extend({method:si("initialize"),params:Wct}),dMe=Fr({experimental:cc($t(),qv).optional(),logging:qv.optional(),completions:qv.optional(),prompts:Fr({listChanged:kc().optional()}).optional(),resources:Fr({subscribe:kc().optional(),listChanged:kc().optional()}).optional(),tools:Fr({listChanged:kc().optional()}).optional(),tasks:$ct.optional(),extensions:cc($t(),qv).optional()}),Vct=Vv.extend({protocolVersion:$t(),capabilities:dMe,serverInfo:fge,instructions:$t().optional()}),pMe=O1.extend({method:si("notifications/initialized"),params:D1.optional()}),Hct=Wv.extend({method:si("server/discover"),params:zk.optional()}),Mre=Vv.extend({supportedVersions:Go($t()),capabilities:dMe,instructions:$t().optional()}),fMe=Wv.extend({method:si("ping"),params:zk.optional()}),Gct=Fr({progress:Gs(),total:xl(Gs()),message:xl($t())}),Jct=Fr({...D1.shape,...Gct.shape,progressToken:nMe}),mMe=O1.extend({method:si("notifications/progress"),params:Jct}),Kct=zk.extend({cursor:rMe.optional()}),TG=Wv.extend({params:Kct.optional()}),IG=Vv.extend({nextCursor:rMe.optional()}),hMe=Fr({uri:$t(),mimeType:xl($t()),_meta:cc($t(),Dl()).optional()}),gMe=hMe.extend({text:$t()}),bpn=$t().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),_Me=hMe.extend({blob:bpn}),CG=Bu(["user","assistant"]),o$=Fr({audience:Go(CG).optional(),priority:Gs().min(0).max(1).optional(),lastModified:jO.datetime({offset:!0}).optional()}),yMe=Fr({...t$.shape,...xG.shape,uri:$t(),description:xl($t()),mimeType:xl($t()),size:xl(Gs()),annotations:o$.optional(),_meta:xl(nu({}))}),Zct=Fr({...t$.shape,...xG.shape,uriTemplate:$t(),description:xl($t()),mimeType:xl($t()),annotations:o$.optional(),_meta:xl(nu({}))}),Yct=TG.extend({method:si("resources/list")}),Xct=IG.extend({resources:Go(yMe)}),Qct=TG.extend({method:si("resources/templates/list")}),elt=IG.extend({resourceTemplates:Go(Zct)}),mge=zk.extend({uri:$t()}),tlt=mge,nlt=Wv.extend({method:si("resources/read"),params:tlt}),rlt=Vv.extend({contents:Go(bc([gMe,_Me]))}),olt=O1.extend({method:si("notifications/resources/list_changed"),params:D1.optional()}),ilt=mge,slt=Wv.extend({method:si("resources/subscribe"),params:ilt}),alt=mge,clt=Wv.extend({method:si("resources/unsubscribe"),params:alt}),vMe=Fr({toolsListChanged:kc().optional(),promptsListChanged:kc().optional(),resourcesListChanged:kc().optional(),resourceSubscriptions:Go($t()).optional()}),llt=zk.extend({notifications:vMe}),ult=Wv.extend({method:si("subscriptions/listen"),params:llt}),dlt=D1.extend({notifications:vMe}),plt=O1.extend({method:si("notifications/subscriptions/acknowledged"),params:dlt}),flt=iMe.extend({[tMe]:kG}),mlt=Vv.extend({_meta:flt}),hlt=D1.extend({uri:$t()}),glt=O1.extend({method:si("notifications/resources/updated"),params:hlt}),_lt=Fr({name:$t(),description:xl($t()),required:xl(kc())}),ylt=Fr({...t$.shape,...xG.shape,description:xl($t()),arguments:xl(Go(_lt)),_meta:xl(nu({}))}),vlt=TG.extend({method:si("prompts/list")}),blt=IG.extend({prompts:Go(ylt)}),Slt=zk.extend({name:$t(),arguments:cc($t(),$t()).optional()}),wlt=Wv.extend({method:si("prompts/get"),params:Slt}),hge=Fr({type:si("text"),text:$t(),annotations:o$.optional(),_meta:cc($t(),Dl()).optional()}),gge=Fr({type:si("image"),data:bpn,mimeType:$t(),annotations:o$.optional(),_meta:cc($t(),Dl()).optional()}),_ge=Fr({type:si("audio"),data:bpn,mimeType:$t(),annotations:o$.optional(),_meta:cc($t(),Dl()).optional()}),klt=Fr({type:si("tool_use"),name:$t(),id:$t(),input:cc($t(),Dl()),_meta:cc($t(),Dl()).optional()}),xlt=Fr({type:si("resource"),resource:bc([gMe,_Me]),annotations:o$.optional(),_meta:cc($t(),Dl()).optional()}),Tlt=yMe.extend({type:si("resource_link")}),yge=bc([hge,gge,_ge,Tlt,xlt]),Ilt=Fr({role:CG,content:yge}),Clt=Vv.extend({description:$t().optional(),messages:Go(Ilt)}),Elt=O1.extend({method:si("notifications/prompts/list_changed"),params:D1.optional()}),Alt=Fr({title:$t().optional(),readOnlyHint:kc().optional(),destructiveHint:kc().optional(),idempotentHint:kc().optional(),openWorldHint:kc().optional()}),Plt=Fr({taskSupport:Bu(["required","optional","forbidden"]).optional()}),bMe=Fr({...t$.shape,...xG.shape,description:$t().optional(),inputSchema:Fr({type:si("object"),properties:cc($t(),wG).optional(),required:Go($t()).optional()}).catchall(Dl()),outputSchema:nu({$schema:$t().optional()}).optional(),annotations:Alt.optional(),execution:Plt.optional(),_meta:cc($t(),Dl()).optional()}),Rlt=TG.extend({method:si("tools/list")}),Dlt=IG.extend({tools:Go(bMe)}),SMe=Vv.extend({content:Go(yge).default([]),structuredContent:Dl().optional(),isError:kc().optional()}),Spn=SMe.or(Vv.extend({toolResult:Dl()})),Olt=Ore.extend({name:$t(),arguments:cc($t(),Dl()).optional()}),Mlt=Wv.extend({method:si("tools/call"),params:Olt}),Nlt=O1.extend({method:si("notifications/tools/list_changed"),params:D1.optional()}),wMe=Fr({autoRefresh:kc().default(!0),debounceMs:Gs().int().nonnegative().default(300)}),kMe=Bu(["debug","info","notice","warning","error","critical","alert","emergency"]),Llt=zk.extend({level:kMe}),Flt=Wv.extend({method:si("logging/setLevel"),params:Llt}),jlt=D1.extend({level:kMe,logger:$t().optional(),data:Dl()}),Blt=O1.extend({method:si("notifications/message"),params:jlt}),Ult=Fr({name:$t().optional()}),zlt=Fr({hints:Go(Ult).optional(),costPriority:Gs().min(0).max(1).optional(),speedPriority:Gs().min(0).max(1).optional(),intelligencePriority:Gs().min(0).max(1).optional()}),$lt=Fr({mode:Bu(["auto","required","none"]).optional()}),qlt=Fr({type:si("tool_result"),toolUseId:$t().describe("The unique identifier for the corresponding tool call."),content:Go(yge),structuredContent:Dl().optional(),isError:kc().optional(),_meta:cc($t(),Dl()).optional()}),Wlt=fV("type",[hge,gge,_ge]),Pre=fV("type",[hge,gge,_ge,klt,qlt]),Vlt=Fr({role:CG,content:bc([Pre,Go(Pre)]),_meta:cc($t(),Dl()).optional()}),Hlt=Ore.extend({messages:Go(Vlt),modelPreferences:zlt.optional(),systemPrompt:$t().optional(),includeContext:Bu(["none","thisServer","allServers"]).optional(),temperature:Gs().optional(),maxTokens:Gs().int(),stopSequences:Go($t()).optional(),metadata:qv.optional(),tools:Go(bMe).optional(),toolChoice:$lt.optional()}),Glt=Wv.extend({method:si("sampling/createMessage"),params:Hlt}),Jlt=Vv.extend({model:$t(),stopReason:xl(Bu(["endTurn","stopSequence","maxTokens"]).or($t())),role:CG,content:Wlt}),Klt=Vv.extend({model:$t(),stopReason:xl(Bu(["endTurn","stopSequence","maxTokens","toolUse"]).or($t())),role:CG,content:bc([Pre,Go(Pre)])}),xMe=Fr({type:si("boolean"),title:$t().optional(),description:$t().optional(),default:kc().optional()}),vge=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),minLength:Gs().optional(),maxLength:Gs().optional(),format:Bu(["email","uri","date","date-time"]).optional(),default:$t().optional()}),bge=Fr({type:Bu(["number","integer"]),title:$t().optional(),description:$t().optional(),minimum:Gs().optional(),maximum:Gs().optional(),default:Gs().optional()}),TMe=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),enum:Go($t()),default:$t().optional()}),IMe=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),oneOf:Go(Fr({const:$t(),title:$t()})),default:$t().optional()}),CMe=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),enum:Go($t()),enumNames:Go($t()).optional(),default:$t().optional()}),Zlt=bc([TMe,IMe]),EMe=Fr({type:si("array"),title:$t().optional(),description:$t().optional(),minItems:Gs().optional(),maxItems:Gs().optional(),items:Fr({type:si("string"),enum:Go($t())}),default:Go($t()).optional()}),AMe=Fr({type:si("array"),title:$t().optional(),description:$t().optional(),minItems:Gs().optional(),maxItems:Gs().optional(),items:Fr({anyOf:Go(Fr({const:$t(),title:$t()}))}),default:Go($t()).optional()}),Ylt=bc([EMe,AMe]),Xlt=bc([CMe,Zlt,Ylt]),PMe=bc([Xlt,xMe,vge,bge]),Sge=Ore.extend({mode:si("form").optional(),message:$t(),requestedSchema:Fr({type:si("object"),properties:cc($t(),PMe),required:Go($t()).optional()}).catchall(Dl())}),Qlt=Ore.extend({mode:si("url"),message:$t(),elicitationId:$t(),url:$t().url()}),eut=bc([Sge,Qlt]),tut=Wv.extend({method:si("elicitation/create"),params:eut}),nut=D1.extend({elicitationId:$t()}),rut=O1.extend({method:si("notifications/elicitation/complete"),params:nut}),out=Vv.extend({action:Bu(["accept","decline","cancel"]),content:hz(e=>e===null?void 0:e,cc($t(),bc([$t(),Gs(),kc(),Go($t())])).optional())}),iut=Fr({type:si("ref/resource"),uri:$t()}),sut=Fr({type:si("ref/prompt"),name:$t()}),aut=zk.extend({ref:bc([sut,iut]),argument:Fr({name:$t(),value:$t()}),context:Fr({arguments:cc($t(),$t()).optional()}).optional()}),cut=Wv.extend({method:si("completion/complete"),params:aut}),lut=Vv.extend({completion:nu({values:Go($t()).max(100),total:xl(Gs().int()),hasMore:xl(kc())})}),uut=Fr({uri:$t().startsWith("file://"),name:$t().optional(),_meta:cc($t(),Dl()).optional()}),dut=Wv.extend({method:si("roots/list"),params:zk.optional()}),put=Vv.extend({roots:Go(uut)}),fut=O1.extend({method:si("notifications/roots/list_changed"),params:D1.optional()}),wpn=nu({ttl:Gs().optional(),pollInterval:Gs().optional()}),mut=Bu(["working","input_required","completed","failed","cancelled"]),EG=Fr({taskId:$t(),status:mut,ttl:bc([Gs(),Bj()]),createdAt:$t(),lastUpdatedAt:$t(),pollInterval:xl(Gs()),statusMessage:xl($t())}),kpn=Vv.extend({task:EG}),hut=D1.merge(EG),xpn=O1.extend({method:si("notifications/tasks/status"),params:hut}),Tpn=Wv.extend({method:si("tasks/get"),params:zk.extend({taskId:$t()})}),Ipn=Vv.merge(EG),Cpn=Wv.extend({method:si("tasks/result"),params:zk.extend({taskId:$t()})}),Epn=Vv.loose(),Apn=TG.extend({method:si("tasks/list")}),Ppn=IG.extend({tasks:Go(EG)}),Rpn=Wv.extend({method:si("tasks/cancel"),params:zk.extend({taskId:$t()})}),Dpn=Vv.merge(EG),Opn=bc([fMe,uMe,Hct,cut,Flt,wlt,vlt,Yct,Qct,nlt,slt,clt,ult,Mlt,Rlt]),Mpn=bc([lMe,mMe,pMe,fut]),Npn=bc([cMe,Jlt,Klt,out,put]),Lpn=bc([fMe,Glt,tut,dut]),Fpn=bc([lMe,mMe,Blt,glt,olt,Nlt,Elt,plt,rut]),jpn=bc([cMe,Vct,Mre,lut,Clt,blt,Xct,elt,rlt,SMe,Dlt,mlt]),Uk=ape().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Eqt.custom,message:"URL must be parseable",fatal:!0}),KCe}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),RMe=nu({resource:$t().url(),authorization_servers:Go(Uk).optional(),jwks_uri:$t().url().optional(),scopes_supported:Go($t()).optional(),bearer_methods_supported:Go($t()).optional(),resource_signing_alg_values_supported:Go($t()).optional(),resource_name:$t().optional(),resource_documentation:$t().optional(),resource_policy_uri:$t().url().optional(),resource_tos_uri:$t().url().optional(),tls_client_certificate_bound_access_tokens:kc().optional(),authorization_details_types_supported:Go($t()).optional(),dpop_signing_alg_values_supported:Go($t()).optional(),dpop_bound_access_tokens_required:kc().optional()}),wge=nu({issuer:$t(),authorization_endpoint:Uk,token_endpoint:Uk,registration_endpoint:Uk.optional(),scopes_supported:Go($t()).optional(),response_types_supported:Go($t()),response_modes_supported:Go($t()).optional(),grant_types_supported:Go($t()).optional(),token_endpoint_auth_methods_supported:Go($t()).optional(),token_endpoint_auth_signing_alg_values_supported:Go($t()).optional(),service_documentation:Uk.optional(),revocation_endpoint:Uk.optional(),revocation_endpoint_auth_methods_supported:Go($t()).optional(),revocation_endpoint_auth_signing_alg_values_supported:Go($t()).optional(),introspection_endpoint:$t().optional(),introspection_endpoint_auth_methods_supported:Go($t()).optional(),introspection_endpoint_auth_signing_alg_values_supported:Go($t()).optional(),code_challenge_methods_supported:Go($t()).optional(),client_id_metadata_document_supported:kc().optional(),authorization_response_iss_parameter_supported:kc().optional().catch(void 0)}),gut=nu({issuer:$t(),authorization_endpoint:Uk,token_endpoint:Uk,userinfo_endpoint:Uk.optional(),jwks_uri:Uk,registration_endpoint:Uk.optional(),scopes_supported:Go($t()).optional(),response_types_supported:Go($t()),response_modes_supported:Go($t()).optional(),grant_types_supported:Go($t()).optional(),acr_values_supported:Go($t()).optional(),subject_types_supported:Go($t()),id_token_signing_alg_values_supported:Go($t()),id_token_encryption_alg_values_supported:Go($t()).optional(),id_token_encryption_enc_values_supported:Go($t()).optional(),userinfo_signing_alg_values_supported:Go($t()).optional(),userinfo_encryption_alg_values_supported:Go($t()).optional(),userinfo_encryption_enc_values_supported:Go($t()).optional(),request_object_signing_alg_values_supported:Go($t()).optional(),request_object_encryption_alg_values_supported:Go($t()).optional(),request_object_encryption_enc_values_supported:Go($t()).optional(),token_endpoint_auth_methods_supported:Go($t()).optional(),token_endpoint_auth_signing_alg_values_supported:Go($t()).optional(),display_values_supported:Go($t()).optional(),claim_types_supported:Go($t()).optional(),claims_supported:Go($t()).optional(),service_documentation:$t().optional(),claims_locales_supported:Go($t()).optional(),ui_locales_supported:Go($t()).optional(),claims_parameter_supported:kc().optional(),request_parameter_supported:kc().optional(),request_uri_parameter_supported:kc().optional(),require_request_uri_registration:kc().optional(),op_policy_uri:Uk.optional(),op_tos_uri:Uk.optional(),client_id_metadata_document_supported:kc().optional(),authorization_response_iss_parameter_supported:kc().optional().catch(void 0)}),DMe=Fr({...gut.shape,...wge.pick({code_challenge_methods_supported:!0}).shape}),OMe=Fr({access_token:$t(),id_token:$t().optional(),token_type:$t(),expires_in:qEe.number().optional(),scope:$t().optional(),refresh_token:$t().optional()}).strip(),_ut=Fr({issued_token_type:si("urn:ietf:params:oauth:token-type:id-jag"),access_token:$t(),token_type:$t().optional(),expires_in:Gs().optional(),scope:$t().optional()}).strip(),MMe=Fr({error:$t(),error_description:$t().optional(),error_uri:$t().optional()}),_pn=Uk.optional().or(si("").transform(()=>{})),yut=Fr({redirect_uris:Go(Uk),token_endpoint_auth_method:$t().optional(),grant_types:Go($t()).optional(),response_types:Go($t()).optional(),application_type:$t().optional(),client_name:$t().optional(),client_uri:Uk.optional(),logo_uri:_pn,scope:$t().optional(),contacts:Go($t()).optional(),tos_uri:_pn,policy_uri:$t().optional(),jwks_uri:Uk.optional(),jwks:sKe().optional(),software_id:$t().optional(),software_version:$t().optional(),software_statement:$t().optional()}).strip(),vut=Fr({client_id:$t(),client_secret:$t().optional(),client_id_issued_at:Gs().optional(),client_secret_expires_at:Gs().optional()}).strip(),NMe=yut.merge(vut),Bpn=Fr({error:$t(),error_description:$t().optional()}).strip(),Upn=Fr({token:$t(),token_type_hint:$t().optional()}).strip()});var NYr=Y(()=>{TYr()});function Lre(e,t){let n=new Set,o=t;for(;typeof o=="function";){let s=o.mcpBrand;Object.prototype.hasOwnProperty.call(o,"mcpBrand")&&typeof s=="string"&&n.add(s),o=Object.getPrototypeOf(o)}n.size!==0&&Object.defineProperty(e,Vpn,{value:n,enumerable:!1,configurable:!0})}function C2(e,t){try{if(typeof t=="object"&&t!==null&&Object.prototype.hasOwnProperty.call(e,"mcpBrand")&&typeof e.mcpBrand=="string"&&Object.prototype.hasOwnProperty.call(t,Vpn)){let n=t[Vpn];if(n&&typeof n.has=="function"&&n.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}function GYr(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function JYr({requestedResource:e,configuredResource:t}){let n=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(n.origin!==o.origin||n.pathname.length<o.pathname.length)return!1;let s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",a=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return s.startsWith(a)}function a$(e){return e>=KYr}function Ypn(e){return e.filter(t=>!a$(t))}function $Me(e){return e.filter(t=>a$(t))}function ZYr(e){let t=e.structuredContent;return t===void 0||!(typeof t!="object"||t===null||Array.isArray(t))||(e.content?.some(n=>n.type==="text")??!1)?e:{...e,content:[...e.content??[],{type:"text",text:JSON.stringify(t)}]}}function I$s(e){return e===null||typeof e!="object"||Array.isArray(e)||e.content!==void 0||YYr.some(t=>t in e)?e:{...e,content:[]}}function C$s(){let e=mV(()=>bc([$t(),Gs(),kc(),Bj(),cc($t(),e),Go(e)])),t=cc($t(),e),n=bc([$t(),Gs().int()]),o=$t(),s=Fr({ttl:Gs().optional()}),a=Fr({taskId:$t()}),l=nu({progressToken:n.optional(),"io.modelcontextprotocol/related-task":a.optional()}),u=Fr({_meta:l.optional()}),f=u.extend({task:s.optional()}),g=Fr({method:$t(),params:u.loose().optional()}),_=Fr({_meta:l.optional()}),b=Fr({method:$t(),params:_.loose().optional()}),w=nu({_meta:l.optional()}),T=bc([$t(),Gs().int()]),I=w.strict(),E=_.extend({requestId:T.optional(),reason:$t().optional()}),R=b.extend({method:si("notifications/cancelled"),params:E}),L=Fr({src:$t(),mimeType:$t().optional(),sizes:Go($t()).optional(),theme:Bu(["light","dark"]).optional()}),U=Fr({icons:Go(L).optional()}),B=Fr({name:$t(),title:$t().optional()}),z=B.extend({...B.shape,...U.shape,version:$t(),websiteUrl:$t().optional(),description:$t().optional()}),$=$L(Fr({applyDefaults:kc().optional()}),t),J=hz(Xv=>Xv&&typeof Xv=="object"&&!Array.isArray(Xv)&&Object.keys(Xv).length===0?{form:{}}:Xv,$L(Fr({form:$.optional(),url:t.optional()}),t.optional())),q=nu({list:t.optional(),cancel:t.optional(),requests:nu({sampling:nu({createMessage:t.optional()}).optional(),elicitation:nu({create:t.optional()}).optional()}).optional()}),ie=nu({list:t.optional(),cancel:t.optional(),requests:nu({tools:nu({call:t.optional()}).optional()}).optional()}),ae=Fr({experimental:cc($t(),t).optional(),sampling:Fr({context:t.optional(),tools:t.optional()}).optional(),elicitation:J.optional(),roots:Fr({listChanged:kc().optional()}).optional(),tasks:q.optional(),extensions:cc($t(),t).optional()}),Ce=u.extend({protocolVersion:$t(),capabilities:ae,clientInfo:z}),pe=g.extend({method:si("initialize"),params:Ce}),ze=Fr({experimental:cc($t(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:Fr({listChanged:kc().optional()}).optional(),resources:Fr({subscribe:kc().optional(),listChanged:kc().optional()}).optional(),tools:Fr({listChanged:kc().optional()}).optional(),tasks:ie.optional(),extensions:cc($t(),t).optional()}),rt=w.extend({protocolVersion:$t(),capabilities:ze,serverInfo:z,instructions:$t().optional()}),Pe=b.extend({method:si("notifications/initialized"),params:_.optional()}),Tt=g.extend({method:si("ping"),params:u.optional()}),Ye=Fr({progress:Gs(),total:xl(Gs()),message:xl($t())}),Fe=Fr({..._.shape,...Ye.shape,progressToken:n}),St=b.extend({method:si("notifications/progress"),params:Fe}),kt=u.extend({cursor:o.optional()}),st=g.extend({params:kt.optional()}),$e=w.extend({nextCursor:o.optional()}),jt=Fr({uri:$t(),mimeType:xl($t()),_meta:cc($t(),Dl()).optional()}),Je=jt.extend({text:$t()}),Xe=$t().refine(Xv=>{try{return atob(Xv),!0}catch{return!1}},{message:"Invalid Base64 string"}),_t=jt.extend({blob:Xe}),Dt=Bu(["user","assistant"]),gn=Fr({audience:Go(Dt).optional(),priority:Gs().min(0).max(1).optional(),lastModified:jO.datetime({offset:!0}).optional()}),cn=Fr({...B.shape,...U.shape,uri:$t(),description:xl($t()),mimeType:xl($t()),size:xl(Gs()),annotations:gn.optional(),_meta:xl(nu({}))}),Fn=Fr({...B.shape,...U.shape,uriTemplate:$t(),description:xl($t()),mimeType:xl($t()),annotations:gn.optional(),_meta:xl(nu({}))}),on=st.extend({method:si("resources/list")}),dt=$e.extend({resources:Go(cn)}),we=st.extend({method:si("resources/templates/list")}),_e=$e.extend({resourceTemplates:Go(Fn)}),Pt=u.extend({uri:$t()}),ut=Pt,Mn=g.extend({method:si("resources/read"),params:ut}),Dr=w.extend({contents:Go(bc([Je,_t]))}),gr=b.extend({method:si("notifications/resources/list_changed"),params:_.optional()}),eo=Pt,to=g.extend({method:si("resources/subscribe"),params:eo}),oo=Pt,ro=g.extend({method:si("resources/unsubscribe"),params:oo}),Ji=_.extend({uri:$t()}),pi=b.extend({method:si("notifications/resources/updated"),params:Ji}),Wi=Fr({name:$t(),description:xl($t()),required:xl(kc())}),Ii=Fr({...B.shape,...U.shape,description:xl($t()),arguments:xl(Go(Wi)),_meta:xl(nu({}))}),Rs=st.extend({method:si("prompts/list")}),ht=$e.extend({prompts:Go(Ii)}),mr=u.extend({name:$t(),arguments:cc($t(),$t()).optional()}),mi=g.extend({method:si("prompts/get"),params:mr}),Ar=Fr({type:si("text"),text:$t(),annotations:gn.optional(),_meta:cc($t(),Dl()).optional()}),hi=Fr({type:si("image"),data:Xe,mimeType:$t(),annotations:gn.optional(),_meta:cc($t(),Dl()).optional()}),Js=Fr({type:si("audio"),data:Xe,mimeType:$t(),annotations:gn.optional(),_meta:cc($t(),Dl()).optional()}),qa=Fr({type:si("tool_use"),name:$t(),id:$t(),input:cc($t(),Dl()),_meta:cc($t(),Dl()).optional()}),li=Fr({type:si("resource"),resource:bc([Je,_t]),annotations:gn.optional(),_meta:cc($t(),Dl()).optional()}),oa=cn.extend({type:si("resource_link")}),Fs=bc([Ar,hi,Js,oa,li]),Qo=Fr({role:Dt,content:Fs}),gi=w.extend({description:$t().optional(),messages:Go(Qo)}),kn=b.extend({method:si("notifications/prompts/list_changed"),params:_.optional()}),Nn=Fr({title:$t().optional(),readOnlyHint:kc().optional(),destructiveHint:kc().optional(),idempotentHint:kc().optional(),openWorldHint:kc().optional()}),Ur=Fr({taskSupport:Bu(["required","optional","forbidden"]).optional()}),Vo=Fr({...B.shape,...U.shape,description:$t().optional(),inputSchema:Fr({type:si("object"),properties:cc($t(),e).optional(),required:Go($t()).optional()}).catchall(Dl()),outputSchema:Fr({type:si("object"),properties:cc($t(),e).optional(),required:Go($t()).optional()}).catchall(Dl()).optional(),annotations:Nn.optional(),execution:Ur.optional(),_meta:cc($t(),Dl()).optional()}),qe=st.extend({method:si("tools/list")}),Kt=$e.extend({tools:Go(Vo)}),Jt=w.extend({content:Go(Fs),structuredContent:cc($t(),Dl()).optional(),isError:kc().optional()}),en=f.extend({name:$t(),arguments:cc($t(),Dl()).optional()}),qn=g.extend({method:si("tools/call"),params:en}),Yr=b.extend({method:si("notifications/tools/list_changed"),params:_.optional()}),ei=Bu(["debug","info","notice","warning","error","critical","alert","emergency"]),ki=u.extend({level:ei}),ca=g.extend({method:si("logging/setLevel"),params:ki}),ks=_.extend({level:ei,logger:$t().optional(),data:Dl()}),Ud=b.extend({method:si("notifications/message"),params:ks}),zd=Fr({name:$t().optional()}),Bm=Fr({hints:Go(zd).optional(),costPriority:Gs().min(0).max(1).optional(),speedPriority:Gs().min(0).max(1).optional(),intelligencePriority:Gs().min(0).max(1).optional()}),Xf=Fr({mode:Bu(["auto","required","none"]).optional()}),kf=Fr({type:si("tool_result"),toolUseId:$t().describe("The unique identifier for the corresponding tool call."),content:Go(Fs),structuredContent:Fr({}).loose().optional(),isError:kc().optional(),_meta:cc($t(),Dl()).optional()}),qi=fV("type",[Ar,hi,Js]),Tm=fV("type",[Ar,hi,Js,qa,kf]),ev=Fr({role:Dt,content:bc([Tm,Go(Tm)]),_meta:cc($t(),Dl()).optional()}),E0=f.extend({messages:Go(ev),modelPreferences:Bm.optional(),systemPrompt:$t().optional(),includeContext:Bu(["none","thisServer","allServers"]).optional(),temperature:Gs().optional(),maxTokens:Gs().int(),stopSequences:Go($t()).optional(),metadata:t.optional(),tools:Go(Vo).optional(),toolChoice:Xf.optional()}),tv=g.extend({method:si("sampling/createMessage"),params:E0}),z_=w.extend({model:$t(),stopReason:xl(Bu(["endTurn","stopSequence","maxTokens"]).or($t())),role:Dt,content:qi}),Yv=w.extend({model:$t(),stopReason:xl(Bu(["endTurn","stopSequence","maxTokens","toolUse"]).or($t())),role:Dt,content:bc([Tm,Go(Tm)])}),Lw=Fr({type:si("boolean"),title:$t().optional(),description:$t().optional(),default:kc().optional()}),Tu=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),minLength:Gs().optional(),maxLength:Gs().optional(),format:Bu(["email","uri","date","date-time"]).optional(),default:$t().optional()}),t0=Fr({type:Bu(["number","integer"]),title:$t().optional(),description:$t().optional(),minimum:Gs().optional(),maximum:Gs().optional(),default:Gs().optional()}),Ub=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),enum:Go($t()),default:$t().optional()}),ta=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),oneOf:Go(Fr({const:$t(),title:$t()})),default:$t().optional()}),af=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),enum:Go($t()),enumNames:Go($t()).optional(),default:$t().optional()}),lP=bc([Ub,ta]),tE=Fr({type:si("array"),title:$t().optional(),description:$t().optional(),minItems:Gs().optional(),maxItems:Gs().optional(),items:Fr({type:si("string"),enum:Go($t())}),default:Go($t()).optional()}),IS=Fr({type:si("array"),title:$t().optional(),description:$t().optional(),minItems:Gs().optional(),maxItems:Gs().optional(),items:Fr({anyOf:Go(Fr({const:$t(),title:$t()}))}),default:Go($t()).optional()}),Fw=bc([tE,IS]),Vs=bc([af,lP,Fw]),Iu=bc([Vs,Lw,Tu,t0]),bs=f.extend({mode:si("form").optional(),message:$t(),requestedSchema:Fr({type:si("object"),properties:cc($t(),Iu),required:Go($t()).optional()}).catchall(Dl())}),A0=f.extend({mode:si("url"),message:$t(),elicitationId:$t(),url:$t().url()}),ri=bc([bs,A0]),la=g.extend({method:si("elicitation/create"),params:ri}),ul=_.extend({elicitationId:$t()}),py=b.extend({method:si("notifications/elicitation/complete"),params:ul}),X0=w.extend({action:Bu(["accept","decline","cancel"]),content:hz(Xv=>Xv===null?void 0:Xv,cc($t(),bc([$t(),Gs(),kc(),Go($t())])).optional())}),jw=Fr({type:si("ref/resource"),uri:$t()}),Ds=Fr({type:si("ref/prompt"),name:$t()}),e_=u.extend({ref:bc([Ds,jw]),argument:Fr({name:$t(),value:$t()}),context:Fr({arguments:cc($t(),$t()).optional()}).optional()}),nE=g.extend({method:si("completion/complete"),params:e_}),$_=w.extend({completion:nu({values:Go($t()).max(100),total:xl(Gs().int()),hasMore:xl(kc())})}),Va=Fr({uri:$t().startsWith("file://"),name:$t().optional(),_meta:cc($t(),Dl()).optional()}),lp=g.extend({method:si("roots/list"),params:u.optional()}),Eh=w.extend({roots:Go(Va)}),rE=b.extend({method:si("notifications/roots/list_changed"),params:_.optional()}),cf=nu({ttl:Gs().optional(),pollInterval:Gs().optional()}),t_=Bu(["working","input_required","completed","failed","cancelled"]),q_=Fr({taskId:$t(),status:t_,ttl:bc([Gs(),Bj()]),createdAt:$t(),lastUpdatedAt:$t(),pollInterval:xl(Gs()),statusMessage:xl($t())}),zb=w.extend({task:q_}),Yl=_.merge(q_),dh=b.extend({method:si("notifications/tasks/status"),params:Yl}),X1=g.extend({method:si("tasks/get"),params:u.extend({taskId:$t()})}),nD=w.merge(q_),ox=g.extend({method:si("tasks/result"),params:u.extend({taskId:$t()})}),eZ=w.loose(),Sd=st.extend({method:si("tasks/list")}),Ah=$e.extend({tasks:Go(q_)}),U8=g.extend({method:si("tasks/cancel"),params:u.extend({taskId:$t()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:o,TaskMetadataSchema:s,RelatedTaskMetadataSchema:a,RequestMetaSchema:l,BaseRequestParamsSchema:u,TaskAugmentedRequestParamsSchema:f,RequestSchema:g,NotificationsParamsSchema:_,NotificationSchema:b,ResultSchema:w,RequestIdSchema:T,EmptyResultSchema:I,CancelledNotificationParamsSchema:E,CancelledNotificationSchema:R,IconSchema:L,IconsSchema:U,BaseMetadataSchema:B,ImplementationSchema:z,ClientTasksCapabilitySchema:q,ServerTasksCapabilitySchema:ie,ClientCapabilitiesSchema:ae,InitializeRequestParamsSchema:Ce,InitializeRequestSchema:pe,ServerCapabilitiesSchema:ze,InitializeResultSchema:rt,InitializedNotificationSchema:Pe,PingRequestSchema:Tt,ProgressSchema:Ye,ProgressNotificationParamsSchema:Fe,ProgressNotificationSchema:St,PaginatedRequestParamsSchema:kt,PaginatedRequestSchema:st,PaginatedResultSchema:$e,ResourceContentsSchema:jt,TextResourceContentsSchema:Je,BlobResourceContentsSchema:_t,RoleSchema:Dt,AnnotationsSchema:gn,ResourceSchema:cn,ResourceTemplateSchema:Fn,ListResourcesRequestSchema:on,ListResourcesResultSchema:dt,ListResourceTemplatesRequestSchema:we,ListResourceTemplatesResultSchema:_e,ResourceRequestParamsSchema:Pt,ReadResourceRequestParamsSchema:ut,ReadResourceRequestSchema:Mn,ReadResourceResultSchema:Dr,ResourceListChangedNotificationSchema:gr,SubscribeRequestParamsSchema:eo,SubscribeRequestSchema:to,UnsubscribeRequestParamsSchema:oo,UnsubscribeRequestSchema:ro,ResourceUpdatedNotificationParamsSchema:Ji,ResourceUpdatedNotificationSchema:pi,PromptArgumentSchema:Wi,PromptSchema:Ii,ListPromptsRequestSchema:Rs,ListPromptsResultSchema:ht,GetPromptRequestParamsSchema:mr,GetPromptRequestSchema:mi,TextContentSchema:Ar,ImageContentSchema:hi,AudioContentSchema:Js,ToolUseContentSchema:qa,EmbeddedResourceSchema:li,ResourceLinkSchema:oa,ContentBlockSchema:Fs,PromptMessageSchema:Qo,GetPromptResultSchema:gi,PromptListChangedNotificationSchema:kn,ToolAnnotationsSchema:Nn,ToolExecutionSchema:Ur,ToolSchema:Vo,ListToolsRequestSchema:qe,ListToolsResultSchema:Kt,CallToolResultSchema:Jt,CallToolRequestParamsSchema:en,CallToolRequestSchema:qn,ToolListChangedNotificationSchema:Yr,LoggingLevelSchema:ei,SetLevelRequestParamsSchema:ki,SetLevelRequestSchema:ca,LoggingMessageNotificationParamsSchema:ks,LoggingMessageNotificationSchema:Ud,ModelHintSchema:zd,ModelPreferencesSchema:Bm,ToolChoiceSchema:Xf,ToolResultContentSchema:kf,SamplingContentSchema:qi,SamplingMessageContentBlockSchema:Tm,SamplingMessageSchema:ev,CreateMessageRequestParamsSchema:E0,CreateMessageRequestSchema:tv,CreateMessageResultSchema:z_,CreateMessageResultWithToolsSchema:Yv,BooleanSchemaSchema:Lw,StringSchemaSchema:Tu,NumberSchemaSchema:t0,UntitledSingleSelectEnumSchemaSchema:Ub,TitledSingleSelectEnumSchemaSchema:ta,LegacyTitledEnumSchemaSchema:af,SingleSelectEnumSchemaSchema:lP,UntitledMultiSelectEnumSchemaSchema:tE,TitledMultiSelectEnumSchemaSchema:IS,MultiSelectEnumSchemaSchema:Fw,EnumSchemaSchema:Vs,PrimitiveSchemaDefinitionSchema:Iu,ElicitRequestFormParamsSchema:bs,ElicitRequestURLParamsSchema:A0,ElicitRequestParamsSchema:ri,ElicitRequestSchema:la,ElicitationCompleteNotificationParamsSchema:ul,ElicitationCompleteNotificationSchema:py,ElicitResultSchema:X0,ResourceTemplateReferenceSchema:jw,PromptReferenceSchema:Ds,CompleteRequestParamsSchema:e_,CompleteRequestSchema:nE,CompleteResultSchema:$_,RootSchema:Va,ListRootsRequestSchema:lp,ListRootsResultSchema:Eh,RootsListChangedNotificationSchema:rE,TaskCreationParamsSchema:cf,TaskStatusSchema:t_,TaskSchema:q_,CreateTaskResultSchema:zb,TaskStatusNotificationParamsSchema:Yl,TaskStatusNotificationSchema:dh,GetTaskRequestSchema:X1,GetTaskResultSchema:nD,GetTaskPayloadRequestSchema:ox,GetTaskPayloadResultSchema:eZ,ListTasksRequestSchema:Sd,ListTasksResultSchema:Ah,CancelTaskRequestSchema:U8,CancelTaskResultSchema:w.merge(q_),ClientRequestSchema:bc([Tt,pe,nE,ca,mi,Rs,on,we,Mn,to,ro,qn,qe,X1,ox,Sd,U8]),ClientNotificationSchema:bc([R,St,Pe,rE,dh]),ClientResultSchema:bc([I,z_,Yv,X0,Eh,nD,Ah,zb]),ServerRequestSchema:bc([Tt,tv,la,lp,X1,ox,Sd,U8]),ServerNotificationSchema:bc([R,St,Ud,pi,gr,Yr,kn,dh,py]),ServerResultSchema:bc([I,rt,$_,gi,ht,dt,_e,Dr,Jt,Kt,nD,Ah,zb]),CallToolResultWireSchema:Dl().superRefine((Xv,pse)=>{if(!(typeof Xv!="object"||Xv===null||Array.isArray(Xv)||Xv.content!==void 0)){for(let fse of YYr)if(fse in Xv){pse.addIssue({code:"custom",message:`content is required when the body carries '${fse}' \u2014 another result family cannot default into an empty tools/call success`});return}}}).transform(I$s).pipe(Jt)}}function XYr(){return E$s??=C$s()}function QYr(e){return e.type!=="object"}function LYr(e){return e!==void 0&&!(typeof e=="string"&&e.startsWith("#"))}function R$s(e){let t=typeof e.$schema=="string"?e.$schema:void 0;if(LYr(e.$id))return{...t!==void 0&&{$schema:t},type:"object",properties:{result:e},required:["result"]};let n=kYr(e.$schema)&&e.$recursiveAnchor!==!0,o=r((s,a)=>{if(Array.isArray(s))return s.map(f=>o(f,!1));if(s===null||typeof s!="object"||!a&&LYr(s.$id))return s;let l={},u=!1;for(let[f,g]of Object.entries(s))a?l[f]=o(g,!1):(f==="$ref"||f==="$dynamicRef")&&typeof g=="string"?l[f]=g==="#"?"#/properties/result":g.startsWith("#/")?`#/properties/result${g.slice(1)}`:g:f==="$recursiveRef"&&g==="#"&&n?u=!0:A$s.has(f)?l[f]=g:P$s.has(f)?l[f]=o(g,!0):l[f]=o(g,!1);return u&&("$ref"in l?l.allOf=[...Array.isArray(l.allOf)?l.allOf:[],{$ref:"#/properties/result"}]:l.$ref="#/properties/result"),l},"rewriteRefs");return{...t!==void 0&&{$schema:t},type:"object",properties:{result:o(e,!1)},required:["result"]}}function Xpn(){if(but)return but;let e=XYr();return but={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},but}function nXr(e){return Object.prototype.hasOwnProperty.call(eXr,e)}function rXr(e){return Object.prototype.hasOwnProperty.call(tXr,e)}function O$s(e){return Object.prototype.hasOwnProperty.call(D$s,e)}function M$s(e){return O$s(e)?Xpn().resultSchemas[e]:void 0}function N$s(e){return nXr(e)?Xpn().requestSchemas[e]:void 0}function L$s(e){return rXr(e)?Xpn().notificationSchemas[e]:void 0}function Hpn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Sut(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:"invalid",message:String(n.error)}}function jYr(e){return Hpn(e)&&Hpn(e.outputSchema)&&QYr(e.outputSchema)}function F$s(){let e=mV(()=>bc([$t(),Gs(),kc(),Bj(),cc($t(),e),Go(e)])),t=cc($t(),e),n=bc([$t(),Gs().int()]),o=$t(),s=bc([$t(),Gs().int()]),a=Bu(["user","assistant"]),l=Bu(["debug","info","notice","warning","error","critical","alert","emergency"]),u=$t().refine(Ah=>{try{return atob(Ah),!0}catch{return!1}},{message:"Invalid Base64 string"}),f=Fr({ttl:Gs().optional()}),g=Fr({taskId:$t()}),_=nu({progressToken:n.optional(),"io.modelcontextprotocol/related-task":g.optional()}),b=Fr({_meta:_.optional()}),w=b.extend({task:f.optional()}),T=Fr({_meta:_.optional()}),I=Fr({method:$t(),params:T.loose().optional()}),E=Fr({src:$t(),mimeType:$t().optional(),sizes:Go($t()).optional(),theme:Bu(["light","dark"]).optional()}),R=Fr({icons:Go(E).optional()}),L=Fr({name:$t(),title:$t().optional()}),U=L.extend({...L.shape,...R.shape,version:$t(),websiteUrl:$t().optional(),description:$t().optional()}),B=$L(Fr({applyDefaults:kc().optional()}),t),z=hz(Ah=>Ah&&typeof Ah=="object"&&!Array.isArray(Ah)&&Object.keys(Ah).length===0?{form:{}}:Ah,$L(Fr({form:B.optional(),url:t.optional()}),t.optional())),$=nu({list:t.optional(),cancel:t.optional(),requests:nu({sampling:nu({createMessage:t.optional()}).optional(),elicitation:nu({create:t.optional()}).optional()}).optional()}),J=nu({list:t.optional(),cancel:t.optional(),requests:nu({tools:nu({call:t.optional()}).optional()}).optional()}),q=Fr({experimental:cc($t(),t).optional(),sampling:Fr({context:t.optional(),tools:t.optional()}).optional(),elicitation:z.optional(),roots:Fr({listChanged:kc().optional()}).optional(),tasks:$.optional(),extensions:cc($t(),t).optional()}),ie=Fr({experimental:cc($t(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:Fr({listChanged:kc().optional()}).optional(),resources:Fr({subscribe:kc().optional(),listChanged:kc().optional()}).optional(),tools:Fr({listChanged:kc().optional()}).optional(),tasks:J.optional(),extensions:cc($t(),t).optional()}),ae=Fr({progress:Gs(),total:xl(Gs()),message:xl($t())}),Ce=Fr({...T.shape,...ae.shape,progressToken:n}),pe=I.extend({method:si("notifications/progress"),params:Ce}),ze=T.extend({level:l,logger:$t().optional(),data:Dl()}),rt=I.extend({method:si("notifications/message"),params:ze}),Pe=Fr({uri:$t(),mimeType:xl($t()),_meta:cc($t(),Dl()).optional()}),Tt=Pe.extend({text:$t()}),Ye=Pe.extend({blob:u}),Fe=Fr({audience:Go(a).optional(),priority:Gs().min(0).max(1).optional(),lastModified:jO.datetime({offset:!0}).optional()}),St=Fr({...L.shape,...R.shape,uri:$t(),description:xl($t()),mimeType:xl($t()),size:xl(Gs()),annotations:Fe.optional(),_meta:xl(nu({}))}),kt=Fr({...L.shape,...R.shape,uriTemplate:$t(),description:xl($t()),mimeType:xl($t()),annotations:Fe.optional(),_meta:xl(nu({}))}),st=I.extend({method:si("notifications/resources/list_changed"),params:T.optional()}),$e=T.extend({uri:$t()}),jt=I.extend({method:si("notifications/resources/updated"),params:$e}),Je=Fr({name:$t(),description:xl($t()),required:xl(kc())}),Xe=Fr({...L.shape,...R.shape,description:xl($t()),arguments:xl(Go(Je)),_meta:xl(nu({}))}),_t=I.extend({method:si("notifications/prompts/list_changed"),params:T.optional()}),Dt=Fr({type:si("text"),text:$t(),annotations:Fe.optional(),_meta:cc($t(),Dl()).optional()}),gn=Fr({type:si("image"),data:u,mimeType:$t(),annotations:Fe.optional(),_meta:cc($t(),Dl()).optional()}),cn=Fr({type:si("audio"),data:u,mimeType:$t(),annotations:Fe.optional(),_meta:cc($t(),Dl()).optional()}),Fn=Fr({type:si("tool_use"),name:$t(),id:$t(),input:cc($t(),Dl()),_meta:cc($t(),Dl()).optional()}),on=Fr({type:si("resource"),resource:bc([Tt,Ye]),annotations:Fe.optional(),_meta:cc($t(),Dl()).optional()}),dt=St.extend({type:si("resource_link")}),we=bc([Dt,gn,cn,dt,on]),_e=Fr({role:a,content:we}),Pt=Fr({title:$t().optional(),readOnlyHint:kc().optional(),destructiveHint:kc().optional(),idempotentHint:kc().optional(),openWorldHint:kc().optional()}),ut=I.extend({method:si("notifications/tools/list_changed"),params:T.optional()}),Mn=Fr({name:$t().optional()}),Dr=Fr({hints:Go(Mn).optional(),costPriority:Gs().min(0).max(1).optional(),speedPriority:Gs().min(0).max(1).optional(),intelligencePriority:Gs().min(0).max(1).optional()}),gr=Fr({mode:Bu(["auto","required","none"]).optional()}),eo=Fr({type:si("boolean"),title:$t().optional(),description:$t().optional(),default:kc().optional()}),to=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),minLength:Gs().optional(),maxLength:Gs().optional(),format:Bu(["email","uri","date","date-time"]).optional(),default:$t().optional()}),oo=Fr({type:Bu(["number","integer"]),title:$t().optional(),description:$t().optional(),minimum:Gs().optional(),maximum:Gs().optional(),default:Gs().optional()}),ro=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),enum:Go($t()),default:$t().optional()}),Ji=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),oneOf:Go(Fr({const:$t(),title:$t()})),default:$t().optional()}),pi=Fr({type:si("string"),title:$t().optional(),description:$t().optional(),enum:Go($t()),enumNames:Go($t()).optional(),default:$t().optional()}),Wi=bc([ro,Ji]),Ii=Fr({type:si("array"),title:$t().optional(),description:$t().optional(),minItems:Gs().optional(),maxItems:Gs().optional(),items:Fr({type:si("string"),enum:Go($t())}),default:Go($t()).optional()}),Rs=Fr({type:si("array"),title:$t().optional(),description:$t().optional(),minItems:Gs().optional(),maxItems:Gs().optional(),items:Fr({anyOf:Go(Fr({const:$t(),title:$t()}))}),default:Go($t()).optional()}),ht=bc([Ii,Rs]),mr=bc([pi,Wi,ht]),mi=bc([mr,eo,to,oo]),Ar=w.extend({mode:si("form").optional(),message:$t(),requestedSchema:Fr({type:si("object"),properties:cc($t(),mi),required:Go($t()).optional()}).catchall(Dl())}),hi=Fr({type:si("ref/resource"),uri:$t()}),Js=Fr({type:si("ref/prompt"),name:$t()}),qa=Fr({uri:$t().startsWith("file://"),name:$t().optional(),_meta:cc($t(),Dl()).optional()}),li=q.shape,oa=Fr({experimental:li.experimental,sampling:li.sampling,elicitation:li.elicitation,roots:li.roots,extensions:li.extensions}),Fs=ie.shape,Qo=Fr({experimental:Fs.experimental,logging:Fs.logging,completions:Fs.completions,prompts:Fs.prompts,resources:Fs.resources,tools:Fs.tools,extensions:Fs.extensions}),gi=nu({progressToken:n.optional(),[n$]:$t(),[lge]:U.optional(),[Rre]:oa,[uge]:l.optional()}),kn=Fr({...L.shape,...R.shape,description:$t().optional(),inputSchema:nu({$schema:$t().optional(),type:si("object")}),outputSchema:nu({$schema:$t().optional()}).optional(),annotations:Pt.optional(),_meta:cc($t(),Dl()).optional()}),Nn=Fr({type:si("tool_result"),toolUseId:$t(),content:Go(we),structuredContent:Dl().optional(),isError:kc().optional(),_meta:cc($t(),Dl()).optional()}),Ur=bc([Dt,gn,cn,Fn,Nn]),Vo=Fr({role:a,content:bc([Ur,Go(Ur)]),_meta:cc($t(),Dl()).optional()}),qe=$t(),Kt=nu({[r$]:U.optional().catch(void 0)}),Jt=Kt.optional();function en(Ah){return nu({_meta:Jt,resultType:qe.default("complete"),...Ah})}r(en,"wireResult");let qn=en({}),Yr=en({nextCursor:o.optional()}),ei=en({content:Go(we),structuredContent:Dl().optional(),isError:kc().optional()}),ki=en({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),tools:Go(kn),nextCursor:o.optional()}),ca=en({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),prompts:Go(Xe),nextCursor:o.optional()}),ks=en({description:$t().optional(),messages:Go(_e)}),Ud=en({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),resources:Go(St),nextCursor:o.optional()}),zd=en({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),resourceTemplates:Go(kt),nextCursor:o.optional()}),Bm=en({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),contents:Go(bc([Tt,Ye]))}),Xf=en({completion:Fr({values:Go($t()).max(100),total:Gs().int().optional(),hasMore:kc().optional()}).loose()}),kf=en({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"])}),qi=en({ttlMs:Gs().int().min(0).catch(0),cacheScope:Bu(["public","private"]).catch("private"),supportedVersions:Go($t()),capabilities:Qo,instructions:$t().optional()}),Tm=Fr({messages:Go(Vo),modelPreferences:Dr.optional(),systemPrompt:$t().optional(),includeContext:Bu(["none","thisServer","allServers"]).optional(),temperature:Gs().optional(),maxTokens:Gs().int(),stopSequences:Go($t()).optional(),metadata:t.optional(),tools:Go(kn).optional(),toolChoice:gr.optional()}),ev=Fr({method:si("sampling/createMessage"),params:Tm}),E0=Fr({method:si("roots/list"),params:Fr({_meta:cc($t(),Dl()).optional()}).optional()}),tv=Fr({...Vo.shape,model:$t(),stopReason:$t().optional()}),z_=Fr({roots:Go(qa)}),Yv=Fr({action:Bu(["accept","decline","cancel"]),content:cc($t(),bc([$t(),Gs(),kc(),Go($t())])).optional()}),Lw=Fr({mode:si("url"),message:$t(),url:$t().url()}),Tu=bc([Ar,Lw]),t0=Fr({method:si("elicitation/create"),params:Tu}),Ub=bc([ev,E0,t0]),ta=bc([tv,z_,Yv]),af=cc($t(),Ub),lP=cc($t(),ta),tE=en({inputRequests:af.optional(),requestState:$t().optional()}),IS={inputResponses:lP.optional(),requestState:$t().optional()},Fw=Fr({_meta:gi,...IS}),Vs=nu({progressToken:n.optional()});function Iu(Ah,U8){return Fr({method:si(Ah),params:Fr({_meta:gi,...U8})})}r(Iu,"wireRequest");function bs(Ah,U8){return Fr({method:si(Ah),params:Fr({_meta:Vs.optional(),...U8}).optional()})}r(bs,"dispatchRequest");let A0={name:$t(),arguments:cc($t(),Dl()).optional(),...IS},ri={cursor:o.optional()},la=Iu("tools/call",A0),ul=Iu("tools/list",ri),py=Iu("prompts/list",ri),X0=Iu("prompts/get",{name:$t(),arguments:cc($t(),$t()).optional(),...IS}),jw=Iu("resources/list",ri),Ds=Iu("resources/templates/list",ri),e_=Iu("resources/read",{uri:$t(),...IS}),nE={ref:bc([Js,hi]),argument:Fr({name:$t(),value:$t()}),context:Fr({arguments:cc($t(),$t()).optional()}).optional()},$_=Iu("completion/complete",nE),Va=Iu("server/discover",{}),lp=Fr({toolsListChanged:kc().optional(),promptsListChanged:kc().optional(),resourcesListChanged:kc().optional(),resourceSubscriptions:Go($t()).optional()}),Eh={notifications:lp},rE=Iu("subscriptions/listen",Eh),cf=Kt.extend({"io.modelcontextprotocol/subscriptionId":s}),t_=nu({_meta:cf,resultType:qe.default("complete")}),q_={"tools/call":bs("tools/call",A0),"tools/list":bs("tools/list",ri),"prompts/get":bs("prompts/get",{name:$t(),arguments:cc($t(),$t()).optional()}),"prompts/list":bs("prompts/list",ri),"resources/list":bs("resources/list",ri),"resources/templates/list":bs("resources/templates/list",ri),"resources/read":bs("resources/read",{uri:$t()}),"completion/complete":bs("completion/complete",nE),"server/discover":bs("server/discover",{}),"subscriptions/listen":bs("subscriptions/listen",Eh)};function zb(Ah){return nu({_meta:Jt,...Ah})}r(zb,"liftedResult");let Yl={"tools/call":zb({content:Go(we),structuredContent:Dl().optional(),isError:kc().optional()}),"tools/list":zb({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),tools:Go(kn),nextCursor:o.optional()}),"prompts/get":zb({description:$t().optional(),messages:Go(_e)}),"prompts/list":zb({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),prompts:Go(Xe),nextCursor:o.optional()}),"resources/list":zb({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),resources:Go(St),nextCursor:o.optional()}),"resources/templates/list":zb({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),resourceTemplates:Go(kt),nextCursor:o.optional()}),"resources/read":zb({ttlMs:Gs().int().min(0),cacheScope:Bu(["public","private"]),contents:Go(bc([Tt,Ye]))}),"completion/complete":zb({completion:Fr({values:Go($t()).max(100),total:Gs().int().optional(),hasMore:kc().optional()}).loose()}),"server/discover":zb({ttlMs:Gs().int().min(0).catch(0),cacheScope:Bu(["public","private"]).catch("private"),supportedVersions:Go($t()),capabilities:Qo,instructions:$t().optional()}),"subscriptions/listen":zb({})},dh=nu({"io.modelcontextprotocol/subscriptionId":s.optional()}),X1=Fr({method:si("notifications/subscriptions/acknowledged"),params:Fr({_meta:dh.optional(),notifications:lp})}),nD=Fr({_meta:dh.optional(),requestId:s,reason:$t().optional()}),ox=Fr({method:si("notifications/cancelled"),params:nD}),eZ={"notifications/cancelled":ox,"notifications/progress":pe,"notifications/message":rt,"notifications/resources/updated":jt,"notifications/resources/list_changed":st,"notifications/tools/list_changed":ut,"notifications/prompts/list_changed":_t,"notifications/subscriptions/acknowledged":X1},Sd=r(Ah=>Fr({jsonrpc:si("2.0"),id:bc([$t(),Gs().int()]),result:Ah}).strict(),"wireResultResponse");return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:o,RequestIdSchema:s,RoleSchema:a,LoggingLevelSchema:l,TaskMetadataSchema:f,RelatedTaskMetadataSchema:g,RequestMetaSchema:_,BaseRequestParamsSchema:b,TaskAugmentedRequestParamsSchema:w,NotificationsParamsSchema:T,NotificationSchema:I,IconSchema:E,IconsSchema:R,BaseMetadataSchema:L,ImplementationSchema:U,ClientTasksCapabilitySchema:$,ServerTasksCapabilitySchema:J,ClientCapabilitiesSchema:q,ServerCapabilitiesSchema:ie,ProgressSchema:ae,ProgressNotificationParamsSchema:Ce,ProgressNotificationSchema:pe,LoggingMessageNotificationParamsSchema:ze,LoggingMessageNotificationSchema:rt,ResourceContentsSchema:Pe,TextResourceContentsSchema:Tt,BlobResourceContentsSchema:Ye,AnnotationsSchema:Fe,ResourceSchema:St,ResourceTemplateSchema:kt,ResourceListChangedNotificationSchema:st,ResourceUpdatedNotificationParamsSchema:$e,ResourceUpdatedNotificationSchema:jt,PromptArgumentSchema:Je,PromptSchema:Xe,PromptListChangedNotificationSchema:_t,TextContentSchema:Dt,ImageContentSchema:gn,AudioContentSchema:cn,ToolUseContentSchema:Fn,EmbeddedResourceSchema:on,ResourceLinkSchema:dt,ContentBlockSchema:we,PromptMessageSchema:_e,ToolAnnotationsSchema:Pt,ToolListChangedNotificationSchema:ut,ModelHintSchema:Mn,ModelPreferencesSchema:Dr,ToolChoiceSchema:gr,BooleanSchemaSchema:eo,StringSchemaSchema:to,NumberSchemaSchema:oo,UntitledSingleSelectEnumSchemaSchema:ro,TitledSingleSelectEnumSchemaSchema:Ji,LegacyTitledEnumSchemaSchema:pi,SingleSelectEnumSchemaSchema:Wi,UntitledMultiSelectEnumSchemaSchema:Ii,TitledMultiSelectEnumSchemaSchema:Rs,MultiSelectEnumSchemaSchema:ht,EnumSchemaSchema:mr,PrimitiveSchemaDefinitionSchema:mi,ElicitRequestFormParamsSchema:Ar,ResourceTemplateReferenceSchema:hi,PromptReferenceSchema:Js,RootSchema:qa,ClientCapabilities2026Schema:oa,ServerCapabilities2026Schema:Qo,RequestMetaEnvelopeSchema:gi,ToolSchema:kn,ToolResultContentSchema:Nn,SamplingMessageContentBlockSchema:Ur,SamplingMessageSchema:Vo,ResultTypeSchema:qe,ResultMetaSchema:Kt,ResultSchema:qn,PaginatedResultSchema:Yr,CallToolResultSchema:ei,ListToolsResultSchema:ki,ListPromptsResultSchema:ca,GetPromptResultSchema:ks,ListResourcesResultSchema:Ud,ListResourceTemplatesResultSchema:zd,ReadResourceResultSchema:Bm,CompleteResultSchema:Xf,CacheableResultSchema:kf,DiscoverResultSchema:qi,CreateMessageRequestParamsSchema:Tm,CreateMessageRequestSchema:ev,ListRootsRequestSchema:E0,CreateMessageResultSchema:tv,ListRootsResultSchema:z_,ElicitResultSchema:Yv,ElicitRequestURLParamsSchema:Lw,ElicitRequestParamsSchema:Tu,ElicitRequestSchema:t0,InputRequestSchema:Ub,InputResponseSchema:ta,InputRequestsSchema:af,InputResponsesSchema:lP,InputRequiredResultSchema:tE,InputResponseRequestParamsSchema:Fw,CallToolRequestSchema:la,ListToolsRequestSchema:ul,ListPromptsRequestSchema:py,GetPromptRequestSchema:X0,ListResourcesRequestSchema:jw,ListResourceTemplatesRequestSchema:Ds,ReadResourceRequestSchema:e_,CompleteRequestSchema:$_,DiscoverRequestSchema:Va,SubscriptionFilterSchema:lp,SubscriptionsListenRequestSchema:rE,SubscriptionsListenResultMetaSchema:cf,SubscriptionsListenResultSchema:t_,dispatchRequestSchemas:q_,dispatchResultSchemas:Yl,NotificationMetaSchema:dh,SubscriptionsAcknowledgedNotificationSchema:X1,CancelledNotificationParamsSchema:nD,CancelledNotificationSchema:ox,notificationSchemas2026:eZ,JSONRPCResultResponseSchema:Sd(qn),CallToolResultResponseSchema:Sd(bc([ei,tE])),ListToolsResultResponseSchema:Sd(ki),ListPromptsResultResponseSchema:Sd(ca),GetPromptResultResponseSchema:Sd(bc([ks,tE])),ListResourcesResultResponseSchema:Sd(Ud),ListResourceTemplatesResultResponseSchema:Sd(zd),ReadResourceResultResponseSchema:Sd(bc([Bm,tE])),CompleteResultResponseSchema:Sd(Xf),DiscoverResultResponseSchema:Sd(qi)}}function Nre(){return j$s??=F$s()}function U$s(e){return B$s.includes(e)}function z$s(e){return e[efn]}function oXr(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function iXr(e){return e==="public"||e==="private"}function V$s(e,t){let n=t.resultType;if(n===void 0)return{...t,resultType:"complete"};if(n==="complete"||W$s.includes(e))return t;throw new oh(Du.InternalError,`Handler for ${e} returned resultType '${String(n)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function H$s(e,t){let n=z$s(t);if(t.resultType!=="complete"||!U$s(e))return n===void 0?t:Y$s(t);let o=t,s=oXr(o.ttlMs)?o.ttlMs:K$s(n),a=iXr(o.cacheScope)?o.cacheScope:Z$s(n),l={...o,ttlMs:s,cacheScope:a};return delete l[efn],l}function G$s(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function J$s(e,t){if(t===void 0)return e;let n=e._meta;return n===void 0?{...e,_meta:{[r$]:t}}:!G$s(n)||n[r$]!==void 0?e:{...e,_meta:{...n,[r$]:t}}}function K$s(e){return e!==void 0&&oXr(e.ttlMs)?e.ttlMs:$$s}function Z$s(e){return e!==void 0&&iXr(e.cacheScope)?e.cacheScope:q$s}function Y$s(e){let t={...e};return delete t[efn],t}function uXr(){if(wut)return wut;let e=Nre();return wut={request:{"elicitation/create":Fr({method:si("elicitation/create"),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":Fr({method:si("sampling/createMessage"),params:e.CreateMessageRequestParamsSchema}),"roots/list":Fr({method:si("roots/list"),params:nu({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},wut}function dXr(e){return X$s.includes(e)}function zpn(e){return dXr(e)?uXr().request[e]:void 0}function Q$s(e){return dXr(e)?uXr().response[e]:void 0}function fXr(e){return Object.prototype.hasOwnProperty.call(tfn,e)}function mXr(e){return Object.prototype.hasOwnProperty.call(pXr,e)}function e9s(e){return Object.prototype.hasOwnProperty.call(tfn,e)}function t9s(e){return fXr(e)?Nre().dispatchRequestSchemas[e]:void 0}function n9s(e){return e9s(e)?Nre().dispatchResultSchemas[e]:void 0}function r9s(e){return mXr(e)?Nre().notificationSchemas2026[e]:void 0}function jMe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function LMe(e,t){if(e===void 0)return{ok:!1,reason:"not-in-era"};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:"invalid",message:String(n.error)}}function s9s(e,t){let n=t,o=!1,s=r(()=>(o||(n={...n},o=!0),n),"copy"),a=t.tools;e==="tools/list"&&Array.isArray(a)&&a.some(u=>jMe(u)&&"execution"in u)&&(s().tools=a.map(u=>{if(!jMe(u)||!("execution"in u))return u;let f={...u};return delete f.execution,f}));let l=t.capabilities;if(jMe(l)&&"tasks"in l){let u={...l};delete u.tasks,s().capabilities=u}return n}function a9s(){if(kut)return kut;let e=Nre();return kut={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},kut}function i$(e){return e!==void 0&&a$(e)?nfn:Qpn}function BYr(e){return e.revision!==void 0?i$(e.revision).era:e.era==="modern"?nfn.era:Qpn.era}function $pn(e){return hXr.some(t=>t.hasRequestMethod(e))}function qpn(e){return hXr.some(t=>t.hasNotificationMethod(e))}function ofn(e){let t=[],n=new Map,o=r((a,l,u)=>{if(a===null||typeof a!="object")return;let f=a;if(UYr in f){if(!u||l.length===0)return`${xut(l)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let _=f[UYr];if(typeof _!="string"||_.length===0)return`${xut(l)}: x-mcp-header MUST be a non-empty string`;if(!u9s.test(_))return`${xut(l)}: x-mcp-header '${_}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let b=typeof f.type=="string"?f.type:void 0;if(b===void 0||!d9s.has(b))return`${xut(l)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${b??"<none>"}`;let w=_.toLowerCase(),T=n.get(w);if(T!==void 0)return`x-mcp-header '${_}' is not case-insensitively unique (also declared as '${T}')`;n.set(w,_),t.push({path:l,headerName:_,type:b})}let g=f.properties;if(g!==null&&typeof g=="object")for(let[_,b]of Object.entries(g)){let w=o(b,[...l,_],u);if(w!==void 0)return w}for(let _ of p9s){let b=f[_];if(b===void 0)continue;let w=Array.isArray(b)?b:b!==null&&typeof b=="object"&&f9s.has(_)?Object.values(b):[b];for(let T of w){let I=o(T,[...l,`<${_}>`],!1);if(I!==void 0)return I}}},"visit"),s=o(e,[],!0);return s===void 0?{valid:!0,declarations:t}:{valid:!1,reason:s}}function xut(e){return e.length===0?"<root>":e.join(".")}function m9s(e){if(typeof e=="string")return e;if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e)?void 0:String(e)}function h9s(e){if(e.length===0||e.startsWith(vXr)&&e.endsWith(bXr)||e!==e.trim())return!0;for(let t=0;t<e.length;t++){let n=e.codePointAt(t);if(!(n===9||n>=32&&n<=126))return!0}return!1}function g9s(e){let t=new TextEncoder().encode(e),n="";for(let o of t)n+=String.fromCodePoint(o);return btoa(n)}function ifn(e){return h9s(e)?`${vXr}${g9s(e)}${bXr}`:e}function _9s(e,t){let n=e;for(let o of t){if(n===null||typeof n!="object")return;n=n[o]}return n}function SXr(e,t){let n={};for(let o of e){let s=_9s(t,o.path);if(s==null)continue;let a=m9s(s);a!==void 0&&(n[`${l9s}${o.headerName}`]=ifn(a))}return n}function Cut(e,t){return REe(e,t)}function FMe(e){return new Set(e.flatMap(t=>Object.keys(t.shape)))}function Gpn(e){if(e==null)return!1;let t=typeof e;return t!=="object"&&t!=="function"||!("~standard"in e)?!1:typeof e["~standard"]?.validate=="function"}function y9s(e,t="input"){let n=e["~standard"],o;if(n.jsonSchema)o=n.jsonSchema[t]({target:Jpn});else if(n.vendor==="zod"){if(!("_zod"in e))throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().");zYr||(zYr=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),o=zL(e,{target:Jpn,io:t})}else throw new Error(`Schema library "${n.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t==="output")return o.type!==void 0?o:wXr(o)?{type:"object",...o}:o;if(o.type!==void 0&&o.type!=="object")throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(o.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:"object",...o}}function wXr(e){if("properties"in e||"patternProperties"in e||"additionalProperties"in e||"required"in e)return!0;for(let t of["oneOf","anyOf","allOf"]){let n=e[t];if(Array.isArray(n)&&n.length>0)return n.every(o=>o!==null&&typeof o=="object"&&(o.type==="object"||wXr(o)))}return!1}function v9s(e){return e.path?.length?`${e.path.map(t=>String(typeof t=="object"?t.key:t)).join(".")}: ${e.message}`:e.message}async function Wpn(e,t){let n=await e["~standard"].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(o=>v9s(o)).join(", ")}:{success:!0,data:n.value}}function b9s(e){let t=zL(e,{target:Jpn,io:"input"});return typeof t.pattern=="string"?t.pattern:void 0}function w9s(e){let t=S9s.exec(e),n=[void 0,-1,0];return t&&n.push(Number(t[1])),[!1,!0].flatMap(o=>[!1,!0].flatMap(s=>n.map(a=>jO.datetime({local:o,offset:s,precision:a}))))}function k9s(e,t){let n;switch(e){case"email":n=[$Je()];break;case"uri":n=[ape()];break;case"date":n=[jO.date()];break;case"date-time":n=w9s(t);break}return new Set(n.map(o=>b9s(o)).filter(o=>o!==void 0))}function x9s(e,t,n){return n!=="zod"?!0:k9s(e,t).has(t)}function UMe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function T9s(e){try{return y9s(e,"input")}catch(t){let n=t instanceof Error?t.message:String(t);throw new oh(Du.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${n}`)}}function sfn(e){return I9s.has(e)||e.startsWith("x-")}function A9s(e,t,n,o){if(!UMe(e))return e;let s=typeof e.type=="string"&&Object.hasOwn($Yr,e.type)?$Yr[e.type]:void 0;if(s===void 0)return e;let a={};for(let[l,u]of Object.entries(e))s.has(l)||sfn(l)?a[l]=u:l==="pattern"&&e.type==="string"&&typeof e.format=="string"?E9s.has(e.format)?(typeof u!="string"||!x9s(e.format,u,n))&&o.push(`${t}.${l}`):a[l]=u:o.push(`${t}.${l}`);return a}function P9s(e,t){let n={},o=[];for(let[s,a]of Object.entries(e))s==="properties"&&UMe(a)?n[s]=Object.fromEntries(Object.entries(a).map(([l,u])=>[l,A9s(u,`properties.${l}`,t,o)])):C9s.has(s)?n[s]=a:sfn(s)||o.push(s);if(o.length>0)throw new oh(Du.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${o.join(", ")}`);return n}function R9s(e,t){if(!UMe(e.properties))return t;let n=Object.entries(e.properties).filter(([,o])=>!Cut(PMe,o).success).map(([o])=>`properties.${o}`);return n.length>0?n.join(", "):t}function Kpn(e,t,n=""){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((o,s)=>Kpn(o,t[s],`${n}[${s}]`)):!UMe(e)||!UMe(t)?[]:Object.entries(e).flatMap(([o,s])=>{let a=n?`${n}.${o}`:o;return Object.prototype.hasOwnProperty.call(t,o)?Kpn(s,t[o],a):sfn(o)?[]:[a]})}function D9s(e){if(!Gpn(e.requestedSchema))return{...e,mode:"form",requestedSchema:e.requestedSchema};let t=e.requestedSchema["~standard"].vendor,n=P9s(T9s(e.requestedSchema),t),o=Cut(Sge.shape.requestedSchema,n);if(!o.success)throw new oh(Du.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${R9s(n,o.error.message)}`);let s=Kpn(n,o.data);if(s.length>0)throw new oh(Du.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${s.join(", ")}`);let a=(o.data.required??[]).filter(l=>!Object.prototype.hasOwnProperty.call(o.data.properties,l));if(a.length>0)throw new oh(Du.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${a.join(", ")}`);return{...e,mode:"form",requestedSchema:o.data}}function O9s(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,n=typeof e.requestState=="string";if(!t&&!n)throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)");return{resultType:"input_required",...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}function kXr(e){return{autoFulfill:e?.autoFulfill??M9s,maxRounds:e?.maxRounds??N9s}}function F9s(e,t,n){let o=t!==void 0&&Object.keys(t).length>0;return!o&&n===void 0?e:{...e,...o&&{inputResponses:t},...n!==void 0&&{requestState:n}}}function j9s(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function B9s(e,t){return new Promise((n,o)=>{if(t?.aborted){o(t.reason instanceof rl?t.reason:new rl(Pc.RequestTimeout,String(t.reason)));return}let s=setTimeout(()=>{t?.removeEventListener("abort",a),n()},e),a=r(()=>{clearTimeout(s),o(t?.reason instanceof rl?t.reason:new rl(Pc.RequestTimeout,String(t?.reason)))},"onAbort");t?.addEventListener("abort",a,{once:!0})})}function U9s(e){let t=new AbortController,n=r(()=>t.abort(e?.reason),"onOuterAbort");return e?.addEventListener("abort",n,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:r(o=>t.abort(o),"abort"),dispose:r(()=>e?.removeEventListener("abort",n),"dispose")}}async function z9s(e){let{config:t,method:n,originalParams:o,requestOptions:s,hooks:a,signal:l}=e,u=e.flowStartedAt??Date.now(),f=e.firstPayload,g=0;for(;;){if(g+=1,g>t.maxRounds)throw new rl(Pc.InputRequiredRoundsExceeded,j9s(n,t.maxRounds),{rounds:t.maxRounds,lastResult:{inputRequests:f.inputRequests,...f.requestState!==void 0&&{requestState:f.requestState}}});s.onprogress?.({progress:g,message:`Fulfilling input required by '${n}' (round ${g})`});let _=Object.entries(f.inputRequests??{}),b;if(_.length>0){let I=U9s(l);try{let E=await Promise.all(_.map(async([R,L])=>{try{return[R,await a.dispatchInputRequest(R,L,I.signal)]}catch(U){throw I.abort(U),U}}));b=Object.fromEntries(E)}finally{I.dispose()}}else await B9s(L9s,l);let w={...s.timeout!==void 0&&{timeout:s.timeout}};if(s.maxTotalTimeout!==void 0){let I=Date.now()-u,E=s.maxTotalTimeout-I;if(E<=0)throw new rl(Pc.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:s.maxTotalTimeout,totalElapsed:I});w.maxTotalTimeout=E}let T=await a.retry(F9s(o,b,f.requestState),w);if(_Xr(T)){f={inputRequests:T.inputRequests??{},...T.requestState!==void 0&&{requestState:T.requestState}};continue}return T}}function IXr(e,t){let n=e.slice(0,-6);xXr[n]=t,TXr[n]=o=>t.safeParse(o).success}function V9s(e){switch(e){case"initialize":case"notifications/initialized":return i$(void 0);case"server/discover":return i$(Iut);default:return}}function qYr(e,t){let n=e.params;if(!BMe(n))return{message:e,lifted:{}};let o=n._meta,s=BMe(o)?H9s.filter(f=>f in o):[],a=t==="request"?G9s.filter(f=>f in n):[];if(s.length===0&&a.length===0)return{message:e,lifted:{}};let l={},u={...n};if(s.length>0&&BMe(o)){let f={},g={...o};for(let _ of s)f[_]=o[_],delete g[_];l.envelope=f,Object.keys(g).length>0?u._meta=g:delete u._meta}for(let f of a)f==="inputResponses"&&(l.inputResponses=u[f]),f==="requestState"&&(l.requestState=u[f]),delete u[f];return{message:{...e,params:u},lifted:l}}function WYr(e,t){let n=e.validateResult(t,void 0);if(!(!n.ok&&n.reason==="not-in-era"))return{"~standard":{version:1,vendor:"mcp-wire-codec",validate(o){let s=e.validateResult(t,o);return s.ok?{value:s.value}:{issues:[{message:s.reason==="invalid"?s.message:`not-in-era: ${t}`}]}}}}}function afn(e){return()=>e}function BMe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function AXr(e,t){let n={...e};for(let o in t){let s=o,a=t[s];if(a===void 0)continue;let l=n[s];n[s]=BMe(l)&&BMe(a)?{...l,...a}:a}return n}function Tut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Z9s(e){let t={},n=[];if(!Tut(e))return{accepted:t,droppedKeys:n};for(let[o,s]of Object.entries(e)){if(!Tut(s)||"method"in s||"result"in s){n.push(o);continue}t[o]=s}return{accepted:t,droppedKeys:n}}function VYr(e){throw new rl(Pc.SendFailed,`ctx.mcpReq.${e} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`)}function Y9s(e,t,n,o,s){return{sessionId:s,mcpReq:{id:e,method:t,_meta:n?._meta,requestState:afn(void 0),signal:o,send:r((()=>VYr("send")),"send"),notify:r(()=>VYr("notify"),"notify")}}}async function X9s(e,t,n,o,s){if(!Tut(o)||typeof o.method!="string")throw new rl(Pc.InvalidResult,`Invalid input request '${n}': each inputRequests entry must be an embedded request object with a method`,{key:n});let a=o.method;if(!t.hasInputRequestMethod(a))throw new rl(Pc.InvalidResult,`Invalid input request '${n}': '${a}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:n,method:a});let l=e.getRequestHandler(a);if(l===void 0)throw new rl(Pc.CapabilityNotSupported,`Cannot fulfil input request '${n}': no handler is registered for '${a}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:n,method:a});let u=Tut(o.params)?o.params:void 0;return await l({jsonrpc:"2.0",id:n,method:a,...u!==void 0&&{params:u}},e.buildContext(Y9s(n,a,u,s,e.sessionId)))}function Q9s(e,t){return{...e?.signal!==void 0&&{signal:e.signal},...e?.onprogress!==void 0&&{onprogress:e.onprogress},...e?.resetTimeoutOnProgress!==void 0&&{resetTimeoutOnProgress:e.resetTimeoutOnProgress},...e?.headers!==void 0&&{headers:e.headers},...t.timeout!==void 0&&{timeout:t.timeout},...t.maxTotalTimeout!==void 0&&{maxTotalTimeout:t.maxTotalTimeout},allowInputRequired:!0}}function PXr(e,t,n,o){let{codec:s,request:a,options:l,flowStartedAt:u}=o,f={inputRequests:n.inputRequests,...n.requestState!==void 0&&{requestState:n.requestState}},g={dispatchInputRequest:r((_,b,w)=>X9s(e,s,_,b,w),"dispatchInputRequest"),retry:r((_,b)=>o.retry(_,Q9s(l,b)),"retry")};return z9s({config:t,method:a.method,originalParams:a.params,firstPayload:f,flowStartedAt:u,signal:l?.signal,requestOptions:{...l?.timeout!==void 0&&{timeout:l.timeout},...l?.maxTotalTimeout!==void 0&&{maxTotalTimeout:l.maxTotalTimeout},...l?.onprogress!==void 0&&{onprogress:l.onprogress}},hooks:g})}function eqs(e){return{resultType:"input_required",inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState}}}function RXr(e){if(e)try{return nqs.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();return t===""||e.slice(t.length).includes(",")?void 0:t}}function OXr(e){return pB.parse(JSON.parse(e))}function lfn(e){return JSON.stringify(e)+`
|
|
2138
2138
|
`}function zMe(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function ufn(e=fetch,t){return t?async(n,o)=>e(n,{...t,...o,headers:o?.headers?{...zMe(t.headers),...zMe(o.headers)}:t.headers}):e}var Vpn,GF,s$,Pc,rl,JF,KYr,Zpn,YYr,E$s,A$s,P$s,eXr,tXr,D$s,but,tbl,nbl,FYr,Qpn,j$s,B$s,efn,Du,oh,aXr,cXr,Tge,lXr,$$s,q$s,W$s,X$s,wut,tfn,pXr,rbl,obl,o9s,i9s,nfn,kut,Iut,hXr,c9s,Fre,gXr,xge,Ige,_Xr,rfn,yXr,l9s,UYr,u9s,d9s,p9s,f9s,vXr,bXr,kge,ibl,sbl,zYr,Jpn,S9s,I9s,C9s,$Yr,E9s,abl,M9s,N9s,L9s,$9s,q9s,xXr,TXr,W9s,CXr,Eut,H9s,G9s,J9s,K9s,EXr,tqs,nqs,DXr,cfn,dfn=Y(()=>{hpn();gpn();NYr();tc();Vpn=Symbol.for("mcp.sdk.errorBrands");r(Lre,"stampErrorBrands");r(C2,"brandedHasInstance");GF=(function(e){return e.InvalidRequest="invalid_request",e.InvalidClient="invalid_client",e.InvalidGrant="invalid_grant",e.UnauthorizedClient="unauthorized_client",e.UnsupportedGrantType="unsupported_grant_type",e.InvalidScope="invalid_scope",e.AccessDenied="access_denied",e.ServerError="server_error",e.TemporarilyUnavailable="temporarily_unavailable",e.UnsupportedResponseType="unsupported_response_type",e.UnsupportedTokenType="unsupported_token_type",e.InvalidToken="invalid_token",e.MethodNotAllowed="method_not_allowed",e.TooManyRequests="too_many_requests",e.InvalidClientMetadata="invalid_client_metadata",e.InvalidRedirectUri="invalid_redirect_uri",e.InsufficientScope="insufficient_scope",e.InvalidTarget="invalid_target",e})({}),s$=class HYr extends Error{static{r(this,"OAuthError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.OAuthError"})}static[Symbol.hasInstance](t){return C2(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return C2(this,t)}constructor(t,n,o){super(n),this.code=t,this.errorUri=o,this.name="OAuthError",Lre(this,new.target)}toResponseObject(){let t={error:this.code,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}static fromResponse(t){return new HYr(t.error,t.error_description??t.error,t.error_uri)}},Pc=(function(e){return e.NotConnected="NOT_CONNECTED",e.AlreadyConnected="ALREADY_CONNECTED",e.NotInitialized="NOT_INITIALIZED",e.CapabilityNotSupported="CAPABILITY_NOT_SUPPORTED",e.RequestTimeout="REQUEST_TIMEOUT",e.ConnectionClosed="CONNECTION_CLOSED",e.SendFailed="SEND_FAILED",e.InvalidResult="INVALID_RESULT",e.UnsupportedResultType="UNSUPPORTED_RESULT_TYPE",e.InputRequiredRoundsExceeded="INPUT_REQUIRED_ROUNDS_EXCEEDED",e.ListPaginationExceeded="LIST_PAGINATION_EXCEEDED",e.MethodNotSupportedByProtocolVersion="METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION",e.EraNegotiationFailed="ERA_NEGOTIATION_FAILED",e.ClientHttpNotImplemented="CLIENT_HTTP_NOT_IMPLEMENTED",e.ClientHttpAuthentication="CLIENT_HTTP_AUTHENTICATION",e.ClientHttpForbidden="CLIENT_HTTP_FORBIDDEN",e.ClientHttpUnexpectedContent="CLIENT_HTTP_UNEXPECTED_CONTENT",e.ClientHttpFailedToOpenStream="CLIENT_HTTP_FAILED_TO_OPEN_STREAM",e.ClientHttpFailedToTerminateSession="CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION",e})({}),rl=class extends Error{static{r(this,"SdkError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkError"})}static[Symbol.hasInstance](e){return C2(this,e)}static isInstance(e){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return C2(this,e)}constructor(e,t,n){super(t),this.code=e,this.data=n,this.name="SdkError",Lre(this,new.target)}},JF=class extends rl{static{r(this,"SdkHttpError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.SdkHttpError"})}constructor(e,t,n){super(e,t,n),this.name="SdkHttpError"}get status(){return this.data.status}get statusText(){return this.data.statusText}};r(GYr,"resourceUrlFromServerUrl");r(JYr,"checkResourceAllowed");KYr="2026-07-28",Zpn=[KYr];r(a$,"isModernProtocolVersion");r(Ypn,"legacyProtocolVersions");r($Me,"modernProtocolVersions");r(ZYr,"appendTextFallbackForNonObject");YYr=["task","inputRequests","requestState"];r(I$s,"normalizeContentlessToolResult");r(C$s,"build$1");r(XYr,"buildSchemas2025");r(QYr,"isNonObjectJsonSchemaRoot");A$s=new Set(["const","enum","default","examples"]),P$s=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]);r(LYr,"establishesNewBase");r(R$s,"wrapOutputSchemaForLegacy");eXr={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},tXr={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},D$s={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null};r(Xpn,"registryMaps");r(nXr,"hasRequestMethod2025");r(rXr,"hasNotificationMethod2025");r(O$s,"hasResultMethod");r(M$s,"getResultSchema");r(N$s,"getRequestSchema");r(L$s,"getNotificationSchema");tbl=Object.keys(eXr),nbl=Object.keys(tXr);r(Hpn,"isPlainObject$4");r(Sut,"triState$1");FYr={ok:!1,reason:"not-in-era"};r(jYr,"toolNeedsLegacyWrap");Qpn={era:"2025-11-25",hasRequestMethod:nXr,hasNotificationMethod:rXr,validateRequest:r((e,t)=>Sut(N$s(e),t),"validateRequest"),validateResult:r((e,t)=>Sut(M$s(e),t),"validateResult"),validateNotification:r((e,t)=>Sut(L$s(e),t),"validateNotification"),hasInputRequestMethod:r(()=>!1,"hasInputRequestMethod"),validateInputRequest:r(()=>FYr,"validateInputRequest"),validateInputResponse:r(()=>FYr,"validateInputResponse"),samplingResultVariant:r(((e,t)=>{let n=XYr();return Sut(e?n.CreateMessageResultWithToolsSchema:n.CreateMessageResultSchema,t)}),"samplingResultVariant"),outboundEnvelope:r(e=>{},"outboundEnvelope"),validateEnvelopeMeta:r(e=>[],"validateEnvelopeMeta"),projectCallToolResult(e,t){let n=ZYr(e),o=n.structuredContent;if(o===void 0)return n;let s=typeof o!="object"||o===null||Array.isArray(o),a=t!==void 0&&QYr(t);return!s&&!a?n:{...n,structuredContent:{result:o}}},decodeResult(e,t){if(Hpn(t)&&"resultType"in t){let n={...t};return delete n.resultType,{kind:"complete",result:n}}return{kind:"complete",result:t}},encodeResult(e,t){if(e!=="tools/list")return t;let n=t.tools;return!Array.isArray(n)||!n.some(o=>jYr(o))?t:{...t,tools:n.map(o=>jYr(o)?{...o,outputSchema:R$s(o.outputSchema)}:o)}},encodeErrorCode:r(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope:r(e=>{},"checkInboundEnvelope")};r(F$s,"build");r(Nre,"buildSchemas2026");B$s=["tools/list","prompts/list","resources/list","resources/templates/list","resources/read","server/discover"];r(U$s,"isCacheableResultMethod");efn=Symbol("modelcontextprotocol.resultCacheHintFallback");r(z$s,"cacheHintFallbackOf");r(oXr,"isValidCacheTtlMs");r(iXr,"isValidCacheScope");Du=(function(e){return e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.ResourceNotFound=-32002]="ResourceNotFound",e[e.MissingRequiredClientCapability=-32021]="MissingRequiredClientCapability",e[e.UnsupportedProtocolVersion=-32022]="UnsupportedProtocolVersion",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired",e})({}),oh=class sXr extends Error{static{r(this,"ProtocolError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ProtocolError"})}static[Symbol.hasInstance](t){return C2(this,t)}static isInstance(t){if(typeof this!="function")throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return C2(this,t)}constructor(t,n,o){super(n),this.code=t,this.data=o,this.name="ProtocolError",Lre(this,new.target)}static fromError(t,n,o){if(t===Du.UrlElicitationRequired&&o){let s=o;if(s.elicitations)return new cXr(s.elicitations,n)}if(t===Du.UnsupportedProtocolVersion&&o){let s=o;if(Array.isArray(s.supported)&&typeof s.requested=="string")return new Tge({supported:s.supported,requested:s.requested},n)}if(t===Du.InvalidParams||t===Du.ResourceNotFound){let s=o;if(typeof s?.uri=="string"&&(t===Du.ResourceNotFound||Object.keys(s).length===1))return new aXr(s.uri,n)}if(t===Du.MissingRequiredClientCapability&&o){let s=o;if(s.requiredCapabilities!==null&&typeof s.requiredCapabilities=="object"&&!Array.isArray(s.requiredCapabilities))return new lXr({requiredCapabilities:s.requiredCapabilities},n)}return new sXr(t,n,o)}},aXr=class extends oh{static{r(this,"ResourceNotFoundError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.ResourceNotFoundError"})}constructor(e,t=`Resource not found: ${e}`){super(Du.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},cXr=class extends oh{static{r(this,"UrlElicitationRequiredError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UrlElicitationRequiredError"})}constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Du.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Tge=class extends oh{static{r(this,"UnsupportedProtocolVersionError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.UnsupportedProtocolVersionError"})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(Du.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},lXr=class extends oh{static{r(this,"MissingRequiredClientCapabilityError")}static{Object.defineProperty(this,"mcpBrand",{value:"mcp.MissingRequiredClientCapabilityError"})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(", ")}`){super(Du.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},$$s=0,q$s="private",W$s=["tools/call","prompts/get","resources/read"];r(V$s,"stampResultType");r(H$s,"fillCacheFields");r(G$s,"isPlainObject$3");r(J$s,"stampServerInfoMeta");r(K$s,"resolveTtlMs");r(Z$s,"resolveCacheScope");r(Y$s,"stripCacheHintFallback");X$s=["elicitation/create","sampling/createMessage","roots/list"];r(uXr,"inputSchemaMaps");r(dXr,"isInputRequestMethod2026");r(zpn,"getInputRequestSchema2026");r(Q$s,"getInputResponseSchema2026");tfn={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},pXr={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};r(fXr,"hasRequestMethod2026");r(mXr,"hasNotificationMethod2026");r(e9s,"hasResultMethod2026");r(t9s,"getRequestSchema2026");r(n9s,"getResultSchema2026");r(r9s,"getNotificationSchema2026");rbl=Object.keys(tfn),obl=Object.keys(pXr);r(jMe,"isPlainObject$2");r(LMe,"triState");o9s={ok:!1,reason:"not-in-era"},i9s=[n$,Rre];r(s9s,"enforceDeletedFields");nfn={era:"2026-07-28",hasRequestMethod:fXr,hasNotificationMethod:mXr,hasInputRequestMethod:r(e=>zpn(e)!==void 0,"hasInputRequestMethod"),validateRequest:r((e,t)=>LMe(t9s(e),t),"validateRequest"),validateResult:r((e,t)=>LMe(n9s(e),t),"validateResult"),validateNotification:r((e,t)=>LMe(r9s(e),t),"validateNotification"),validateInputRequest:r((e,t)=>LMe(zpn(e),t),"validateInputRequest"),validateInputResponse:r((e,t)=>LMe(Q$s(e),t),"validateInputResponse"),samplingResultVariant:r(()=>o9s,"samplingResultVariant"),outboundEnvelope(e){return{[n$]:e.protocolVersion,[lge]:e.clientInfo,[Rre]:e.clientCapabilities,...e.logLevel!==void 0&&{[uge]:e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let o of i9s)o in e||t.push({key:o,problem:"missing"});let n=Nre().RequestMetaEnvelopeSchema.safeParse(e);if(!n.success)for(let o of n.error.issues){let s=o.path.map(String),a=s.length>0?s.join("."):"_meta";s.length===1&&t.some(l=>l.key===a&&l.problem==="missing")||t.push({key:a,problem:o.message})}return t},projectCallToolResult:r(e=>ZYr(e),"projectCallToolResult"),inputRequestSchema:zpn,decodeResult(e,t){if(!jMe(t))return{kind:"invalid",error:new rl(Pc.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let n=t.resultType;if(n===void 0)return{kind:"invalid",error:new rl(Pc.InvalidResult,`Invalid result for ${e}: missing required resultType \u2014 servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:"missing-resultType"})};if(typeof n!="string")return{kind:"invalid",error:new rl(Pc.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:n})};if(n==="input_required"){let l=t.inputRequests,u=jMe(l)?l:{},f=t.requestState;return Object.keys(u).length===0&&typeof f!="string"?{kind:"invalid",error:new rl(Pc.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:"input-required-missing-both"})}:{kind:"input_required",inputRequests:u,...typeof f=="string"&&{requestState:f}}}if(n!=="complete")return{kind:"invalid",error:new rl(Pc.UnsupportedResultType,`Unsupported result type '${n}' for ${e}`,{resultType:n,method:e})};let o=a9s(),s=Object.hasOwn(o,e)?o[e]:void 0;if(s!==void 0){let l=s.safeParse(t);if(!l.success)return{kind:"invalid",error:new rl(Pc.InvalidResult,`Invalid result for ${e}: ${l.error}`,{method:e})}}let a={...t};return delete a.resultType,{kind:"complete",result:a}},encodeResult(e,t,n){return J$s(H$s(e,V$s(e,s9s(e,t))),n)},encodeErrorCode:r(e=>e===-32002?-32602:e,"encodeErrorCode"),checkInboundEnvelope(e){if(e.envelope===void 0)return"Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)";let t=Nre().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(n=>n.message).join("; ")}`}};r(a9s,"getWireResultSchemas");Iut="2026-07-28";r(i$,"codecForVersion");r(BYr,"classifiedWireEra");r($pn,"isSpecRequestMethod");r(qpn,"isSpecNotificationMethod");hXr=[Qpn,nfn],c9s=SYr({AnnotationsSchema:r(()=>o$,"AnnotationsSchema"),AudioContentSchema:r(()=>_ge,"AudioContentSchema"),BaseMetadataSchema:r(()=>t$,"BaseMetadataSchema"),BaseRequestParamsSchema:r(()=>zk,"BaseRequestParamsSchema"),BlobResourceContentsSchema:r(()=>_Me,"BlobResourceContentsSchema"),BooleanSchemaSchema:r(()=>xMe,"BooleanSchemaSchema"),CallToolRequestParamsSchema:r(()=>Olt,"CallToolRequestParamsSchema"),CallToolRequestSchema:r(()=>Mlt,"CallToolRequestSchema"),CallToolResultSchema:r(()=>SMe,"CallToolResultSchema"),CancelTaskRequestSchema:r(()=>Rpn,"CancelTaskRequestSchema"),CancelTaskResultSchema:r(()=>Dpn,"CancelTaskResultSchema"),CancelledNotificationParamsSchema:r(()=>Bct,"CancelledNotificationParamsSchema"),CancelledNotificationSchema:r(()=>lMe,"CancelledNotificationSchema"),ClientCapabilitiesSchema:r(()=>qct,"ClientCapabilitiesSchema"),ClientNotificationSchema:r(()=>Mpn,"ClientNotificationSchema"),ClientRequestSchema:r(()=>Opn,"ClientRequestSchema"),ClientResultSchema:r(()=>Npn,"ClientResultSchema"),ClientTasksCapabilitySchema:r(()=>zct,"ClientTasksCapabilitySchema"),CompatibilityCallToolResultSchema:r(()=>Spn,"CompatibilityCallToolResultSchema"),CompleteRequestParamsSchema:r(()=>aut,"CompleteRequestParamsSchema"),CompleteRequestSchema:r(()=>cut,"CompleteRequestSchema"),CompleteResultSchema:r(()=>lut,"CompleteResultSchema"),ContentBlockSchema:r(()=>yge,"ContentBlockSchema"),CreateMessageRequestParamsSchema:r(()=>Hlt,"CreateMessageRequestParamsSchema"),CreateMessageRequestSchema:r(()=>Glt,"CreateMessageRequestSchema"),CreateMessageResultSchema:r(()=>Jlt,"CreateMessageResultSchema"),CreateMessageResultWithToolsSchema:r(()=>Klt,"CreateMessageResultWithToolsSchema"),CreateTaskResultSchema:r(()=>kpn,"CreateTaskResultSchema"),CursorSchema:r(()=>rMe,"CursorSchema"),DiscoverRequestSchema:r(()=>Hct,"DiscoverRequestSchema"),DiscoverResultSchema:r(()=>Mre,"DiscoverResultSchema"),ElicitRequestFormParamsSchema:r(()=>Sge,"ElicitRequestFormParamsSchema"),ElicitRequestParamsSchema:r(()=>eut,"ElicitRequestParamsSchema"),ElicitRequestSchema:r(()=>tut,"ElicitRequestSchema"),ElicitRequestURLParamsSchema:r(()=>Qlt,"ElicitRequestURLParamsSchema"),ElicitResultSchema:r(()=>out,"ElicitResultSchema"),ElicitationCompleteNotificationParamsSchema:r(()=>nut,"ElicitationCompleteNotificationParamsSchema"),ElicitationCompleteNotificationSchema:r(()=>rut,"ElicitationCompleteNotificationSchema"),EmbeddedResourceSchema:r(()=>xlt,"EmbeddedResourceSchema"),EmptyResultSchema:r(()=>cMe,"EmptyResultSchema"),EnumSchemaSchema:r(()=>Xlt,"EnumSchemaSchema"),GetPromptRequestParamsSchema:r(()=>Slt,"GetPromptRequestParamsSchema"),GetPromptRequestSchema:r(()=>wlt,"GetPromptRequestSchema"),GetPromptResultSchema:r(()=>Clt,"GetPromptResultSchema"),GetTaskPayloadRequestSchema:r(()=>Cpn,"GetTaskPayloadRequestSchema"),GetTaskPayloadResultSchema:r(()=>Epn,"GetTaskPayloadResultSchema"),GetTaskRequestSchema:r(()=>Tpn,"GetTaskRequestSchema"),GetTaskResultSchema:r(()=>Ipn,"GetTaskResultSchema"),IconSchema:r(()=>Uct,"IconSchema"),IconsSchema:r(()=>xG,"IconsSchema"),ImageContentSchema:r(()=>gge,"ImageContentSchema"),ImplementationSchema:r(()=>fge,"ImplementationSchema"),InitializeRequestParamsSchema:r(()=>Wct,"InitializeRequestParamsSchema"),InitializeRequestSchema:r(()=>uMe,"InitializeRequestSchema"),InitializeResultSchema:r(()=>Vct,"InitializeResultSchema"),InitializedNotificationSchema:r(()=>pMe,"InitializedNotificationSchema"),JSONArraySchema:r(()=>ypn,"JSONArraySchema"),JSONObjectSchema:r(()=>qv,"JSONObjectSchema"),JSONRPCErrorResponseSchema:r(()=>pge,"JSONRPCErrorResponseSchema"),JSONRPCMessageSchema:r(()=>pB,"JSONRPCMessageSchema"),JSONRPCNotificationSchema:r(()=>aMe,"JSONRPCNotificationSchema"),JSONRPCRequestSchema:r(()=>sMe,"JSONRPCRequestSchema"),JSONRPCResponseSchema:r(()=>vpn,"JSONRPCResponseSchema"),JSONRPCResultResponseSchema:r(()=>dge,"JSONRPCResultResponseSchema"),JSONValueSchema:r(()=>wG,"JSONValueSchema"),LegacyTitledEnumSchemaSchema:r(()=>CMe,"LegacyTitledEnumSchemaSchema"),ListChangedOptionsBaseSchema:r(()=>wMe,"ListChangedOptionsBaseSchema"),ListPromptsRequestSchema:r(()=>vlt,"ListPromptsRequestSchema"),ListPromptsResultSchema:r(()=>blt,"ListPromptsResultSchema"),ListResourceTemplatesRequestSchema:r(()=>Qct,"ListResourceTemplatesRequestSchema"),ListResourceTemplatesResultSchema:r(()=>elt,"ListResourceTemplatesResultSchema"),ListResourcesRequestSchema:r(()=>Yct,"ListResourcesRequestSchema"),ListResourcesResultSchema:r(()=>Xct,"ListResourcesResultSchema"),ListRootsRequestSchema:r(()=>dut,"ListRootsRequestSchema"),ListRootsResultSchema:r(()=>put,"ListRootsResultSchema"),ListTasksRequestSchema:r(()=>Apn,"ListTasksRequestSchema"),ListTasksResultSchema:r(()=>Ppn,"ListTasksResultSchema"),ListToolsRequestSchema:r(()=>Rlt,"ListToolsRequestSchema"),ListToolsResultSchema:r(()=>Dlt,"ListToolsResultSchema"),LoggingLevelSchema:r(()=>kMe,"LoggingLevelSchema"),LoggingMessageNotificationParamsSchema:r(()=>jlt,"LoggingMessageNotificationParamsSchema"),LoggingMessageNotificationSchema:r(()=>Blt,"LoggingMessageNotificationSchema"),ModelHintSchema:r(()=>Ult,"ModelHintSchema"),ModelPreferencesSchema:r(()=>zlt,"ModelPreferencesSchema"),MultiSelectEnumSchemaSchema:r(()=>Ylt,"MultiSelectEnumSchemaSchema"),NotificationSchema:r(()=>O1,"NotificationSchema"),NotificationsParamsSchema:r(()=>D1,"NotificationsParamsSchema"),NumberSchemaSchema:r(()=>bge,"NumberSchemaSchema"),PaginatedRequestParamsSchema:r(()=>Kct,"PaginatedRequestParamsSchema"),PaginatedRequestSchema:r(()=>TG,"PaginatedRequestSchema"),PaginatedResultSchema:r(()=>IG,"PaginatedResultSchema"),PingRequestSchema:r(()=>fMe,"PingRequestSchema"),PrimitiveSchemaDefinitionSchema:r(()=>PMe,"PrimitiveSchemaDefinitionSchema"),ProgressNotificationParamsSchema:r(()=>Jct,"ProgressNotificationParamsSchema"),ProgressNotificationSchema:r(()=>mMe,"ProgressNotificationSchema"),ProgressSchema:r(()=>Gct,"ProgressSchema"),ProgressTokenSchema:r(()=>nMe,"ProgressTokenSchema"),PromptArgumentSchema:r(()=>_lt,"PromptArgumentSchema"),PromptListChangedNotificationSchema:r(()=>Elt,"PromptListChangedNotificationSchema"),PromptMessageSchema:r(()=>Ilt,"PromptMessageSchema"),PromptReferenceSchema:r(()=>sut,"PromptReferenceSchema"),PromptSchema:r(()=>ylt,"PromptSchema"),ReadResourceRequestParamsSchema:r(()=>tlt,"ReadResourceRequestParamsSchema"),ReadResourceRequestSchema:r(()=>nlt,"ReadResourceRequestSchema"),ReadResourceResultSchema:r(()=>rlt,"ReadResourceResultSchema"),RelatedTaskMetadataSchema:r(()=>jct,"RelatedTaskMetadataSchema"),RequestIdSchema:r(()=>kG,"RequestIdSchema"),RequestMetaSchema:r(()=>oMe,"RequestMetaSchema"),RequestSchema:r(()=>Wv,"RequestSchema"),ResourceContentsSchema:r(()=>hMe,"ResourceContentsSchema"),ResourceLinkSchema:r(()=>Tlt,"ResourceLinkSchema"),ResourceListChangedNotificationSchema:r(()=>olt,"ResourceListChangedNotificationSchema"),ResourceRequestParamsSchema:r(()=>mge,"ResourceRequestParamsSchema"),ResourceSchema:r(()=>yMe,"ResourceSchema"),ResourceTemplateReferenceSchema:r(()=>iut,"ResourceTemplateReferenceSchema"),ResourceTemplateSchema:r(()=>Zct,"ResourceTemplateSchema"),ResourceUpdatedNotificationParamsSchema:r(()=>hlt,"ResourceUpdatedNotificationParamsSchema"),ResourceUpdatedNotificationSchema:r(()=>glt,"ResourceUpdatedNotificationSchema"),ResultMetaObjectSchema:r(()=>iMe,"ResultMetaObjectSchema"),ResultSchema:r(()=>Vv,"ResultSchema"),RoleSchema:r(()=>CG,"RoleSchema"),RootSchema:r(()=>uut,"RootSchema"),RootsListChangedNotificationSchema:r(()=>fut,"RootsListChangedNotificationSchema"),SamplingContentSchema:r(()=>Wlt,"SamplingContentSchema"),SamplingMessageContentBlockSchema:r(()=>Pre,"SamplingMessageContentBlockSchema"),SamplingMessageSchema:r(()=>Vlt,"SamplingMessageSchema"),ServerCapabilitiesSchema:r(()=>dMe,"ServerCapabilitiesSchema"),ServerNotificationSchema:r(()=>Fpn,"ServerNotificationSchema"),ServerRequestSchema:r(()=>Lpn,"ServerRequestSchema"),ServerResultSchema:r(()=>jpn,"ServerResultSchema"),ServerTasksCapabilitySchema:r(()=>$ct,"ServerTasksCapabilitySchema"),SetLevelRequestParamsSchema:r(()=>Llt,"SetLevelRequestParamsSchema"),SetLevelRequestSchema:r(()=>Flt,"SetLevelRequestSchema"),SingleSelectEnumSchemaSchema:r(()=>Zlt,"SingleSelectEnumSchemaSchema"),StringSchemaSchema:r(()=>vge,"StringSchemaSchema"),SubscribeRequestParamsSchema:r(()=>ilt,"SubscribeRequestParamsSchema"),SubscribeRequestSchema:r(()=>slt,"SubscribeRequestSchema"),SubscriptionFilterSchema:r(()=>vMe,"SubscriptionFilterSchema"),SubscriptionsAcknowledgedNotificationParamsSchema:r(()=>dlt,"SubscriptionsAcknowledgedNotificationParamsSchema"),SubscriptionsAcknowledgedNotificationSchema:r(()=>plt,"SubscriptionsAcknowledgedNotificationSchema"),SubscriptionsListenRequestParamsSchema:r(()=>llt,"SubscriptionsListenRequestParamsSchema"),SubscriptionsListenRequestSchema:r(()=>ult,"SubscriptionsListenRequestSchema"),SubscriptionsListenResultMetaSchema:r(()=>flt,"SubscriptionsListenResultMetaSchema"),SubscriptionsListenResultSchema:r(()=>mlt,"SubscriptionsListenResultSchema"),TaskAugmentedRequestParamsSchema:r(()=>Ore,"TaskAugmentedRequestParamsSchema"),TaskCreationParamsSchema:r(()=>wpn,"TaskCreationParamsSchema"),TaskMetadataSchema:r(()=>Fct,"TaskMetadataSchema"),TaskSchema:r(()=>EG,"TaskSchema"),TaskStatusNotificationParamsSchema:r(()=>hut,"TaskStatusNotificationParamsSchema"),TaskStatusNotificationSchema:r(()=>xpn,"TaskStatusNotificationSchema"),TaskStatusSchema:r(()=>mut,"TaskStatusSchema"),TextContentSchema:r(()=>hge,"TextContentSchema"),TextResourceContentsSchema:r(()=>gMe,"TextResourceContentsSchema"),TitledMultiSelectEnumSchemaSchema:r(()=>AMe,"TitledMultiSelectEnumSchemaSchema"),TitledSingleSelectEnumSchemaSchema:r(()=>IMe,"TitledSingleSelectEnumSchemaSchema"),ToolAnnotationsSchema:r(()=>Alt,"ToolAnnotationsSchema"),ToolChoiceSchema:r(()=>$lt,"ToolChoiceSchema"),ToolExecutionSchema:r(()=>Plt,"ToolExecutionSchema"),ToolListChangedNotificationSchema:r(()=>Nlt,"ToolListChangedNotificationSchema"),ToolResultContentSchema:r(()=>qlt,"ToolResultContentSchema"),ToolSchema:r(()=>bMe,"ToolSchema"),ToolUseContentSchema:r(()=>klt,"ToolUseContentSchema"),UnsubscribeRequestParamsSchema:r(()=>alt,"UnsubscribeRequestParamsSchema"),UnsubscribeRequestSchema:r(()=>clt,"UnsubscribeRequestSchema"),UntitledMultiSelectEnumSchemaSchema:r(()=>EMe,"UntitledMultiSelectEnumSchemaSchema"),UntitledSingleSelectEnumSchemaSchema:r(()=>TMe,"UntitledSingleSelectEnumSchemaSchema")}),Fre=r(e=>sMe.safeParse(e).success,"isJSONRPCRequest"),gXr=r(e=>aMe.safeParse(e).success,"isJSONRPCNotification"),xge=r(e=>dge.safeParse(e).success,"isJSONRPCResultResponse"),Ige=r(e=>pge.safeParse(e).success,"isJSONRPCErrorResponse"),_Xr=r(e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.resultType==="input_required","isInputRequiredResult"),rfn=r(e=>uMe.safeParse(e).success,"isInitializeRequest"),yXr=r(e=>pMe.safeParse(e).success,"isInitializedNotification"),l9s="Mcp-Param-",UYr="x-mcp-header",u9s=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,d9s=new Set(["string","integer","boolean","number"]);r(ofn,"scanXMcpHeaderDeclarations");p9s=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],f9s=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);r(xut,"pathName");vXr="=?base64?",bXr="?=";r(m9s,"mcpParamPrimitiveToString");r(h9s,"needsBase64");r(g9s,"utf8ToBase64");r(ifn,"encodeMcpParamValue");r(_9s,"valueAtPath");r(SXr,"buildMcpParamHeaders");kge=-32020,ibl=[{rung:"http-method",order:1,evaluatedAt:"edge",codes:[-32e3],conformance:[],rationale:"The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read."},{rung:"jsonrpc-shape",order:2,evaluatedAt:"edge",codes:[Du.InvalidRequest],conformance:["server-stateless"],rationale:"The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic."},{rung:"era-classification",order:3,evaluatedAt:"edge",codes:[kge,Du.UnsupportedProtocolVersion],conformance:["server-stateless","http-header-validation","http-custom-header-server-validation"],rationale:"Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions."},{rung:"envelope",order:4,evaluatedAt:"edge",codes:[Du.InvalidParams],conformance:["server-stateless"],rationale:"A present envelope claim with a malformed envelope \u2014 and a missing envelope on a request whose protocol-version header names a modern revision \u2014 is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400."},{rung:"method-registry",order:5,evaluatedAt:"dispatch",codes:[Du.MethodNotFound],conformance:["server-stateless"],rationale:"Method existence outranks parameter validity: a method absent from the negotiated revision\u2019s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at."},{rung:"request-params",order:6,evaluatedAt:"dispatch",codes:[Du.InvalidParams],conformance:[],rationale:"Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table."},{rung:"standard-header-validation",order:7,evaluatedAt:"pre-dispatch",codes:[kge],conformance:["http-header-validation"],rationale:"SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers \u2014 presence, sentinel decoding, and `Mcp-Name` \u2194 body cross-check \u2014 are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier\u2019s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5\u20136) are consulted."},{rung:"client-capabilities",order:8,evaluatedAt:"pre-dispatch",codes:[Du.MissingRequiredClientCapability],conformance:["server-stateless"],rationale:"The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced \u2014 pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable."},{rung:"param-header-validation",order:9,evaluatedAt:"pre-dispatch",codes:[kge],conformance:["http-custom-header-server-validation"],rationale:"SEP-2243 `Mcp-Param-*` headers are validated against the named tool\u2019s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung."}],sbl={[Du.ParseError]:400,[Du.InvalidRequest]:400,[Du.MethodNotFound]:404,[Du.UnsupportedProtocolVersion]:400,[Du.MissingRequiredClientCapability]:400,[kge]:400};r(Cut,"parseSchema");r(FMe,"shapeKeys");r(Gpn,"isStandardSchema");zYr=!1,Jpn="draft-2020-12";r(y9s,"standardSchemaToJsonSchema");r(wXr,"isProvablyObjectShapedRoot");r(v9s,"formatIssue");r(Wpn,"validateStandardSchema");r(b9s,"zodEmittedPattern");S9s=/\\\.\\d\{(\d+)\}/;r(w9s,"datetimeReferenceSchemas");r(k9s,"referencePatternsForFormat");r(x9s,"isLibraryFormatPattern");r(UMe,"isJsonObject");r(T9s,"convertStandardElicitationSchema");I9s=new Set(["$comment","deprecated","description","examples","readOnly","title","writeOnly"]);r(sfn,"isAnnotationOnlyJsonSchemaKeyword");C9s=new Set(["$schema",...Object.keys(Sge.shape.requestedSchema.shape)]),$Yr={string:FMe([vge,TMe,IMe,CMe]),number:FMe([bge]),integer:FMe([bge]),boolean:FMe([xMe]),array:FMe([EMe,AMe])},E9s=new Set(vge.shape.format.unwrap().options);r(A9s,"walkProperty");r(P9s,"walkRequestedSchema");r(R9s,"describeUnsupportedProperties");r(Kpn,"findDroppedConstraintPaths");r(D9s,"normalizeElicitInputParams");r(O9s,"buildInputRequired");abl=Object.assign(O9s,{elicit(e){try{return{method:"elicitation/create",params:D9s(e)}}catch(t){throw t instanceof oh?new TypeError(t.message,{cause:t}):t}},elicitUrl(e){return{method:"elicitation/create",params:{...e,mode:"url"}}},createMessage(e){return{method:"sampling/createMessage",params:e}},listRoots(){return{method:"roots/list"}}}),M9s=!0,N9s=10,L9s=250;r(kXr,"resolveInputRequiredDriverConfig");r(F9s,"buildInputRequiredRetryParams");r(j9s,"inputRequiredRoundsExceededMessage");r(B9s,"sleep");r(U9s,"linkedRoundAbort");r(z9s,"runInputRequiredDriver");$9s=["AnnotationsSchema","AudioContentSchema","BaseMetadataSchema","BlobResourceContentsSchema","BooleanSchemaSchema","CallToolRequestSchema","CallToolRequestParamsSchema","CallToolResultSchema","CancelledNotificationSchema","CancelledNotificationParamsSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientCapabilitiesSchema","ClientNotificationSchema","ClientRequestSchema","ClientResultSchema","CompatibilityCallToolResultSchema","CompleteRequestSchema","CompleteRequestParamsSchema","CompleteResultSchema","ContentBlockSchema","CreateMessageRequestSchema","CreateMessageRequestParamsSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","CreateTaskResultSchema","CursorSchema","DiscoverRequestSchema","DiscoverResultSchema","ElicitationCompleteNotificationSchema","ElicitationCompleteNotificationParamsSchema","ElicitRequestSchema","ElicitRequestFormParamsSchema","ElicitRequestParamsSchema","ElicitRequestURLParamsSchema","ElicitResultSchema","EmbeddedResourceSchema","EmptyResultSchema","EnumSchemaSchema","GetPromptRequestSchema","GetPromptRequestParamsSchema","GetPromptResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","GetTaskRequestSchema","GetTaskResultSchema","IconSchema","IconsSchema","ImageContentSchema","ImplementationSchema","InitializedNotificationSchema","InitializeRequestSchema","InitializeRequestParamsSchema","InitializeResultSchema","JSONArraySchema","JSONObjectSchema","JSONRPCErrorResponseSchema","JSONRPCMessageSchema","JSONRPCNotificationSchema","JSONRPCRequestSchema","JSONRPCResponseSchema","JSONRPCResultResponseSchema","JSONValueSchema","LegacyTitledEnumSchemaSchema","ListPromptsRequestSchema","ListPromptsResultSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ListRootsRequestSchema","ListRootsResultSchema","ListTasksRequestSchema","ListTasksResultSchema","ListToolsRequestSchema","ListToolsResultSchema","LoggingLevelSchema","LoggingMessageNotificationSchema","LoggingMessageNotificationParamsSchema","ModelHintSchema","ModelPreferencesSchema","MultiSelectEnumSchemaSchema","NotificationSchema","NumberSchemaSchema","PaginatedRequestSchema","PaginatedRequestParamsSchema","PaginatedResultSchema","PingRequestSchema","PrimitiveSchemaDefinitionSchema","ProgressSchema","ProgressNotificationSchema","ProgressNotificationParamsSchema","ProgressTokenSchema","PromptSchema","PromptArgumentSchema","PromptListChangedNotificationSchema","PromptMessageSchema","PromptReferenceSchema","ReadResourceRequestSchema","ReadResourceRequestParamsSchema","ReadResourceResultSchema","RelatedTaskMetadataSchema","RequestSchema","RequestIdSchema","RequestMetaSchema","ResourceSchema","ResourceContentsSchema","ResourceLinkSchema","ResourceListChangedNotificationSchema","ResourceRequestParamsSchema","ResourceTemplateSchema","ResourceTemplateReferenceSchema","ResourceUpdatedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResultMetaObjectSchema","ResultSchema","RoleSchema","RootSchema","RootsListChangedNotificationSchema","SamplingContentSchema","SamplingMessageSchema","SamplingMessageContentBlockSchema","ServerCapabilitiesSchema","ServerNotificationSchema","ServerRequestSchema","ServerResultSchema","SetLevelRequestSchema","SetLevelRequestParamsSchema","SingleSelectEnumSchemaSchema","StringSchemaSchema","SubscribeRequestSchema","SubscribeRequestParamsSchema","SubscriptionFilterSchema","SubscriptionsAcknowledgedNotificationSchema","SubscriptionsAcknowledgedNotificationParamsSchema","SubscriptionsListenRequestSchema","SubscriptionsListenRequestParamsSchema","SubscriptionsListenResultSchema","SubscriptionsListenResultMetaSchema","TaskAugmentedRequestParamsSchema","TaskCreationParamsSchema","TaskMetadataSchema","TaskSchema","TaskStatusSchema","TaskStatusNotificationSchema","TaskStatusNotificationParamsSchema","TextContentSchema","TextResourceContentsSchema","TitledMultiSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","ToolSchema","ToolAnnotationsSchema","ToolChoiceSchema","ToolExecutionSchema","ToolListChangedNotificationSchema","ToolResultContentSchema","ToolUseContentSchema","UnsubscribeRequestSchema","UnsubscribeRequestParamsSchema","UntitledMultiSelectEnumSchemaSchema","UntitledSingleSelectEnumSchemaSchema"],q9s={IdJagTokenExchangeResponseSchema:_ut,OAuthClientInformationFullSchema:NMe,OAuthClientInformationSchema:vut,OAuthClientMetadataSchema:yut,OAuthClientRegistrationErrorSchema:Bpn,OAuthErrorResponseSchema:MMe,OAuthMetadataSchema:wge,OAuthProtectedResourceMetadataSchema:RMe,OAuthTokenRevocationRequestSchema:Upn,OAuthTokensSchema:OMe,OpenIdProviderDiscoveryMetadataSchema:DMe,OpenIdProviderMetadataSchema:gut},xXr={},TXr={};r(IXr,"register");for(let e of $9s)IXr(e,c9s[e]);for(let[e,t]of Object.entries(q9s))IXr(e,t);W9s=Object.freeze(xXr),CXr=Object.freeze(TXr);r(V9s,"bootstrapOutboundCodec");Eut=6e4,H9s=[n$,lge,Rre,uge],G9s=["inputResponses","requestState"];r(qYr,"liftWireOnlyMaterial");r(WYr,"codecResultValidator");r(afn,"requestStateAccessor");J9s=afn(void 0),EXr=class{static{r(this,"Protocol")}_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;static{K9s=r((e,t)=>{e._negotiatedProtocolVersion=t},"writeNegotiatedProtocolVersion")}_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Nct,this.setNotificationHandler("notifications/cancelled",t=>{this._oncancel(t)}),this.setNotificationHandler("notifications/progress",t=>{this._onprogress(t)}),this.setRequestHandler("ping",t=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let n=e.params??{};return{...e,params:{...n,_meta:{...t,...n._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new rl(Pc.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new rl(Pc.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,a)=>{o?.(s,a),xge(s)||Ige(s)?this._onresponse(s):Fre(s)?this._onrequest(s,a):gXr(s)?this._onnotification(s,a):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let o of this._timeoutInfo.values())clearTimeout(o.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let n=new rl(Pc.ConnectionClosed,"Connection closed");this._transport=void 0;try{this.onclose?.()}finally{for(let o of e.values())o(n);for(let o of t.values())o.abort(n)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:n}=qYr(e,"notification"),o=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop")return;if(t?.classification!==void 0){let l=BYr(t.classification);if(l!==o.era){this._onerror(new Error(`Era mismatch on inbound notification '${n.method}': classified as ${l} but this instance serves ${o.era}`));return}}if(qpn(n.method)&&!o.hasNotificationMethod(n.method))return;let s=this._notificationHandlers.get(n.method),a=this.fallbackNotificationHandler;s===void 0&&a===void 0||Promise.resolve().then(()=>s===void 0?a(n):s(n,o)).catch(l=>this._onerror(new Error(`Uncaught error in notification handler: ${l}`)))}_onrequest(e,t){let{message:n,lifted:o}=qYr(e,"request"),s=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)==="drop"){this._onerror(new Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let a=this._transport,l=r((E,R,L)=>{let U={jsonrpc:"2.0",id:n.id,error:{code:E,message:R,...L!==void 0&&{data:L}}};a?.send(U).catch(B=>this._onerror(new Error(`Failed to send an error response: ${B}`)))},"sendErrorResponse");if(t?.classification!==void 0){let E=BYr(t.classification);if(E!==s.era){this._onerror(new Error(`Era mismatch on inbound request '${n.method}': classified as ${E} but this instance serves ${s.era}`));let R=t.classification.revision??E;l(Du.UnsupportedProtocolVersion,`Unsupported protocol version: ${R}`,{supported:this._supportedProtocolVersions,requested:R});return}}if($pn(n.method)&&!s.hasRequestMethod(n.method)){l(Du.MethodNotFound,"Method not found");return}let u=this._requestHandlers.get(n.method)??this.fallbackRequestHandler;if(u===void 0){l(Du.MethodNotFound,"Method not found");return}let f=s.checkInboundEnvelope(o);if(f!==void 0){l(Du.InvalidParams,f);return}let g=r((E,R)=>this._notificationViaCodec(this._resolveOutboundCodec(E.method),E,{...R,relatedRequestId:n.id}),"sendNotification"),_=r((E,R,L)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(E.method),E,R,{...L,relatedRequestId:n.id}),"sendRequest"),b=new AbortController;this._requestHandlerAbortControllers.set(n.id,b);let w=o.inputResponses===void 0?void 0:Z9s(o.inputResponses),T={sessionId:a?.sessionId,mcpReq:{id:n.id,method:n.method,_meta:n.params?._meta,...o.envelope!==void 0&&{envelope:o.envelope},...w!==void 0&&{inputResponses:w.accepted},...w!==void 0&&w.droppedKeys.length>0&&{droppedInputResponseKeys:w.droppedKeys},requestState:o.requestState===void 0?J9s:afn(o.requestState),signal:b.signal,send:r(((E,R,L)=>{let U=this._resolveOutboundCodec(E.method);if(this._assertOutboundRequestInEra(U,E.method),Gpn(R))return _(E,R,L);let B=WYr(U,E.method);if(B===void 0)throw new TypeError(`'${E.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return _(E,B,R)}),"send"),notify:g},http:t?.authInfo?{authInfo:t.authInfo}:void 0},I=this.buildContext(T,t);Promise.resolve().then(()=>u(n,I)).then(async E=>{if(b.signal.aborted)return;let R;try{R=s.encodeResult(n.method,E,this._outboundServerInfo())}catch(U){this._onerror(new Error(`Failed to encode result for ${n.method}: ${U}`)),l(Du.InternalError,"Internal error");return}let L={result:R,jsonrpc:"2.0",id:n.id};await a?.send(L)},async E=>{if(b.signal.aborted)return;let R=Number.isSafeInteger(E.code)?E.code:Du.InternalError,L={jsonrpc:"2.0",id:n.id,error:{code:s.encodeErrorCode(R),message:E.message??"Internal error",...E.data!==void 0&&{data:E.data}}};await a?.send(L)}).catch(E=>this._onerror(new Error(`Failed to send response: ${E}`))).finally(()=>{this._requestHandlerAbortControllers.get(n.id)===b&&this._requestHandlerAbortControllers.delete(n.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,o=Number(t),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(o),l=this._timeoutInfo.get(o);if(l&&a&&l.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(u){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),a(u);return}s(n)}_onresponse(e){let t=Number(e.id),n=this._responseHandlers.get(t);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),xge(e)?n(e):n(oh.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,n){let o=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(o,e.method),Gpn(t))return this._requestWithSchemaViaCodec(o,e,t,n);let s=WYr(o,e.method);if(s===void 0)throw new TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(o,e,s,t)}_negotiatedWireCodec(){return i$(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=V9s(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if($pn(t)&&!e.hasRequestMethod(t))throw new rl(Pc.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,n){let o=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(o,e.method),this._requestWithSchemaViaCodec(o,e,t,n)}_requestWithSchemaViaCodec(e,t,n,o){let{relatedRequestId:s,resumptionToken:a,onresumptiontoken:l,headers:u}=o??{},f=Date.now(),g,_;return new Promise((b,w)=>{let T=r(J=>{w(J)},"earlyReject");if(!this._transport){T(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(J){T(J);return}if(o?.signal?.aborted){let J=o.signal.reason;throw J instanceof rl?J:new rl(Pc.RequestTimeout,String(J))}let I=e.era===Iut&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,E=this._requestMessageId++;_=E;let R={...t,jsonrpc:"2.0",id:E};o?.onprogress&&(this._progressHandlers.set(E,o.onprogress),R.params={...t.params,_meta:{...t.params?._meta,progressToken:E}});let L=this._envelopeOutbound(R),U=!1,B=r(J=>{U||(this._progressHandlers.delete(E),I===void 0?this._transport?.send(this._envelopeOutbound({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:E,reason:String(J)}}),{relatedRequestId:s,resumptionToken:a,onresumptiontoken:l}).catch(q=>this._onerror(new Error(`Failed to send cancellation: ${q}`))):I.abort(),w(J instanceof rl?J:new rl(Pc.RequestTimeout,String(J))))},"cancel");this._responseHandlers.set(E,J=>{if(o?.signal?.aborted)return;if(U=!0,J instanceof Error)return w(J);let q;try{q=e.decodeResult(t.method,J.result)}catch(ae){return w(ae instanceof Error?ae:new Error(String(ae)))}if(q.kind==="invalid")return w(q.error);if(q.kind==="input_required"){if(o?.allowInputRequired===!0)return b(eqs(q));let ae={codec:e,request:t,resultSchema:n,options:o,flowStartedAt:f,retry:r((Ce,pe)=>this._requestWithSchemaViaCodec(e,Ce===void 0?{method:t.method}:{method:t.method,params:Ce},n,pe),"retry")};return b(this._resolveNonCompleteResult(q,ae))}let ie=q.result;Wpn(n,ie).then(ae=>{ae.success?b(ae.data):w(new rl(Pc.InvalidResult,`Invalid result for ${t.method}: ${ae.error}`))},w)}),g=r(()=>B(o?.signal?.reason),"onAbort"),o?.signal?.addEventListener("abort",g,{once:!0});let z=o?.timeout??Eut,$=r(()=>B(new rl(Pc.RequestTimeout,"Request timed out",{timeout:z})),"timeoutHandler");this._setupTimeout(E,z,o?.maxTotalTimeout,$,o?.resetTimeoutOnProgress??!1),this._transport.send(L,{relatedRequestId:s,resumptionToken:a,onresumptiontoken:l,headers:u,requestSignal:I?.signal}).catch(J=>{this._progressHandlers.delete(E),w(J)})}).finally(()=>{g&&o?.signal?.removeEventListener("abort",g),_!==void 0&&(this._responseHandlers.delete(_),this._cleanupTimeout(_))})}async notification(e,t){return this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,n){if(!this._transport)throw new rl(Pc.NotConnected,"Not connected");if(qpn(t.method)&&!e.hasNotificationMethod(t.method))throw new rl(Pc.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let o=this._envelopeOutbound({jsonrpc:"2.0",...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!n?.relatedRequestId){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(o,n).catch(s=>this._onerror(s))});return}await this._transport.send(o,n)}setRequestHandler(e,t,n){this.assertRequestHandlerCapability(e);let o;if(typeof t=="function"){if(!$pn(e))throw new TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);o=r((s,a)=>{let l=this._negotiatedWireCodec(),u=l.validateRequest(e,s);if(!u.ok&&u.reason==="not-in-era"&&(u=l.validateInputRequest(e,s)),!u.ok)throw u.reason==="not-in-era"?new oh(Du.InternalError,`No wire schema for ${e} in the resolved era`):new Error(u.message);return Promise.resolve(t(u.value,a))},"stored")}else if(n)o=r(async(s,a)=>{let l=await Wpn(t.params,{...s.params});if(!l.success)throw new oh(Du.InvalidParams,`Invalid params for ${e}: ${l.error}`);return n(l.data,a)},"stored");else throw new TypeError("setRequestHandler: handler is required");this._requestHandlers.set(e,this._wrapHandler(e,o))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,n){if(typeof t=="function"){if(!qpn(e))throw new TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(o,s)=>{let a=s.validateNotification(e,o);if(!a.ok)throw a.reason==="not-in-era"?new oh(Du.InternalError,`No wire schema for ${e} in the resolved era`):new Error(a.message);return Promise.resolve(t(a.value))});return}if(!n)throw new TypeError("setNotificationHandler: handler is required");this._notificationHandlers.set(e,async o=>{let s=await Wpn(t.params,{...o.params});if(!s.success)throw new oh(Du.InvalidParams,`Invalid params for notification ${e}: ${s.error}`);await n(s.data,o)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};r(BMe,"isPlainObject$1");r(AXr,"mergeCapabilities");r(Tut,"isPlainObject");r(Z9s,"partitionInputResponses");r(VYr,"relatedMessagingUnavailable");r(Y9s,"synthesizeInputRequestContext");r(X9s,"dispatchInputRequest");r(Q9s,"buildRetryLegRequestOptions");r(PXr,"runInputRequiredFlow");r(eqs,"manualInputRequiredValue");tqs=qs((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,n=/\\([\u000b\u0020-\u00ff])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=s;function s(u){if(!u)throw new TypeError("argument string is required");var f=typeof u=="object"?a(u):u;if(typeof f!="string")throw new TypeError("argument string is required to be a string");var g=f.indexOf(";"),_=g!==-1?f.slice(0,g).trim():f.trim();if(!o.test(_))throw new TypeError("invalid media type");var b=new l(_.toLowerCase());if(g!==-1){var w,T,I;for(t.lastIndex=g;T=t.exec(f);){if(T.index!==g)throw new TypeError("invalid parameter format");g+=T[0].length,w=T[1].toLowerCase(),I=T[2],I.charCodeAt(0)===34&&(I=I.slice(1,-1),I.indexOf("\\")!==-1&&(I=I.replace(n,"$1"))),b.parameters[w]=I}if(g!==f.length)throw new TypeError("invalid parameter format")}return b}r(s,"parse");function a(u){var f;if(typeof u.getHeader=="function"?f=u.getHeader("content-type"):typeof u.headers=="object"&&(f=u.headers&&u.headers["content-type"]),typeof f!="string")throw new TypeError("content-type header is missing from object");return f}r(a,"getcontenttype");function l(u){this.parameters=Object.create(null),this.type=u}r(l,"ContentType")})),nqs=Mct(tqs(),1);r(RXr,"mediaTypeEssence");DXr=10*1024*1024,cfn=class{static{r(this,"ReadBuffer")}_buffer;_maxBufferSize;constructor(e){this._maxBufferSize=e?.maxBufferSize??DXr}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){for(;this._buffer;){let e=this._buffer.indexOf(`
|
|
2139
2139
|
`);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");this._buffer=this._buffer.subarray(e+1);try{return OXr(t)}catch(n){if(n instanceof SyntaxError)continue;throw n}}return null}clear(){this._buffer=void 0}};r(OXr,"deserializeMessage");r(lfn,"serializeMessage");r(zMe,"normalizeHeaders");r(ufn,"createFetchWithInit")});function pfn(e){let t=new e({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return yWs(t),t}var Put,MXr,Ld,Nf,KF,Dut,rqs,NXr,LXr,Rut,oqs,ZF,iqs,sqs,FXr,aqs,Out,Cge,qMe,Ege,Mut,cqs,jXr,lqs,uqs,dqs,ffn,pqs,mfn,BXr,fqs,mqs,hqs,gqs,_qs,yqs,vqs,bqs,hfn,Sqs,wqs,kqs,UXr,zXr,$Xr,xqs,Tqs,Iqs,gfn,Cqs,qXr,Eqs,Aqs,Pqs,Rqs,Dqs,Oqs,Mqs,Nqs,WXr,Lqs,VXr,HXr,GXr,Fqs,_fn,jqs,JXr,KXr,ZXr,Bqs,Uqs,YXr,zqs,$qs,qqs,XXr,Wqs,Vqs,QXr,Hqs,Gqs,Jqs,Kqs,Zqs,Yqs,Xqs,Qqs,eWs,tWs,nWs,rWs,oWs,iWs,sWs,aWs,cWs,lWs,uWs,dWs,pWs,fWs,mWs,eQr,hWs,gWs,_Ws,yWs,yfn,bbl,tQr=Y(()=>{hpn();gpn();Put=qs((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{static{r(this,"_CodeOrName")}};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{static{r(this,"Name")}constructor(L){if(super(),!e.IDENTIFIER.test(L))throw new Error("CodeGen: name must be a valid identifier");this.str=L}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var o=class extends t{static{r(this,"_Code")}constructor(L){super(),this._items=typeof L=="string"?[L]:L}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let L=this._items[0];return L===""||L==='""'}get str(){var L;return(L=this._str)!==null&&L!==void 0?L:this._str=this._items.reduce((U,B)=>`${U}${B}`,"")}get names(){var L;return(L=this._names)!==null&&L!==void 0?L:this._names=this._items.reduce((U,B)=>(B instanceof n&&(U[B.str]=(U[B.str]||0)+1),U),{})}};e._Code=o,e.nil=new o("");function s(L,...U){let B=[L[0]],z=0;for(;z<U.length;)u(B,U[z]),B.push(L[++z]);return new o(B)}r(s,"_"),e._=s;let a=new o("+");function l(L,...U){let B=[T(L[0])],z=0;for(;z<U.length;)B.push(a),u(B,U[z]),B.push(a,T(L[++z]));return f(B),new o(B)}r(l,"str"),e.str=l;function u(L,U){U instanceof o?L.push(...U._items):U instanceof n?L.push(U):L.push(b(U))}r(u,"addCodeArg"),e.addCodeArg=u;function f(L){let U=1;for(;U<L.length-1;){if(L[U]===a){let B=g(L[U-1],L[U+1]);if(B!==void 0){L.splice(U-1,3,B);continue}L[U++]="+"}U++}}r(f,"optimize");function g(L,U){if(U==='""')return L;if(L==='""')return U;if(typeof L=="string")return U instanceof n||L[L.length-1]!=='"'?void 0:typeof U!="string"?`${L.slice(0,-1)}${U}"`:U[0]==='"'?L.slice(0,-1)+U.slice(1):void 0;if(typeof U=="string"&&U[0]==='"'&&!(L instanceof n))return`"${L}${U.slice(1)}`}r(g,"mergeExprItems");function _(L,U){return U.emptyStr()?L:L.emptyStr()?U:l`${L}${U}`}r(_,"strConcat"),e.strConcat=_;function b(L){return typeof L=="number"||typeof L=="boolean"||L===null?L:T(Array.isArray(L)?L.join(","):L)}r(b,"interpolate");function w(L){return new o(T(L))}r(w,"stringify"),e.stringify=w;function T(L){return JSON.stringify(L).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}r(T,"safeStringify"),e.safeStringify=T;function I(L){return typeof L=="string"&&e.IDENTIFIER.test(L)?new o(`.${L}`):s`[${L}]`}r(I,"getProperty"),e.getProperty=I;function E(L){if(typeof L=="string"&&e.IDENTIFIER.test(L))return new o(`${L}`);throw new Error(`CodeGen: invalid export name: ${L}, use explicit $id name mapping`)}r(E,"getEsmExportName"),e.getEsmExportName=E;function R(L){return new o(L.toString())}r(R,"regexpCode"),e.regexpCode=R})),MXr=qs((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Put();var n=class extends Error{static{r(this,"ValueError")}constructor(f){super(`CodeGen: "code" for ${f} not defined`),this.value=f.value}},o;(function(f){f[f.Started=0]="Started",f[f.Completed=1]="Completed"})(o||(e.UsedValueState=o={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};var s=class{static{r(this,"Scope")}constructor({prefixes:f,parent:g}={}){this._names={},this._prefixes=f,this._parent=g}toName(f){return f instanceof t.Name?f:this.name(f)}name(f){return new t.Name(this._newName(f))}_newName(f){let g=this._names[f]||this._nameGroup(f);return`${f}${g.index++}`}_nameGroup(f){var g,_;if(!((_=(g=this._parent)===null||g===void 0?void 0:g._prefixes)===null||_===void 0)&&_.has(f)||this._prefixes&&!this._prefixes.has(f))throw new Error(`CodeGen: prefix "${f}" is not allowed in this scope`);return this._names[f]={prefix:f,index:0}}};e.Scope=s;var a=class extends t.Name{static{r(this,"ValueScopeName")}constructor(f,g){super(g),this.prefix=f}setValue(f,{property:g,itemIndex:_}){this.value=f,this.scopePath=(0,t._)`.${new t.Name(g)}[${_}]`}};e.ValueScopeName=a;let l=(0,t._)`\n`;var u=class extends s{static{r(this,"ValueScope")}constructor(f){super(f),this._values={},this._scope=f.scope,this.opts={...f,_n:f.lines?l:t.nil}}get(){return this._scope}name(f){return new a(f,this._newName(f))}value(f,g){var _;if(g.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let b=this.toName(f),{prefix:w}=b,T=(_=g.key)!==null&&_!==void 0?_:g.ref,I=this._values[w];if(I){let L=I.get(T);if(L)return L}else I=this._values[w]=new Map;I.set(T,b);let E=this._scope[w]||(this._scope[w]=[]),R=E.length;return E[R]=g.ref,b.setValue(g,{property:w,itemIndex:R}),b}getValue(f,g){let _=this._values[f];if(_)return _.get(g)}scopeRefs(f,g=this._values){return this._reduceValues(g,_=>{if(_.scopePath===void 0)throw new Error(`CodeGen: name "${_}" has no value`);return(0,t._)`${f}${_.scopePath}`})}scopeCode(f=this._values,g,_){return this._reduceValues(f,b=>{if(b.value===void 0)throw new Error(`CodeGen: name "${b}" has no value`);return b.value.code},g,_)}_reduceValues(f,g,_={},b){let w=t.nil;for(let T in f){let I=f[T];if(!I)continue;let E=_[T]=_[T]||new Map;I.forEach(R=>{if(E.has(R))return;E.set(R,o.Started);let L=g(R);if(L){let U=this.opts.es5?e.varKinds.var:e.varKinds.const;w=(0,t._)`${w}${U} ${R} = ${L};${this.opts._n}`}else if(L=b?.(R))w=(0,t._)`${w}${L}${this.opts._n}`;else throw new n(R);E.set(R,o.Completed)})}return w}};e.ValueScope=u})),Ld=qs((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=Put(),n=MXr();var o=Put();Object.defineProperty(e,"_",{enumerable:!0,get:r(function(){return o._},"get")}),Object.defineProperty(e,"str",{enumerable:!0,get:r(function(){return o.str},"get")}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:r(function(){return o.strConcat},"get")}),Object.defineProperty(e,"nil",{enumerable:!0,get:r(function(){return o.nil},"get")}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:r(function(){return o.getProperty},"get")}),Object.defineProperty(e,"stringify",{enumerable:!0,get:r(function(){return o.stringify},"get")}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:r(function(){return o.regexpCode},"get")}),Object.defineProperty(e,"Name",{enumerable:!0,get:r(function(){return o.Name},"get")});var s=MXr();Object.defineProperty(e,"Scope",{enumerable:!0,get:r(function(){return s.Scope},"get")}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:r(function(){return s.ValueScope},"get")}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:r(function(){return s.ValueScopeName},"get")}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:r(function(){return s.varKinds},"get")}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};var a=class{static{r(this,"Node")}optimizeNodes(){return this}optimizeNames(Je,Xe){return this}},l=class extends a{static{r(this,"Def")}constructor(Je,Xe,_t){super(),this.varKind=Je,this.name=Xe,this.rhs=_t}render({es5:Je,_n:Xe}){let _t=Je?n.varKinds.var:this.varKind,Dt=this.rhs===void 0?"":` = ${this.rhs}`;return`${_t} ${this.name}${Dt};`+Xe}optimizeNames(Je,Xe){if(Je[this.name.str])return this.rhs&&(this.rhs=Pe(this.rhs,Je,Xe)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},u=class extends a{static{r(this,"Assign")}constructor(Je,Xe,_t){super(),this.lhs=Je,this.rhs=Xe,this.sideEffects=_t}render({_n:Je}){return`${this.lhs} = ${this.rhs};`+Je}optimizeNames(Je,Xe){if(!(this.lhs instanceof t.Name&&!Je[this.lhs.str]&&!this.sideEffects))return this.rhs=Pe(this.rhs,Je,Xe),this}get names(){return rt(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},f=class extends u{static{r(this,"AssignOp")}constructor(Je,Xe,_t,Dt){super(Je,_t,Dt),this.op=Xe}render({_n:Je}){return`${this.lhs} ${this.op}= ${this.rhs};`+Je}},g=class extends a{static{r(this,"Label")}constructor(Je){super(),this.label=Je,this.names={}}render({_n:Je}){return`${this.label}:`+Je}},_=class extends a{static{r(this,"Break")}constructor(Je){super(),this.label=Je,this.names={}}render({_n:Je}){return`break${this.label?` ${this.label}`:""};`+Je}},b=class extends a{static{r(this,"Throw")}constructor(Je){super(),this.error=Je}render({_n:Je}){return`throw ${this.error};`+Je}get names(){return this.error.names}},w=class extends a{static{r(this,"AnyCode")}constructor(Je){super(),this.code=Je}render({_n:Je}){return`${this.code};`+Je}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(Je,Xe){return this.code=Pe(this.code,Je,Xe),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},T=class extends a{static{r(this,"ParentNode")}constructor(Je=[]){super(),this.nodes=Je}render(Je){return this.nodes.reduce((Xe,_t)=>Xe+_t.render(Je),"")}optimizeNodes(){let{nodes:Je}=this,Xe=Je.length;for(;Xe--;){let _t=Je[Xe].optimizeNodes();Array.isArray(_t)?Je.splice(Xe,1,..._t):_t?Je[Xe]=_t:Je.splice(Xe,1)}return Je.length>0?this:void 0}optimizeNames(Je,Xe){let{nodes:_t}=this,Dt=_t.length;for(;Dt--;){let gn=_t[Dt];gn.optimizeNames(Je,Xe)||(Tt(Je,gn.names),_t.splice(Dt,1))}return _t.length>0?this:void 0}get names(){return this.nodes.reduce((Je,Xe)=>ze(Je,Xe.names),{})}},I=class extends T{static{r(this,"BlockNode")}render(Je){return"{"+Je._n+super.render(Je)+"}"+Je._n}},E=class extends T{static{r(this,"Root")}},R=class extends I{static{r(this,"Else")}};R.kind="else";var L=class Aut extends I{static{r(this,"If")}constructor(Xe,_t){super(_t),this.condition=Xe}render(Xe){let _t=`if(${this.condition})`+super.render(Xe);return this.else&&(_t+="else "+this.else.render(Xe)),_t}optimizeNodes(){super.optimizeNodes();let Xe=this.condition;if(Xe===!0)return this.nodes;let _t=this.else;if(_t){let Dt=_t.optimizeNodes();_t=this.else=Array.isArray(Dt)?new R(Dt):Dt}if(_t)return Xe===!1?_t instanceof Aut?_t:_t.nodes:this.nodes.length?this:new Aut(Ye(Xe),_t instanceof Aut?[_t]:_t.nodes);if(!(Xe===!1||!this.nodes.length))return this}optimizeNames(Xe,_t){var Dt;if(this.else=(Dt=this.else)===null||Dt===void 0?void 0:Dt.optimizeNames(Xe,_t),!!(super.optimizeNames(Xe,_t)||this.else))return this.condition=Pe(this.condition,Xe,_t),this}get names(){let Xe=super.names;return rt(Xe,this.condition),this.else&&ze(Xe,this.else.names),Xe}};L.kind="if";var U=class extends I{static{r(this,"For")}};U.kind="for";var B=class extends U{static{r(this,"ForLoop")}constructor(Je){super(),this.iteration=Je}render(Je){return`for(${this.iteration})`+super.render(Je)}optimizeNames(Je,Xe){if(super.optimizeNames(Je,Xe))return this.iteration=Pe(this.iteration,Je,Xe),this}get names(){return ze(super.names,this.iteration.names)}},z=class extends U{static{r(this,"ForRange")}constructor(Je,Xe,_t,Dt){super(),this.varKind=Je,this.name=Xe,this.from=_t,this.to=Dt}render(Je){let Xe=Je.es5?n.varKinds.var:this.varKind,{name:_t,from:Dt,to:gn}=this;return`for(${Xe} ${_t}=${Dt}; ${_t}<${gn}; ${_t}++)`+super.render(Je)}get names(){return rt(rt(super.names,this.from),this.to)}},$=class extends U{static{r(this,"ForIter")}constructor(Je,Xe,_t,Dt){super(),this.loop=Je,this.varKind=Xe,this.name=_t,this.iterable=Dt}render(Je){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(Je)}optimizeNames(Je,Xe){if(super.optimizeNames(Je,Xe))return this.iterable=Pe(this.iterable,Je,Xe),this}get names(){return ze(super.names,this.iterable.names)}},J=class extends I{static{r(this,"Func")}constructor(Je,Xe,_t){super(),this.name=Je,this.args=Xe,this.async=_t}render(Je){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(Je)}};J.kind="func";var q=class extends T{static{r(this,"Return")}render(Je){return"return "+super.render(Je)}};q.kind="return";var ie=class extends I{static{r(this,"Try")}render(Je){let Xe="try"+super.render(Je);return this.catch&&(Xe+=this.catch.render(Je)),this.finally&&(Xe+=this.finally.render(Je)),Xe}optimizeNodes(){var Je,Xe;return super.optimizeNodes(),(Je=this.catch)===null||Je===void 0||Je.optimizeNodes(),(Xe=this.finally)===null||Xe===void 0||Xe.optimizeNodes(),this}optimizeNames(Je,Xe){var _t,Dt;return super.optimizeNames(Je,Xe),(_t=this.catch)===null||_t===void 0||_t.optimizeNames(Je,Xe),(Dt=this.finally)===null||Dt===void 0||Dt.optimizeNames(Je,Xe),this}get names(){let Je=super.names;return this.catch&&ze(Je,this.catch.names),this.finally&&ze(Je,this.finally.names),Je}},ae=class extends I{static{r(this,"Catch")}constructor(Je){super(),this.error=Je}render(Je){return`catch(${this.error})`+super.render(Je)}};ae.kind="catch";var Ce=class extends I{static{r(this,"Finally")}render(Je){return"finally"+super.render(Je)}};Ce.kind="finally";var pe=class{static{r(this,"CodeGen")}constructor(Je,Xe={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...Xe,_n:Xe.lines?`
|
|
@@ -15246,7 +15246,7 @@ if (isProcessEntry) {
|
|
|
15246
15246
|
`)}function zVo(e){return e.trim().slice(0,2e3)}var Fbe,VVa,BVo,WAn,VAn,UVo,qVo=Y(()=>{"use strict";Fbe=require("node:path"),VVa=3e4,BVo=128*1024,WAn=/!`([^`]*)`/gu,VAn=/```!\s*\r?\n?([\s\S]*?)```/gu,UVo=/\$\{(CLAUDE_CODE_SESSION_ID|CLAUDE_PLUGIN_DATA|CLAUDE_PLUGIN_ROOT|CLAUDE_PROJECT_DIR|CLAUDE_SESSION_ID|CLAUDE_SKILL_DIR|ZCODE_PLUGIN_DATA|ZCODE_PLUGIN_ROOT|ZCODE_PROJECT_DIR|ZCODE_SESSION_ID|ZCODE_SKILL_DIR)\}/gu;r($Vo,"expandCustomCommandShellSyntax");r(HVa,"collectShellExpansionMatches");r(GVa,"pickNextMatch");r(JVa,"normalizeFencedShellCommand");r(KVa,"runShellExpansion");r(ZVa,"createShellExpansionEnv");r(YVa,"assertShellExpansionContextAvailable");r(XVa,"inferPluginContext");r(QVa,"formatShellExpansionError");r(zVo,"trimPreview")});function nHa(e){return e.trim().replace(/^\/+/,"").toLowerCase()}function jbe(e){return tHa.has(nHa(e))}var WVo,VVo,eHa,tHa,Bkt=Y(()=>{"use strict";ms();WVo=["goal","workflow","compact","init"],VVo=[{description:"Switch to Plan mode and optionally send a task.",inputHint:"/plan [task]",name:"plan",source:"builtin"}],eHa=["compress","plan"],tHa=new Set($R.flatMap(e=>[e.name,...e.aliases??[]]).concat([...eHa]));r(nHa,"normalizeZCodeSlashCommandName");r(jbe,"isReservedZCodeSlashCommandName")});async function HVo(e,t={}){let n=iHa(e);if(!(!n||jbe(n.name)))try{let o=await Fkt({...t,name:n.name});if(t.executionPort){let s=_Xt({args:n.args,command:o}),a=await $Vo({command:o,content:s.body,executionPort:t.executionPort,sessionId:t.sessionId,signal:t.signal,traceContext:t.traceContext,workingDirectory:t.workingDirectory??process.cwd()});return yXt({argumentCount:s.argumentCount,body:a,command:o,usedArgumentsPlaceholder:s.usedArgumentsPlaceholder}).prompt}return qQe({args:n.args,command:o}).prompt}catch(o){if(o instanceof Error&&rHa.test(o.message))return;throw o}}function iHa(e){let t=oHa.exec(e.trim());return t?.[1]?{args:t[2]?.trim()??"",name:t[1].toLowerCase()}:null}var rHa,oHa,GVo=Y(()=>{"use strict";nr();jkt();qVo();Bkt();rHa=/not found/i,oHa=/^\/([^\s]+)(?:\s+([\s\S]*))?$/;r(HVo,"resolveZCodeCustomCommandPrompt");r(iHa,"parsePromptCustomCommandInvocation")});function KVo(e){return qQe({args:e,command:cHa}).prompt}var f9,Ukt,JVo,sHa,aHa,HAn,cHa,GAn=Y(()=>{"use strict";nr();ms();Mje();f9="workflow",Ukt=$R.find(e=>e.name===f9);if(!Ukt)throw new Error(`Missing builtin slash command help entry: ${f9}`);JVo=`/${f9} `,sHa=Ukt.summary,aHa=Ukt.usage.startsWith(JVo)?Ukt.usage.slice(JVo.length):"",HAn=[`Use the \`${Cb}\` skill to design and launch a dynamic workflow for this request:`,"","$ARGUMENTS","","Decide the subagent topology before writing any code: how many subagents, which of them","share a context, what result each one returns. Then write the script and call the","`CreateWorkflow` tool. (`CreateWorkflow` is the dynamic-workflow tool. Do not use the","legacy `Workflow` tool, and do not substitute the `Agent` tool.)",""].join(`
|
|
15247
15247
|
`),cHa={bytesRead:Buffer.byteLength(HAn),content:HAn,metadata:{allowedTools:[],argumentHint:aHa,description:sHa,disableNonInteractive:!1,frontmatterKeys:["description","argument-hint","skills"],name:f9,path:`builtin:${f9}`,rootPath:"builtin:",scope:"system",skills:[Cb],source:"zcode"},sizeBytes:Buffer.byteLength(HAn),truncated:!1};r(KVo,"expandBuiltinWorkflowCommandPrompt")});function ZVo(e,t={}){let n=dHa(e);if(n){if(n.name===uHa){let o=t.workingDirectory??process.cwd();return pHa({args:n.args,targetPath:(0,zkt.join)(o,"AGENTS.md"),workingDirectory:o})}if(n.name===f9)return t.dynamicWorkflowEnabled===!1?void 0:KVo(n.args)}}function dHa(e){let t=lHa.exec(e.trim());return t?.[1]?{args:t[2]?.trim()??"",name:t[1].toLowerCase()}:null}function pHa(e){let t=e.args?["","Additional user instructions supplied with /init:","```text",e.args,"```"].join(`
|
|
15248
15248
|
`):"";return["You are running ZCode's built-in /init command.","","Your task is to create or update a concise workspace instruction file for future ZCode agents.","","Target:",`- Workspace directory: ${e.workingDirectory}`,`- Instruction file: ${e.targetPath}`,`- Existing hidden instruction candidates: ${(0,zkt.join)(e.workingDirectory,".zcode","AGENTS.md")} and ${(0,zkt.join)(e.workingDirectory,".agents","AGENTS.md")}`,"- File name must be exactly AGENTS.md.","- This command targets the current workspace only. Do not write ~/.zcode/AGENTS.md.",t,"","Process:","1. First check whether .zcode/AGENTS.md or .agents/AGENTS.md exists in the workspace. If either exists, tell the user they already have an instructions file, mention the path found, and stop without creating a new AGENTS.md.","2. Inspect the repository before writing. Prefer Read, Glob, Grep, and safe Bash commands such as ls, find, git status, and package-manager script inspection.","3. If AGENTS.md already exists, read it first and update it with Edit instead of replacing it wholesale.","4. If AGENTS.md does not exist, create it at the workspace root.","5. Keep the file practical and short enough for future agents to read quickly.","6. Include only project-specific facts future ZCode agents would otherwise miss.","7. Ask the user only if a repository-specific decision cannot be inferred and would materially change the file.","","Recommended AGENTS.md content:","- Repository purpose and major directories.","- Build, typecheck, lint, and focused test commands discovered from the repo.","- Architecture boundaries and layer rules that matter for edits.","- Coding conventions, import/path rules, logging rules, UI/design rules, and platform compatibility constraints if present.","- Known gotchas for desktop app, web, remote, stdio, protocols, or agent runtime if this repo has them.","- Any documentation files that agents should read before changing sensitive areas.","","After creating or editing AGENTS.md, summarize the main sections you wrote and mention the file path."].join(`
|
|
15249
|
-
`)}var zkt,lHa,uHa,YVo=Y(()=>{"use strict";zkt=require("node:path");GAn();lHa=/^\/([^\s]+)(?:\s+([\s\S]*))?$/,uHa="init";r(ZVo,"resolveZCodeBuiltinPromptCommand");r(dHa,"parseBuiltinPromptCommandInvocation");r(pHa,"buildInitAgentsPrompt")});async function XVo(e){let t=await Zqt((0,BK.join)(e.storageRoot,"agents"));await Kqt((0,BK.join)(e.storageRoot,"v2","agents-state.json"));let n=[{path:(0,BK.join)(e.storageRoot,"agents"),source:"user"},{path:(0,BK.join)(e.workingDirectory,".zcode","agents"),source:"project"}],o=[];for(let l of t.failures)o.push({code:"agent_read_failed",message:"Subagent Markdown migration failed; original file preserved",path:l.path}),e.logger?.warn("Subagent Markdown migration failed",{module:"bootstrap.subagents",path:l.path,error:String(l.error)});let s=vHa(e.storageRoot),a=[];for(let l of n)for(let u of eHo(l.path)){let f=(0,R8.readFileSync)(u,"utf8"),g=qvn({content:f,path:u,source:l.source});if(g.diagnostic&&(o.push(g.diagnostic),e.logger?.warn("Agent profile diagnostic",{code:g.diagnostic.code,message:g.diagnostic.message,module:"bootstrap.subagents",path:u})),g.profile){let _=mHa(g.profile);if(SHa(_,s.disabledAgentIds))continue;a.push(_)}}return e.logger?.debug("Agent profiles loaded",{diagnosticCount:o.length,module:"bootstrap.subagents",profileCount:a.length}),{builtInModelSelectionOverrides:s.builtInModelSelectionOverrides,pluginAgentModelSelectionOverrides:s.pluginAgentModelSelectionOverrides,diagnostics:o,profiles:a}}function mHa(e){if(e.source!=="project"||e.permissionMode===void 0)return e;let{permissionMode:t,...n}=e;return n}function QVo(e){let t=[],n=[],o=new Set([...fHa,...e.reservedProfileNames??[]]);for(let l of e.plugins){if(!l.enabled)continue;let u=l.components.find(f=>f.kind==="agent")?.items??[];for(let f of u){let g=(0,BK.join)(l.rootPath,"agents",`${f.name}.md`),_=hHa({filePath:g,logger:e.logger,plugin:l});_.diagnostic&&t.push(_.diagnostic),_.parsed&&n.push(_.parsed)}}let s=yHa(n),a=[];for(let l of n){let u=e.modelSelectionOverrides?.[Wqt(l.plugin.id,l.bareName)],f={...gHa(l),...u?{modelSelection:u}:{}};a.push(f);let g=l.bareName.trim();s.get(g)===1&&!o.has(g)?a.push({...f,name:g}):o.has(g)?t.push({code:"agent_ambiguous_name",message:`Plugin agent bare name conflicts with an existing profile; use ${f.name}: ${g}`,path:f.path}):(s.get(g)??0)>1&&t.push({code:"agent_ambiguous_name",message:`Plugin agent bare name is ambiguous; use ${f.name}: ${g}`,path:f.path})}return e.logger?.debug("Plugin agent profiles loaded",{diagnosticCount:t.length,module:"bootstrap.subagents",profileCount:a.length}),{builtInModelSelectionOverrides:{},pluginAgentModelSelectionOverrides:{},diagnostics:t,profiles:a}}function hHa(e){try{let t=(0,R8.readFileSync)(e.filePath,"utf8"),n=qvn({content:t,path:e.filePath,source:"user"});return n.diagnostic&&(e.logger?.warn("Plugin agent profile diagnostic",{code:n.diagnostic.code,message:n.diagnostic.message,module:"bootstrap.subagents",path:e.filePath,pluginId:e.plugin.id}),!n.profile)?{diagnostic:n.diagnostic}:n.profile?{...n.diagnostic?{diagnostic:n.diagnostic}:{},parsed:{bareName:n.profile.name,plugin:e.plugin,profile:n.profile}}:{}}catch(t){return{diagnostic:{code:"agent_read_failed",message:t instanceof Error?t.message:`Failed to read plugin agent: ${e.filePath}`,path:e.filePath}}}}function gHa(e){return{...e.profile,name:`${e.plugin.name}:${e.bareName}`}}function _Ha(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yHa(e){let t=new Map;for(let n of e){let o=n.bareName.trim();t.set(o,(t.get(o)??0)+1)}return t}function vHa(e){try{let t=(0,R8.readFileSync)((0,BK.join)(e,"v2","agents-state.json"),"utf8"),n=JSON.parse(t);return{pluginAgentModelSelectionOverrides:eAe(n.pluginAgentModelSelectionOverrides),builtInModelSelectionOverrides:bHa(n.builtInModelSelectionOverrides),disabledAgentIds:new Set(Array.isArray(n.disabledAgentIds)?n.disabledAgentIds.filter(o=>typeof o=="string"&&o.trim().length>0):[])}}catch{return{builtInModelSelectionOverrides:{},pluginAgentModelSelectionOverrides:{},disabledAgentIds:new Set}}}function bHa(e){let t={},n=_Ha(e)?e:{},o=Pu.safeParse(n["general-purpose"]),s=Pu.safeParse(n.Explore);return o.success&&(t["general-purpose"]=o.data),s.success&&(t.Explore=s.data),t}function SHa(e,t){return e.source!=="user"?!1:t.has(Vqt({name:e.name,scope:"user",source:"user"}))}function eHo(e){if(!(0,R8.existsSync)(e))return[];if(!(0,R8.statSync)(e).isDirectory())return[];let t=[];for(let n of(0,R8.readdirSync)(e,{withFileTypes:!0})){let o=(0,BK.join)(e,n.name);if(n.isDirectory()){t.push(...eHo(o));continue}n.isFile()&&/\.(md|markdown)$/iu.test(n.name)&&t.push(o)}return t.sort((n,o)=>n.localeCompare(o))}var R8,BK,fHa,tHo=Y(()=>{"use strict";R8=require("node:fs"),BK=require("node:path");bz();Y0();ms();fHa=new Set(["general-purpose","Explore"]);r(XVo,"loadZCodeAgentProfiles");r(mHa,"sanitizeProjectAgentProfile");r(QVo,"loadPluginAgentProfiles");r(hHa,"parsePluginAgentProfile");r(gHa,"namespacePluginAgentProfile");r(_Ha,"isRecord");r(yHa,"countBareProfileNames");r(vHa,"readAgentState");r(bHa,"normalizeBuiltInSelectionOverrides");r(SHa,"isDisabledUserProfile");r(eHo,"listMarkdownFiles")});function nHo(){let e=Zie(process.platform),t=Zie((0,$kt.arch)()),n=Zie((0,$kt.release)());return{...e&&t?{"X-Platform":`${e}-${t}`}:{},"X-Os-Category":kHa(process.platform),...n?{"X-Os-Version":n}:{}}}function Zie(e){let t=e?.trim();if(!(!t||!wHa.test(t)))return t}function kHa(e){switch(e){case"darwin":return"macos";case"win32":return"windows";default:return"linux"}}var $kt,wHa,rHo=Y(()=>{"use strict";$kt=require("node:os"),wHa=/^[\x20-\x7e]+$/;r(nHo,"createRuntimePlatformHeaders");r(Zie,"normalizePrintableHeaderValue");r(kHa,"normalizeOsCategory")});function oHo(e=process.env,t={}){let n=THa(t.network);return{defaultHeaders:iHo(e,t),codingPlanSignature:xHa(e,t),env:e,...n?{network:n}:{},...t.endpointRoutingPort?{endpointRoutingPort:t.endpointRoutingPort}:{}}}function xHa(e,t){return{configUrl:YAe(e,JJt),headers:iHo(e,t)}}function THa(e){if(!(!e?.caCertFile&&!e?.httpProxy&&!e?.noProxy))return{...e.caCertFile?{caCertFile:e.caCertFile}:{},...e.httpProxy?{httpProxy:e.httpProxy}:{},...e.noProxy?{noProxy:e.noProxy}:{}}}function iHo(e,t={}){let n=t.sourceTitle??CHa(),o=IHa(e,t),s=Zie(Intl.DateTimeFormat().resolvedOptions().locale),a=Zie(Intl.DateTimeFormat().resolvedOptions().timeZone);return{"HTTP-Referer":p1(e),"User-Agent":`ZCode/${o??"unknown"}`,...o?{"X-ZCode-App-Version":o}:{},"X-Title":`Z Code@${n}`,"X-Release-Channel":YL(e),"X-Client-Language":s??"unknown","X-Client-Timezone":a??"unknown","X-ZCode-Agent":"glm",...nHo()}}function IHa(e,t){return Zie(e[Ape]??t.appVersion)}function CHa(){return process.argv.includes("app-server")||process.argv.includes("agent-server")?"electron":"cli"}var sHo=Y(()=>{"use strict";ms();rHo();r(oHo,"createRuntimeAiSdkModelExecutionConfig");r(xHa,"createCodingPlanSignatureConfig");r(THa,"normalizeAiSdkNetworkConfig");r(iHo,"buildCliZCodeSourceHeaders");r(IHa,"resolveAppVersionForHeaders");r(CHa,"detectDefaultProviderSourceTitle")});var qkt,aHo=Y(()=>{"use strict";NK();qkt=class{static{r(this,"ApiProviderModelRuntime")}#e;#t;#n=!1;constructor(t){this.#e=t.registry,this.#t=t.modelAdapter}modelFactory=r(t=>{if(!this.#n)throw new Error("ApiProviderModelRuntime \u5FC5\u987B\u5148 start() \u518D\u521B\u5EFA Model");let n=this.#e.validateSelection(t.selection);if(!n.ok)throw $En(n);let o=t.selection.providerId,s=t.selection.modelId,a=this.#e.getProvider(o);if(!a)throw new Error("Registry Selection \u6821\u9A8C\u4E0E Provider \u7D22\u5F15\u7ED3\u679C\u4E0D\u4E00\u81F4");let l=this.#e.getModel(o,s);if(!l)throw new Error("Registry Selection \u6821\u9A8C\u4E0E Model \u7D22\u5F15\u7ED3\u679C\u4E0D\u4E00\u81F4");return this.#r(a,l,t)},"modelFactory");start(){this.#n||(this.#n=!0)}dispose(){this.#n=!1}#r(t,n,o){let s=n.config,a=o.selection.options.reasoningLevel;return this.#t.createModel({providerId:t.providerId,modelId:n.modelId,providerConfig:t.config,modelConfig:s,...t.config.access.type==="zhipu-account"&&t.config.access.mode==="off-peak"?{requestDependencies:{requestAuth:{source:o.requestDependencies?.requestAuth?.source}}}:{},options:{reasoningLevel:a}})}}});function Wkt(e){let t=e.options.pluginStorageRoot??bbe(e.cliStorageRoot),n=wct({config:e.configResult.config.plugins,env:e.env??process.env,officialPluginRoots:Aje({extraRoots:e.options.officialPluginRoots,logger:e.logger,storageRoot:t,suppressedBuiltins:new Set(e.configResult.config.plugins.suppressedBuiltins)}),officialPluginsEnabledByDefault:$wt,storageRoot:t,workingDirectory:e.workingDirectory});return e.startupTimer.mark("ZCode plugins resolved",{context:{commandRootCount:n.commandRoots.length,diagnosticCount:n.diagnostics.length,enabledPluginCount:n.plugins.filter(o=>o.enabled).length,hookCount:Object.values(n.hooks??{}).reduce((o,s)=>o+(s??[]).reduce((a,l)=>a+l.hooks.length,0),0),mcpServerCount:Object.keys(n.mcpServers).length,pluginCount:n.plugins.length,pluginStorageRoot:t,skillRootCount:n.skillRoots.length},event:"bootstrap.app.startup.plugins.completed",stage:"resolve_plugins"}),n}function cHo(e){e.startupTimer.start("ZCode app startup started",{context:{hasInjectedModelAdapter:e.hasInjectedModelAdapter,resume:e.resume},event:"bootstrap.app.startup.started",stage:"start"})}function lHo(e){e.startupTimer.mark("ZCode app configuration loaded",{context:{configSourceEnv:e.configResult.sources.env,configSourceProject:e.configResult.sources.project.loaded,configSourceUser:e.configResult.sources.user.loaded},event:"bootstrap.app.startup.config.completed",stage:"load_config"})}function uHo(e){e.startupTimer.mark("ZCode storage adapters initialized",{context:{hasInjectedArtifactStore:e.hasInjectedArtifactStore,hasInjectedSessionStore:e.hasInjectedSessionStore,cliStorageRoot:e.cliStorageRoot,storageRoot:e.storageRoot},event:"bootstrap.app.startup.storage.completed",stage:"initialize_storage"})}function dHo(e){e.startupTimer.mark("ZCode MCP adapter initialized",{context:{hasInjectedMcpPort:e.hasInjectedMcpPort,mcpEnabled:e.mcpEnabled,mcpServerCount:Object.keys(e.configuredMcpServers).length,trustedMcpServerCount:e.trustedMcpServerCount},event:"bootstrap.app.startup.mcp.completed",stage:"initialize_mcp"})}function pHo(e){e.startupTimer.mark("ZCode runtime constructed",{context:{hasInjectedModelAdapter:e.hasInjectedModelAdapter,sessionId:e.sessionId},event:"bootstrap.app.startup.runtime.completed",stage:"create_runtime"})}function fHo(e){e.startupTimer.complete("ZCode app startup completed",{context:{sessionId:e.sessionId,workingDirectory:e.workingDirectory},event:"bootstrap.app.startup.completed",stage:"total"})}function mHo(e){e.logger.debug("Runtime config resolved",{mode:e.runtimeConfig.mode,module:"bootstrap",permissionAllowedToolCount:e.configResult.config.permission.allowedTools.length,permissionDisallowedToolCount:e.configResult.config.permission.disallowedTools.length,permissionSourceEnv:e.configResult.sources.env,permissionSourceUserConfig:e.configResult.sources.user.loaded})}var JAn=Y(()=>{"use strict";GOe();qwt();MK();l9();r(Wkt,"resolveStartupPlugins");r(cHo,"startAppStartup");r(lHo,"markConfigurationLoaded");r(uHo,"markStorageAdaptersInitialized");r(dHo,"markMcpAdapterInitialized");r(pHo,"markRuntimeConstructed");r(fHo,"completeAppStartup");r(mHo,"debugRuntimeConfigResolved")});function EHa(e,t,n){let o=e.indexOf(","),s=e.slice(0,5).toLowerCase()==="data:"&&o>=0?e.slice(5,o).split(";"):[],a=(s.shift()?.trim()||t).split(";",1)[0].toLowerCase(),l=o>=0?e.slice(o+1):"";if(s.at(-1)?.trim().toLowerCase()!=="base64"||!/^[A-Za-z0-9+/]*={0,2}$/u.test(l)||l.length%4!==0)throw new Error("fault.attachment.previewArtifactInvalid");if(!a.startsWith("image/")&&!a.startsWith("video/")&&a!=="application/pdf")throw new Error("fault.attachment.previewNotMedia");let u=Buffer.from(l,"base64");if(u.byteLength>n)throw new Error("fault.attachment.previewTooLarge");return{bytes:u,mediaType:a}}async function KAn(e){if(!e?.providerRegistry)throw new Error("createZCodeApp requires a Provider Registry");let t=I4(),n=e.version??"0.0.0",o=e.sessionId??Ov(),s=e.traceContext??vA({sessionId:o}),a=(0,A4.resolve)(e.runtimeConfig?.workingDirectory??process.cwd()),l=Jzo(K0({env:e.env,projectConfigPath:e.projectConfigPath,workingDirectory:a,workspaceIdentity:e.runtimeConfig?.memory?.workspaceIdentity,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,cliOverrides:Gzo(e)}),e),u=e.loggerFactory??rB({env:e.env}),f=u.createLogger("zcode").child({...Qa(s),module:"bootstrap"}),g=new DK(f,{...Qa(s),module:"bootstrap",startupKind:"zcode_app"},t);cHo({hasInjectedModelAdapter:e.modelAdapter!==void 0,resume:e.resume===!0,startupTimer:g}),lHo({configResult:l,startupTimer:g});let _=u.createLogger("zcode").child({...Qa(s),module:"adapters.model"}),b=Bzo({owner:e.telemetryOwner,sessionId:o}),w,T,I;try{let E=zg(l.config.storage.dir),R=k8(E),L=Zzo(R,OCe(e.env??process.env)==="development"),U=await XVo({logger:f,storageRoot:E,workingDirectory:a}),B=U.profiles,z=Wkt({cliStorageRoot:R,configResult:l,env:e.env,logger:f,options:e,startupTimer:g,workingDirectory:a}),$=ekt({cliStorageRoot:R,logger:f}),J=QVo({logger:f,plugins:z.plugins,reservedProfileNames:B.map(kn=>kn.name),modelSelectionOverrides:U.pluginAgentModelSelectionOverrides}).profiles,q=s$o(z),ie=MVo({pluginOutcome:z,workingDirectory:a}),ae=[...B,...J],Ce=e.sessionStore===void 0,pe=e.sessionStore??await n7o(l,g),ze=Qzo(pe),rt=Sbe(a),Pe=e.runtimeConfig?.mode?void 0:e7o(ze,rt),{configuredMcpServers:Tt,runtimeConfig:Ye,untrustedProjectMcpServers:Fe}=T$o({cliStorageRoot:R,configResult:l,options:e,persistedMode:Pe,pluginHooks:z.hooks,pluginMcpServers:z.mcpServers,builtInMcpServers:ie,pluginRuntimeFeatures:q,builtInSubagentModelSelectionOverrides:U.builtInModelSelectionOverrides,subagentOutputRootDir:(0,A4.join)(R,"agents"),subagentProfiles:ae,storageRoot:E,workingDirectory:a,workspaceIdentity:e.runtimeConfig?.memory?.workspaceIdentity}),St=e.browserControlPort;St&&q.browserUse===!0&&Ye.mcp?.servers?.node_repl?.type==="stdio"&&(w=e.nodeReplBrowserBroker??(T=Nkt({browserControlPort:St,logger:f,platform:e.platform})),Tt=zAn(Tt,w),Ye.mcp={...Ye.mcp,servers:zAn(Ye.mcp.servers??{},w)}),g.mark("ZCode runtime configuration resolved",{context:I$o(Ye,a),event:"bootstrap.app.startup.runtime_config.completed",stage:"resolve_runtime_config"});let kt=Uye(z.plugins);Ye.pluginReferenceCatalog=kt;let st,$e=K$o({appVersion:n,logger:f,projectConfigPath:e.projectConfigPath,policy:e.workspaceHookPolicy,policyProvider:e.workspaceHookPolicyProvider,reviewHost:e.workspaceHookReviewHost,workspaceHookTrustEnabled:e.workspaceHookTrustEnabled,runtimeRoot:l.sources.project.workspaceHookRuntimeRoot??{enabled:Ye.hooks?.enabled===!0,timeoutMs:Ye.hooks?.timeoutMs??6e4,maxOutputBytes:Ye.hooks?.maxOutputBytes??32768},sessionId:o,snapshot:l.sources.project.workspaceHookSnapshot,userConfigPath:l.sources.user.path,workingDirectory:a,...e.workspaceHookReviewHost?{emitReviewEvent:r(async kn=>{if(!st)throw new Error("ZCode runtime is not initialized yet.");await st.appendEvent(om(kn.type,o,kn.payload,{traceId:s.traceId}),s)},"emitReviewEvent"),emitAdmissionEvent:r(async kn=>{if(!st)throw new Error("ZCode runtime is not initialized yet.");await st.appendEvent(om(kn.type,o,kn.payload,{traceId:s.traceId}),s)},"emitAdmissionEvent")}:{}}),jt=new UM({allowedTools:new Set(l.config.permission.allowedTools),autoApproveHighRisk:l.config.permission.autoApproveHighRisk,disallowedTools:new Set(l.config.permission.disallowedTools),allowMediumRiskInAutoMode:l.config.permission.allowMediumRiskInAuto}),Je=e.inputHistoryStore??Xzo(pe),Xe=e.artifactStore??yxr({imageCacheRootDir:(0,A4.join)(E,"cli","image-cache"),pdfCacheRootDir:(0,A4.join)(E,"cli","pdf-cache"),rootDir:(0,A4.join)(E,"cli","artifacts"),videoCacheRootDir:(0,A4.join)(E,"cli","video-cache")}),_t=e.imageProcessorPort??y3r(),Dt=Hzo(e.env??process.env),gn=e.sessionMailboxPort??(Dt?F2o({rootDir:zg((e.env??process.env).ZCODE_MAILBOX_ROOT??"~/.zcode/mailbox")}):void 0);uHo({cliStorageRoot:R,hasInjectedArtifactStore:e.artifactStore!==void 0,hasInjectedSessionStore:e.sessionStore!==void 0,startupTimer:g,storageRoot:E});let cn=e.mcpPort??(Ye.mcp?.enabled===!1?void 0:e.mcpPortFactory?.({workingDirectory:a})??Amn({clientVersion:n,env:e.env,logger:f,network:{httpProxy:l.config.network.httpProxy,noProxy:l.config.network.noProxy,caCertFile:l.config.network.caCertFile},workingDirectory:a})),Fn=e.mcpPort===void 0&&cn!==void 0,on=e.executionPort??sne({onToolExecResource:e.onToolExecResource,network:{httpProxy:l.config.network.httpProxy,noProxy:l.config.network.noProxy,caCertFile:l.config.network.caCertFile},outputRootDir:(0,A4.join)(E,"cli","exec"),processEnv:e.env??process.env}),dt=e.executionPort===void 0,we=e.pdfDocumentPort??S3r({executionPort:on}),_e=e.fileSystemPort??hH(),Pt=e.httpClientPort??C3({env:e.env??process.env,timeoutMs:l.config.network.timeout,proxyUrl:l.config.network.httpProxy,noProxy:l.config.network.noProxy,caCertFile:l.config.network.caCertFile}),ut=e.providerEndpointRoutingPort;dHo({configuredMcpServers:Tt,hasInjectedMcpPort:e.mcpPort!==void 0,mcpEnabled:Ye.mcp?.enabled!==!1,startupTimer:g,trustedMcpServerCount:Object.keys(Ye.mcp?.servers??{}).length}),mHo({configResult:l,logger:f,runtimeConfig:Ye});let Mn=r(()=>{if(!st)throw new Error("ZCode runtime is not initialized yet.");return st},"getRuntime"),Dr=!1,gr=r(()=>Qte({env:e.env??process.env,platform:e.platform??process.platform}).selection,"resolveDefaultShellSelection"),eo,to=r(()=>(eo??=(async()=>await e.resolveInitialBashShellSelection?.()??gr())(),eo),"resolveInitialShellSelection"),oo=r(async()=>{Mn().initializeSessionShellEnvironmentIfNeeded(await to())},"initializeSessionShellEnvironment"),ro=r(async()=>{let kn=e.providerRegistry,Nn;try{Nn=await t7o(pe,o)}catch(Vo){f.warn("Session model selection restore failed",{error:Vo instanceof Error?Vo.message:String(Vo),event:"session.model_selection.restore_failed",sessionId:o})}let Ur=Nn&&kn.validateSelection(Nn);Mn().$zRestoredSessionModel={selection:Nn,registry:kn};return Mn().setSessionModelSelection(Ur?.ok?Nn:void 0),Nn},"restorePersistedModelSelection"),Ji=r(async kn=>{let Nn=Mn(),Ur=kn?.onEvent?Nn.subscribeEvents({onSessionEvent:kn.onEvent}):void 0;try{let Vo=kn?.traceContext??s,qe=await ro();await oo();let Kt=await Nn.resumeFromStore({...kn?.abortSignal?{abortSignal:kn.abortSignal}:{},modeOverride:e.runtimeConfig?.mode,persistedMessages:kn?.persistedMessages,traceContext:Vo});return await Nn.activatePausedTargetAfterResume(Vo),Dr=!0,{...Kt,modelSelection:qe}}finally{Ur?.()}},"resumeFromStore"),pi=r(async(kn,Nn)=>{!e.resume||Dr||(await Ji({...Nn?{abortSignal:Nn}:{},traceContext:kn??s}),Dr=!0)},"prepareResume"),Wi=r(async kn=>{await oo(),await pi(kn?.traceContext,kn?.abortSignal)},"prepareUserExecutionBoundary"),Ii=oHo(e.env,{appVersion:n,endpointRoutingPort:ut,network:l.config.network,sourceTitle:e.sourceTitle}),Rs=e.modelAdapter??Ewt({env:e.env,logger:_,modelIoDir:L,modelIoFullRetentionEnabled:e.modelIoFullRetentionEnabled,executionConfig:Ii,statusSink:b.statusSink,streamIdleTimeoutMs:l.config.modelStream.idleTimeoutMs});e.modelAdapter&&b.statusSink&&Rs.addStatusSink(b.statusSink);let ht=zqo();Rs.setModelIoFullRetentionEnabled(e.modelIoFullRetentionEnabled??!1),I=new qkt({registry:e.providerRegistry,modelAdapter:Rs}),I.start();let mr=I.modelFactory,mi=F9o({agentTelemetry:b.agentExecution,appOptions:e,appVersion:n,artifactStore:Xe,configResult:l,fileSystemPort:_e,httpClientPort:Pt,imageProcessorPort:_t,pdfDocumentPort:we,logger:f,mcpPort:cn,modelFactory:mr,permissionService:jt,prepareUserExecutionBoundary:Wi,getRuntime:Mn,runtimeConfig:Ye,sessionId:o,sessionStore:pe,storageRoot:E,traceContext:s,workingDirectory:a}),Ar=qje(pe,f),hi=Ar===void 0?void 0:mVo({concurrency:ht,createActorRuntime:r(({persona:kn,pinnedModel:Nn,runSubagentModel:Ur,sessionId:Vo,submitPort:qe,submitProfile:Kt,escalatePort:Jt,modelRequestAdmission:en})=>lkt({childSessionId:Vo,configOverrides:{workflowActor:{...kn.name===void 0?{}:{name:kn.name},...kn.system===void 0?{}:{persona:kn.system}},...IVo(),...xVo({parentSelection:Mn().getSessionModelSelection(),...Ur===void 0?{}:{runSelection:Ur}},Nn).configOverrides},deps:{agentTelemetry:b.agentExecution,appOptions:e,appVersion:n,artifactStore:Xe,configResult:l,fileSystemPort:_e,httpClientPort:Pt,imageProcessorPort:_t,logger:f,mcpPort:cn,modelFactory:mr,permissionService:jt,runtime:Mn(),runtimeConfig:Ye,sessionId:o,sessionStore:pe,storageRoot:E,workingDirectory:a},request:{opts:{}},traceContext:s,...Kt.kind==="untyped"?{}:{workflowSubmitPort:qe},...Kt.kind==="mono"?{workflowSubmitSchema:{...Kt.schema}}:{},workflowEscalatePort:Jt,...en===void 0?{}:{modelRequestAdmission:en}}),"createActorRuntime"),actorTranscriptStore:pe,artifactStore:Xe,executionPort:on,fileSystemPort:_e,journal:Ar,logger:f,onRunEvent:wVo({getRuntime:Mn,logger:f,sessionId:o}),parentSessionId:o,registerResidencyBlockingWork:r(kn=>{Mn().trackResidencyBlockingWork(kn)},"registerResidencyBlockingWork"),resolveLaunchInputId:r(kn=>{let Nn=Mn().getActiveTurnInfo();return Nn!==void 0&&Nn.turnId===kn.turnId?Nn.inputId:void 0},"resolveLaunchInputId"),...sAn(pe)?{taskLinkStore:pe}:{}}),Js=yVo({executionPort:on,fileSystemPort:_e,logger:f}),qa=bVo({registry:e.providerRegistry,currentSelection:r(()=>Mn().getSessionModelSelection(),"currentSelection")});st=new V2(o,Ye,{agentTelemetry:b.agentExecution,modelRequestAdmission:ht.observer(),eventStore:e.eventStore??zz(),sessionStore:pe,sessionMailboxPort:gn,logger:f,executionPort:on,workspaceHookAdmission:$e?.admission,workspaceHookSnapshot:$e?.snapshot,browserControlPort:St,fileSystemPort:_e,httpClientPort:Pt,imageProcessorPort:_t,pdfDocumentPort:we,artifactStore:Xe,contextSourcePort:e.contextSourcePort??bme({env:e.env}),skillPort:l.config.features.skill&&l.config.skills.enabled?e.skillPort??mG({extraRoots:l.config.skills.roots,extraResolvedRoots:[...z.skillRoots,...$],disabledPaths:[...x8(l.config.skillOverrides),...Ye.dynamicWorkflowEnabled===!1?M$o($):[]]}):void 0,mcpPort:cn,eventSink:e.eventSink,modelFactory:mr,modelIoDir:L,providerRuntimeHeadersPort:e.providerRuntimeHeadersPort,resolveEffectiveModelSelection:e.resolveEffectiveModelSelection,isRemoteWorkspace:r(()=>YJt(Ye.memory?.workspaceIdentity??""),"isRemoteWorkspace"),permissionBroker:e.permissionBroker,permissionService:jt,workflowPort:mi.workflowPort,dynamicWorkflowRunPort:hi,dynamicWorkflowSnippetPort:Js,modelCatalogPort:qa,automationPort:e.automationPort,offPeakPort:e.offPeakPort,appVersion:n,traceContext:s}),pHo({hasInjectedModelAdapter:e.modelAdapter!==void 0,sessionId:o,startupTimer:g}),fHo({sessionId:o,startupTimer:g,workingDirectory:a}),Rwt(u,f);let li=d7o({artifactStore:Xe,customCommandPromptResolver:r(async(kn,Nn)=>{let Ur=ZVo(kn,{dynamicWorkflowEnabled:Ye.dynamicWorkflowEnabled,workingDirectory:a});return Ur!==void 0?Ur:await HVo(kn,{env:e.env,executionPort:on,logger:f,projectConfigPath:e.projectConfigPath,sessionId:o,signal:Nn?.abortSignal,skipUserConfig:e.skipUserConfig,traceContext:Nn?.traceContext??s,userConfigPath:e.userConfigPath,workingDirectory:a})},"customCommandPromptResolver"),inputHistoryStore:Je,logger:f,prepareUserExecutionBoundary:Wi,runtime:st,sessionId:o,traceContext:s}),oa=i7o({agentTelemetry:b.agentExecution,appOptions:e,appVersion:n,artifactStore:Xe,cliStorageRoot:R,configResult:l,eventSink:e.eventSink,imageProcessorPort:_t,pdfDocumentPort:we,logger:f,mcpPort:cn,modelFactory:mr,permissionService:jt,prepareUserExecutionBoundary:Wi,runtime:st,runtimeConfig:Ye,sessionId:o,sessionStore:pe,storageRoot:E,traceContext:s,workingDirectory:a}),Fs=S$o({...hi===void 0?{}:{closeDynamicWorkflowRuns:r(()=>hi.close(),"closeDynamicWorkflowRuns")},configResult:l,configuredMcpServers:Tt,...e.configuredDefaultModelSelection?{configuredDefaultModelSelection:e.configuredDefaultModelSelection}:{},executionPort:on,localSettingStore:ze,logger:f,loggerFactory:u,mcpPort:cn,ownsExecutionPort:dt,ownsMcpPort:Fn,closeNodeReplBrowserBroker:r(async()=>{await T?.close()},"closeNodeReplBrowserBroker"),ownsSessionStore:Ce,prepareUserExecutionBoundary:Wi,prepareResume:pi,projectID:rt,providerRegistry:e.providerRegistry,resolveUiLocale:r(kn=>xEn(kn,e),"resolveUiLocale"),runtime:st,sessionId:o,sessionStore:pe,traceContext:s,untrustedProjectMcpServers:Fe,workingDirectory:a}),Qo=Fs.close,gi=r(async kn=>{let Nn=kn.ref,Ur=kn.mime,Vo;if(kn.messageId&&kn.attachmentIndex!==void 0){let Kt=(await pe.messageWithParts({sessionID:o,messageID:kn.messageId}))?.parts.filter(Jt=>Jt.type==="file")[kn.attachmentIndex];Kt?.type==="file"&&(Ur=Kt.mime,Vo=Kt.metadata?.artifactUri??(Kt.url.startsWith("zcode-artifact://")?Kt.url:void 0),Nn=Vo??(Kt.url.startsWith("data:")?kn.ref:Kt.url))}return{ref:Nn,mediaType:Ur,...Vo?{artifactUri:Vo}:{}}},"resolvePromptAttachment");return{sessionId:o,traceId:s.traceId,runtime:st,respondWorkspaceHookReview:r(kn=>$e?.respond({sessionId:kn.sessionId,taskId:kn.taskId,runId:kn.runId,...kn.remoteSessionId?{remoteSessionId:kn.remoteSessionId}:{},workspaceIdentity:kn.workspaceIdentity,bundleDigest:kn.bundleDigest,reviewFlowId:kn.reviewFlowId,generation:kn.generation,interactionId:kn.interactionId},kn.decision)??Promise.resolve({accepted:!1,reasonCode:"workspace_hooks_require_trust_capable_host"}),"respondWorkspaceHookReview"),toggleWorkspaceHookReviewItem:r(kn=>$e?.toggle({sessionId:kn.sessionId,taskId:kn.taskId,runId:kn.runId,...kn.remoteSessionId?{remoteSessionId:kn.remoteSessionId}:{},workspaceIdentity:kn.workspaceIdentity,bundleDigest:kn.bundleDigest,reviewFlowId:kn.reviewFlowId,generation:kn.generation,interactionId:kn.interactionId},kn.reviewItemId,kn.enabled)??Promise.resolve({accepted:!1,reasonCode:"workspace_hooks_require_trust_capable_host"}),"toggleWorkspaceHookReviewItem"),revokeWorkspaceHookTrust:r(kn=>("hookDeclarationDigests"in kn?$e?.revokeCurrent(kn):$e?.revoke({sessionId:kn.sessionId,taskId:kn.taskId,runId:kn.runId,...kn.remoteSessionId?{remoteSessionId:kn.remoteSessionId}:{},workspaceIdentity:kn.workspaceIdentity,bundleDigest:kn.bundleDigest,reviewFlowId:kn.reviewFlowId,generation:kn.generation,interactionId:kn.interactionId},kn.reviewItemIds))??Promise.resolve({accepted:!1,reasonCode:"workspace_hooks_require_trust_capable_host"}),"revokeWorkspaceHookTrust"),requestWorkspaceHookReview:r(kn=>$e?.requestReview({workspaceIdentity:kn.workspaceIdentity,bundleDigest:kn.bundleDigest})??Promise.resolve({accepted:!1,reasonCode:"workspace_hooks_require_trust_capable_host"}),"requestWorkspaceHookReview"),reloadWorkspaceHookTrust:r(()=>$e?.reloadTrust()??Promise.resolve(),"reloadWorkspaceHookTrust"),setModelIoFullRetentionEnabled:r(kn=>Rs.setModelIoFullRetentionEnabled(kn),"setModelIoFullRetentionEnabled"),readToolResultArtifact:r(kn=>Xe.readToolResultArtifact({uri:kn,trace:s}),"readToolResultArtifact"),writePromptAttachment:r(async kn=>{let Nn=await Xe.writeToolResultArtifact({content:`data:${kn.mime};base64,${Buffer.from(kn.bytes).toString("base64")}`,contentType:"text/plain",retention:"session",sessionId:o,toolCallId:`prompt-attachment-upload-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,toolName:"prompt-attachment:upload",trace:s});return(kn.mime.startsWith("image/")||kn.mime.startsWith("video/")||kn.mime.split(";",1)[0]?.trim().toLowerCase()==="application/pdf")&&Xe.primeMediaAttachmentPath?.({bytes:kn.bytes,mediaType:kn.mime,uri:Nn.uri}).catch(()=>{}),{ref:Nn.uri}},"writePromptAttachment"),readPromptAttachment:r(async kn=>{let{ref:Nn,mediaType:Ur}=await gi(kn);if(Nn.startsWith("zcode-artifact://")){let qe=await Xe.readToolResultArtifact({uri:Nn,trace:s});return EHa(qe.content,Ur,kn.maxBytes)}return{bytes:(await _e.readBinaryFile({path:Nn,maxBytes:kn.maxBytes,trace:s})).content,mediaType:Ur}},"readPromptAttachment"),statPromptAttachment:r(async kn=>{let{ref:Nn,mediaType:Ur,artifactUri:Vo}=await gi(kn);if(Vo){if(!Xe.statToolResultArtifact)throw new m1(nC.statUnsupported);let Kt=await Xe.statToolResultArtifact({uri:Vo,trace:s});return{totalBytes:Kt.bytes,mediaType:Kt.contentType||Ur,...Kt.mtimeMs===void 0?{}:{mtimeMs:Kt.mtimeMs}}}let qe=await _e.stat({path:Nn,trace:s});if(qe.kind!=="file")throw new m1(nC.statNotFile);return{totalBytes:qe.sizeBytes,mediaType:Ur,...qe.mtimeMs===void 0?{}:{mtimeMs:qe.mtimeMs}}},"statPromptAttachment"),resolvePromptAttachmentPreviewSource:r(async kn=>{let Nn=await gi(kn);if(!Nn.mediaType.startsWith("video/"))return{kind:"chunked"};if(Nn.artifactUri){if(!Xe.ensureMediaAttachmentPath)return{kind:"chunked"};try{let Ur=await Xe.ensureMediaAttachmentPath({uri:Nn.artifactUri,mediaType:Nn.mediaType});if(Ur.status==="ready"&&Ur.path.trim())return{kind:"local_path",path:Ur.path,mediaType:Nn.mediaType}}catch{}return{kind:"chunked"}}return(0,A4.isAbsolute)(Nn.ref)?{kind:"local_path",path:Nn.ref,mediaType:Nn.mediaType}:{kind:"chunked"}},"resolvePromptAttachmentPreviewSource"),...Fs,close:r(async()=>{try{await Qo?.()}finally{try{I?.dispose()}finally{await b.shutdown()}}},"close"),...oa,...mi,...hi===void 0?{}:{listDynamicWorkflowRunEvents:r(async kn=>hi.listEvents(kn.runId,{...kn.afterSequence===void 0?{}:{afterSequence:kn.afterSequence},...kn.limit===void 0?{}:{limit:kn.limit}}),"listDynamicWorkflowRunEvents")},...hi===void 0||typeof hi.listArtifacts!="function"||typeof hi.listArtifactItems!="function"||typeof hi.readArtifact!="function"?{}:{listDynamicWorkflowRunArtifacts:r(async kn=>hi.listArtifacts(kn.runId),"listDynamicWorkflowRunArtifacts"),listDynamicWorkflowRunArtifactItems:r(async kn=>hi.listArtifactItems(kn.runId,kn.artifactId,{...kn.afterSequence===void 0?{}:{afterSequence:kn.afterSequence},limit:kn.limit}),"listDynamicWorkflowRunArtifactItems"),readDynamicWorkflowRunArtifact:r(async kn=>hi.readArtifact(kn.runId,kn.artifactId,kn.version),"readDynamicWorkflowRunArtifact")},...hi===void 0||typeof hi.listWorkspaceNodes!="function"||typeof hi.readWorkspaceNodeResult!="function"?{}:{listDynamicWorkflowRunWorkspaceNodes:r(async kn=>hi.listWorkspaceNodes(kn.runId),"listDynamicWorkflowRunWorkspaceNodes"),readDynamicWorkflowRunNodeResult:r(async kn=>hi.readWorkspaceNodeResult(kn.runId,kn.siteId,kn.ordinal,{maxBytes:kn.maxBytes}),"readDynamicWorkflowRunNodeResult")},...hi===void 0?{}:{},...hi===void 0||typeof hi.listRunsForSession!="function"?{}:{listDynamicWorkflowRuns:r(async kn=>hi.listRunsForSession(kn.limit),"listDynamicWorkflowRuns")},...hi===void 0||typeof hi.replayProgressForSession!="function"?{}:{replayDynamicWorkflowRuns:r(async kn=>hi.replayProgressForSession(kn),"replayDynamicWorkflowRuns")},...hi===void 0||typeof hi.resume!="function"?{}:{resumeWorkflowRun:r(async kn=>{let Nn=await hi.resume(kn.workId);return Nn.ok&&await Mn().trackResumedDynamicWorkflowRun({runId:Nn.runId,...Nn.toolCallId===void 0?{}:{toolCallId:Nn.toolCallId},...kn.name===void 0?{}:{name:kn.name},traceContext:s}),Nn},"resumeWorkflowRun")},...hi===void 0?{}:{startSavedWorkflow:r(async kn=>(await Wi({traceContext:s}),await Mn().startSavedWorkflowRun({...kn,traceContext:s})),"startSavedWorkflow")},...hi===void 0||typeof hi.amend!="function"||typeof hi.getScript!="function"?{}:{amendWorkflowRunSettings:r(async kn=>(await Wi({traceContext:s}),await Mn().amendWorkflowRunSettings({...kn,traceContext:s})),"amendWorkflowRunSettings")},...r$o({configResult:l,options:e,workingDirectory:a}),getPluginReferenceCatalog:r(()=>kt,"getPluginReferenceCatalog"),getSkillCatalog:r(async()=>(await Wi({traceContext:s}),await Mn().getSkillCatalog(s)),"getSkillCatalog"),resume:Ji,...li}}catch(E){throw I?.dispose(),b.shutdown().catch(()=>{}),T?.close(),g.fail("ZCode app startup failed",E,{context:{sessionId:o,workingDirectory:a},event:"bootstrap.app.startup.failed",stage:"total"}),E}}var A4,ZAn=Y(()=>{"use strict";A4=require("node:path");f3();W0e();vw();Eme();yme();a7();Msn();Fsn();j2o();xRe();K0e();sdt();Y0();Cwt();nr();ms();g0();wEn();Pwt();kEn();Kzo();l9();wbe();s7o();p7o();o$o();a$o();w$o();C$o();Mje();N$o();Z$o();j9o();BAn();SAn();vVo();SVo();kVo();QEn();TVo();CVo();$An();NVo();GVo();YVo();kbe();tHo();sHo();aHo();JAn();r(EHa,"decodePromptAttachmentDataUrl");r(KAn,"createZCodeApp")});function QAn(e){let t=DHa.parse(e),n=t.model,o=Hkt(typeof n=="string"?n:n?.main),s=typeof n=="object"?Hkt(n?.lite):void 0,a=o||s?{...o?{main:o}:{},...s?{lite:s}:{}}:void 0;return{...a?{model:a}:{},...t.provider?{provider:t.provider}:{}}}function Hkt(e){if(!e)return;let t=e.indexOf("/");if(t<=0||t===e.length-1)return;let n=e.slice(0,t).trim(),o=e.slice(t+1).trim();if(!(!n||!o))return{provider:n,model:o}}var XAn,hHo,Vkt,AHa,PHa,RHa,YAn,DHa,gHo=Y(()=>{"use strict";Fa();XAn=m.record(m.string(),m.string()),hHo=m.record(m.string(),m.unknown()),Vkt=m.number().finite().positive(),AHa=m.object({enabled:m.boolean().optional(),levels:m.array(m.string().min(1)).optional(),defaultLevel:m.string().min(1).optional(),providerOptionsByLevel:m.record(m.string(),hHo).optional()}),PHa=m.object({id:m.string().min(1).optional(),name:m.string().min(1).optional(),attachment:m.boolean().optional(),reasoning:m.union([m.boolean(),AHa]).optional(),tool_call:m.boolean().optional(),structured_output:m.boolean().optional(),supportsImages:m.boolean().optional(),supportsPdf:m.boolean().optional(),supportsVideo:m.boolean().optional(),supportsToolCall:m.boolean().optional(),supportsJsonSchemaOutput:m.boolean().optional(),contextWindow:Vkt.optional(),maxOutputTokens:Vkt.optional(),limit:m.object({context:Vkt.optional(),output:Vkt.optional()}).optional(),modalities:m.object({input:m.array(m.enum(["text","audio","image","video","pdf"])).optional(),output:m.array(m.enum(["text","audio","image","video","pdf"])).optional()}).optional(),options:hHo.optional(),headers:XAn.optional()}).passthrough(),RHa=m.object({kind:m.enum(["anthropic","openai","openai-compatible"]),name:m.string().min(1).optional(),npm:m.never().optional(),options:m.object({apiKey:m.string().optional(),baseURL:m.string().min(1).optional(),apiKeyRequired:m.boolean().optional(),headers:XAn.optional()}).passthrough().optional(),headers:XAn.optional(),models:m.record(m.string(),PHa).optional()}).passthrough(),YAn=m.string().refine(e=>Hkt(e)!==void 0,{message:"Model references must use provider/model format"}),DHa=m.object({provider:m.record(m.string(),RHa).optional(),model:m.union([YAn,m.object({main:YAn.optional(),lite:YAn.optional()}).strict().refine(e=>e.main!==void 0||e.lite!==void 0)]).optional(),small_model:m.never().optional()}).passthrough();r(QAn,"parseLegacyCliModelConfig");r(Hkt,"parseModelTarget")});function MHa(e){switch(e){case"anthropic":return"anthropic-messages";case"openai":return"openai-responses";case"openai-compatible":case void 0:return"openai-chat-completions"}return"openai-chat-completions"}function NHa(e){let t=QAn(e.input),n=uw.empty(),o=dA.empty();for(let[a,l]of Object.entries(t.provider??{})){let u=a.trim();if(!u)continue;let f=u==="builtin:bigmodel"?aee.bigmodel:u==="builtin:zai"?aee.zai:void 0;if(f){let w=l.options?.apiKey?.trim();w&&(n=n.setRule({providerId:f,templateId:f,config:new Tk({group:"standard-personal",access:new xz({apiKey:w})})}));continue}if(u.startsWith("builtin:")||u.startsWith("account:")||l.source!==void 0&&l.source!=="custom")continue;if(BHa(l))throw new Gkt(u);let g=FHa(l),_=g.map(w=>w.modelId),b=l.name?.trim();n=n.setRule({providerId:u,providerName:b&&b!==u?b:void 0,config:new Tk({group:"standard-personal",access:new xz({apiKey:l.options?.apiKey}),api:new _pe({type:MHa(l.kind),baseUrl:l.options?.baseURL,headers:jHa(l.headers,l.options?.headers)}),..._.length>0?{personalModelIds:_,modelOrder:_}:{}})});for(let w of g)w.contextWindow!==void 0&&(o=o.setExact(u,w.modelId,new uA({properties:new lAe({contextWindow:w.contextWindow})})))}let s=LHa(e.input)??void 0;return Object.freeze({providers:n,models:o,defaultModelSelection:s})}async function Jkt(e){let t=e.filePath??U7();try{let n=JSON.parse(await(0,_Ho.readFile)(t,"utf8"));return NHa({input:n})}catch(n){if(UHa(n)||n instanceof Gkt)return null;throw n}}function LHa(e){let t=QAn(e).model?.main;return!t||t.provider===OHa?null:Object.freeze({providerId:t.provider,modelId:t.model})}function FHa(e){let t=new Set,n=[];for(let[o,s]of Object.entries(e.models??{})){if(s.deleted===!0)continue;let a=(s.id??o).trim();if(!a||t.has(a))continue;t.add(a);let l=s.contextWindow??s.limit?.context;n.push({modelId:a,...zHa(l)?{contextWindow:l}:{}})}return n}function jHa(...e){let t=Object.assign({},...e.filter(Boolean));return Object.keys(t).length>0?t:void 0}function BHa(e){return e.options?.apiKeyRequired===!1}function UHa(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function zHa(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0}var _Ho,OHa,Gkt,ePn=Y(()=>{"use strict";_Ho=require("node:fs/promises");ms();vw();gHo();pA();OHa="builtin:zapi",Gkt=class extends Error{static{r(this,"UnsupportedLegacyCliProviderConfigError")}providerId;constructor(t){super(`\u65E7 CLI Provider ${t} \u542B\u6709\u6B63\u5F0F Config \u5C1A\u4E0D\u80FD\u8868\u8FBE\u7684\u6267\u884C\u5B57\u6BB5`),this.name="UnsupportedLegacyCliProviderConfigError",this.providerId=t}};r(MHa,"resolveLegacyProviderApiType");r(NHa,"importLegacyCliPersonalProviderConfig");r(Jkt,"readLegacyCliPersonalProviderConfig");r(LHa,"importLegacyCliConfiguredDefault");r(FHa,"collectLegacyCliModelMembers");r(jHa,"mergeHeaders");r(BHa,"requiresUnsupportedNoAuthentication");r(UHa,"isFileNotFound");r(zHa,"isPositiveInteger")});async function tPn(e){return(await nPn(e)).providers}async function nPn(e,t){if(t)return{zcodeBuiltinRevision:t.revision,providers:t.providers.entries().flatMap(([s,a])=>{let l=a.access,u=a.builtinModelIds?.find(f=>f.trim())?.trim();return l?.type==="zhipu-account"&&l.mode==="individual-coding-plan"&&l.accountType&&u?[{family:l.accountType,modelId:u,providerId:s}]:[]})};let n=e[LV]?.trim();if(!n)throw new Error(`${LV} is required for login`);let o=new UO({bundledFilePath:n,watch:!1});try{let s=await o.read();return nPn(e,s)}finally{o.dispose()}}async function vHo(e,t){let n=(await tPn(t)).filter(o=>o.family===e);if(n.length!==1)throw new Error(`ZCode Built-in Config \u5FC5\u987B\u4E3A ${e} \u58F0\u660E\u552F\u4E00 Individual Coding Plan Provider`);return n[0]}function Yie(e){let t=e.trim();if(!t)throw new Error("Standalone Account Provider ID \u4E0D\u80FD\u4E3A\u7A7A");return`account-provider:${t}:identity`}function t3e(e){let t=e.providerId.trim(),n=e.accountIdentity.trim();if(!t)throw new Error("Standalone Account Provider ID \u4E0D\u80FD\u4E3A\u7A7A");if(!n)throw new Error("Standalone Account Identity \u4E0D\u80FD\u4E3A\u7A7A");return`account-provider:coding-plan:${t}:account:${encodeURIComponent(n)}:api-key`}function rPn(e){let t=e.trim();if(!t)throw new Error("Standalone Account Secret \u4E0D\u80FD\u4E3A\u7A7A");return`key-${(0,yHo.createHash)("sha256").update(t).digest("hex").slice(0,24)}`}async function oPn(e,t,n){let o=await nPn(t,n),s=o.providers,a=s.map(({providerId:b})=>Yie(b)),l=await e.loadMany(a),u=s.flatMap(({family:b,providerId:w})=>{let T=l[Yie(w)]?.trim();if(!T)return[];let I=t3e({providerId:w,accountIdentity:T});return[{accountIdentity:T,credentialKey:I,family:b,providerId:w}]}),f=await e.loadMany(u.map(({credentialKey:b})=>b)),g=new Map(u.map(b=>[b.providerId,b])),_=new uw(s.map(({family:b,providerId:w})=>{let T=g.get(w),I=T?f[T.credentialKey]?.trim():void 0;return!T||!I?[w,new Tk({access:new zj({entitled:!1})})]:[w,new Tk({access:new zj({entitled:!0})})]}));return pAe(o.zcodeBuiltinRevision,_)}async function bHo(e,t){return(await oPn(e,t)).providers.entries().some(([,n])=>n.access?.type==="zhipu-account"?n.access.entitled===!0:!1)}function SHo(e,t){return{shouldRefreshBeforeModelRequest(){return!0},async refreshBeforeModelRequest(n){n.abortSignal?.throwIfAborted();let o=n.providerId.trim(),s=n.accountAccess;if(!s||s.mode!=="individual-coding-plan")throw new Error(`Standalone Account Provider \u8BF7\u6C42\u8EAB\u4EFD\u65E0\u6548: ${o}`);let a=(await e.load(Yie(o)))?.trim();if(!a)throw new Error(`Standalone Account Provider \u51ED\u636E\u5DF2\u7ECF\u5931\u6548: ${o}`);let l=(await e.load(t3e({providerId:o,accountIdentity:a})))?.trim();if(!l)throw new Error(`Standalone Account Provider \u7F3A\u5C11\u8BF7\u6C42\u51ED\u636E: ${o}`);return{headersApplied:!0,requestAuth:{apiKey:l}}}}}var yHo,iPn=Y(()=>{"use strict";yHo=require("node:crypto");pA();hfe();r(tPn,"readStandaloneCodingPlanProviders");r(nPn,"readStandaloneCodingPlanCatalog");r(vHo,"resolveStandaloneCodingPlanProvider");r(Yie,"standaloneAccountIdentityCredentialKey");r(t3e,"standaloneAccountProviderCredentialKey");r(rPn,"createStandaloneAccountIdentityFromSecret");r(oPn,"readStandaloneAccountProviderConfigSnapshot");r(bHo,"hasStandaloneCodingPlanAccess");r(SHo,"createStandaloneProviderRuntimeHeadersPort")});function UK(e){if(e?.aborted)throw sPn(e)}async function wHo(e,t,n){if(!n){await e(t);return}await Promise.race([e(t),xHo(n)])}async function kHo(e){let t;try{return await Promise.race([e.callbackServer.waitForCallback(),new Promise((n,o)=>{t=setTimeout(()=>o(e.createTimeoutError()),e.timeoutMs)}),xHo(e.signal)])}finally{t&&clearTimeout(t)}}function xHo(e){return e?new Promise((t,n)=>{if(e.aborted){n(sPn(e));return}e.addEventListener("abort",()=>n(sPn(e)),{once:!0})}):new Promise(()=>{})}function sPn(e){return e.reason??new Error("Login cancelled.")}var THo=Y(()=>{"use strict";r(UK,"throwIfAborted");r(wHo,"sleepWithAbort");r(kHo,"waitForCallbackWithAbort");r(xHo,"rejectOnAbort");r(sPn,"abortReason")});async function WHa(e={}){let t=e.credentialStore??jM({env:e.env});return bHo(t,e.env??process.env)}async function VHa(e={}){if((e.env??process.env).ZCODE_CLI_OAUTH_CALLBACK_STDIN==="1"){let $zEnv=e.env??process.env;UK(e.abortSignal);let $zStore=e.credentialStore??jM({env:$zEnv}),$zHttp=e.httpClient??CHo($zEnv),$zPayload;try{$zPayload=JSON.parse(require("node:fs").readFileSync(0,"utf8"))}catch($zError){throw new m9("invalid_callback","Unable to read the Z.AI OAuth callback.",{cause:$zError})}if(!$zPayload||typeof $zPayload.callbackUrl!=="string"||typeof $zPayload.state!=="string")throw new m9("invalid_callback","The Z.AI OAuth callback payload is invalid.");let $zUrl;try{$zUrl=new URL($zPayload.callbackUrl)}catch($zError){throw new m9("invalid_callback","The Z.AI OAuth callback URL is invalid.",{cause:$zError})}if($zUrl.protocol!=="zcode:"||$zUrl.hostname!=="zai-auth"||$zUrl.pathname.replace(/\/+$/u,"")!=="/callback")throw new m9("invalid_callback","The Z.AI OAuth callback target is invalid.");let $zCode=$zUrl.searchParams.get("code")??$zUrl.searchParams.get("authCode"),$zState=$zUrl.searchParams.get("state");if(!$zCode||!$zState||$zState!==$zPayload.state)throw new m9("invalid_callback","The Z.AI OAuth callback state is invalid or expired.");let $zResponse=await $zHttp.request({maxResponseBytes:65536,body:new TextEncoder().encode(JSON.stringify({provider:"zai",code:$zCode,redirect_uri:"zcode://zai-auth/callback",state:$zState})),headers:{"Content-Type":"application/json"},method:"POST",trace:e.trace,url:"https://zcode.z.ai/api/v1/oauth/token"},e.abortSignal),$zText=new TextDecoder().decode($zResponse.body),$zEnvelope;try{$zEnvelope=JSON.parse($zText)}catch($zError){throw new m9("token_exchange_failed",$zResponse.status<200||$zResponse.status>=300?"OAuth HTTP error "+$zResponse.status+" (empty or non-JSON response)":"OAuth response is not valid JSON",{cause:$zError})}let $zMessage=typeof $zEnvelope?.msg==="string"&&$zEnvelope.msg.trim()?$zEnvelope.msg.trim():void 0;if($zResponse.status<200||$zResponse.status>=300)throw new m9("token_exchange_failed",$zMessage??"OAuth HTTP error "+$zResponse.status);if($zEnvelope?.code!==0)throw new m9("token_exchange_failed",$zMessage??"Z.AI token exchange failed.");let $zData=$zEnvelope.data,$zAccessToken=$zData?.zai?.access_token,$zJwtToken=$zData?.token,$zUser=$zData?.user;if(typeof $zAccessToken!=="string"||typeof $zJwtToken!=="string"||!$zUser||typeof $zUser!=="object")throw new m9("token_exchange_failed","Z.AI token response is missing credentials or user data.");UK(e.abortSignal);try{await $zStore.saveZaiLoginCredentials({accessToken:$zAccessToken,jwtToken:$zJwtToken,user:$zUser})}catch($zError){throw new m9("credential_write_failed","Login succeeded but writing credentials failed.",{cause:$zError})}let $zApiKey=await EHo({accessToken:$zAccessToken,env:$zEnv,httpClient:$zHttp,family:"zai",resolver:e.apiKeyResolver}),$zConfig;try{$zConfig=await aPn({accountIdentity:$zUser.user_id,apiKey:$zApiKey,credentialStore:$zStore,env:$zEnv,personalProviderConfigPath:e.personalProviderConfigPath,providerId:"zai"})}catch($zError){throw new m9("config_update_failed","Login succeeded but updating ZCode config failed.",{cause:$zError})}return{configPath:$zConfig.path,credentialsPath:$zStore.filePath,model:$zConfig.mainModel,providerId:"zai",user:$zUser}}let t=e.env??process.env,n=e.now??Date.now,o=e.sleep??XHa;UK(e.abortSignal);let s=e.pollToken??HZr(),a=e.credentialStore??jM({env:t}),l=KHa(e,t),u=await l.init({pollToken:s});await e.onAuthorizeUrl?.(u),UK(e.abortSignal);let f=e.noBrowser?void 0:await(e.openBrowser??Ydn)(u.authorize_url);f&&await e.onBrowserOpen?.(f);let g=await YHa({abortSignal:e.abortSignal,initData:u,now:n,oauthClient:l,onPollStatus:e.onPollStatus,pollToken:s,sleep:o,timeoutMs:e.timeoutMs??IHo});UK(e.abortSignal);try{await a.saveZaiLoginCredentials({accessToken:g.zai.access_token,jwtToken:g.token,user:g.user})}catch(w){throw new m9("credential_write_failed","Login succeeded but writing credentials failed.",{cause:w})}let _=await EHo({accessToken:g.zai.access_token,env:t,httpClient:e.httpClient,family:"zai",resolver:e.apiKeyResolver}),b;try{b=await aPn({accountIdentity:g.user.user_id,apiKey:_,credentialStore:a,env:t,personalProviderConfigPath:e.personalProviderConfigPath,providerId:"zai"})}catch(w){throw new m9("config_update_failed","Login succeeded but updating ZCode config failed.",{cause:w})}return{...f?{browser:f}:{},configPath:b.path,credentialsPath:a.filePath,model:b.mainModel,providerId:"zai",user:g.user}}async function HHa(e={}){let t=e.env??process.env;UK(e.abortSignal);let n=e.httpClient??CHo(t),o=e.state??MZr(),s=e.callbackServer??await YOe({callbackPath:qHa,state:o}),a=OZr({httpClient:n}),l=a.buildAuthorizeUrl({redirectUri:s.callbackUrl,state:o});await e.onAuthorizeUrl?.({authorize_url:l,callback_url:s.callbackUrl,state:o}),UK(e.abortSignal);let u=e.noBrowser?void 0:await(e.openBrowser??Ydn)(l);u&&await e.onBrowserOpen?.(u),UK(e.abortSignal);try{let f=await kHo({callbackServer:s,createTimeoutError:r(()=>new m9("auth_timeout","Authorization timed out. Please retry login."),"createTimeoutError"),signal:e.abortSignal,timeoutMs:e.timeoutMs??IHo}),g=await a.exchangeCode({code:f.code}),_=await EHo({accessToken:g.accessToken,env:t,httpClient:n,family:"bigmodel",resolver:e.apiKeyResolver}),b=e.credentialStore??jM({env:t}),w=rPn(_);await b.saveMany({[R1.activeProvider]:"bigmodel",[R1.bigmodelAccessToken]:g.accessToken,...g.refreshToken?{[R1.bigmodelRefreshToken]:g.refreshToken}:{},[R1.bigmodelUserInfo]:JSON.stringify({id:w})});let T=await aPn({accountIdentity:w,apiKey:_,credentialStore:b,env:t,personalProviderConfigPath:e.personalProviderConfigPath,providerId:"bigmodel"});return{...u?{browser:u}:{},configPath:T.path,model:T.mainModel,providerId:"bigmodel"}}finally{await s.close()}}async function GHa(e){let t=e.apiKey.trim();if(!t)throw new m9("config_update_failed","API key must not be empty.");let n=e.credentialStore??jM({env:e.env}),o=await aPn({accountIdentity:rPn(t),apiKey:t,credentialStore:n,env:e.env??process.env,personalProviderConfigPath:e.personalProviderConfigPath,providerId:e.providerId});return{configPath:o.path,model:o.mainModel,providerId:e.providerId}}async function JHa(e={}){let t=e.credentialStore??jM({env:e.env}),n=(await tPn(e.env??process.env)).map(({providerId:f})=>f),o=n.map(Yie),s=await t.loadMany(o),a=n.flatMap(f=>{let g=s[Yie(f)]?.trim();return g?[t3e({providerId:f,accountIdentity:g})]:[]}),l=[...Object.values(R1),...o,...a],u=await t.loadMany(l);return await t.deleteIfValues(Object.fromEntries(Object.entries(u).flatMap(([f,g])=>g===null?[]:[[f,g]]))),{credentialsPath:t.filePath}}async function aPn(e){let t=await vHo(e.providerId,e.env),n=t.providerId,o=t.modelId,s=t3e({providerId:n,accountIdentity:e.accountIdentity});await e.credentialStore.saveMany({[Yie(n)]:e.accountIdentity,[s]:e.apiKey});let a=e.personalProviderConfigPath??e.env[tte]?.trim()??(0,Kkt.join)((0,Kkt.dirname)(e.credentialStore.filePath),MXe),l=new Cpe({filePath:a,importLegacy:r(()=>Jkt({}),"importLegacy"),pollingIntervalMs:!1}),u=new Tpe({personalRepository:l});try{await u.saveConfiguredDefault({providerId:n,modelId:o})}finally{u.dispose(),l.dispose()}return{mainModel:`${n}/${o}`,path:a}}function KHa(e,t){let n=e.baseUrl??Bee(ZHa(t)).apiBaseUrl;if(e.httpClient)return Xdn({baseUrl:n,httpClient:e.httpClient});let o=K0({env:t});return Xdn({baseUrl:n,httpClient:s2e({env:t,proxyUrl:o.config.network.httpProxy,noProxy:o.config.network.noProxy,caCertFile:o.config.network.caCertFile,timeoutMs:o.config.network.timeout})})}function ZHa(e){return p1(e)}function CHo(e){let t=K0({env:e});return s2e({env:e,proxyUrl:t.config.network.httpProxy,noProxy:t.config.network.noProxy,caCertFile:t.config.network.caCertFile,timeoutMs:t.config.network.timeout})}async function EHo(e){return(e.resolver??$Zr({httpClient:e.httpClient??CHo(e.env)})).resolve({accessToken:e.accessToken,family:e.family})}async function YHa(e){let t=e.initData.expires_at*1e3,n=Math.min(e.now()+e.timeoutMs,t),o=Math.max($Ha,e.initData.poll_interval_sec*1e3);for(;e.now()<n;){UK(e.abortSignal);let s=await e.oauthClient.poll({flowId:e.initData.flow_id,pollToken:e.pollToken});if(await e.onPollStatus?.(s),s.status==="ready")return s;if(s.status==="failed")throw new m9("auth_failed","Authorization failed. Please retry login.");await wHo(e.sleep,Math.min(o,Math.max(0,n-e.now())),e.abortSignal)}throw new m9("auth_timeout","Authorization timed out. Please retry login.")}function XHa(e){return new Promise(t=>setTimeout(t,e))}var Kkt,IHo,$Ha,qHa,m9,AHo=Y(()=>{"use strict";adt();vw();a7();ms();hfe();ePn();Kkt=require("node:path");iPn();THo();IHo=300*1e3,$Ha=1e3,qHa="/oauth/callback/bigmodel";r(WHa,"hasConfiguredStandaloneCodingPlan");m9=class extends Error{static{r(this,"ZCodeCliLoginError")}code;constructor(t,n,o={}){super(n,o),this.name="ZCodeCliLoginError",this.code=t}};r(VHa,"loginZCodeCli");r(HHa,"loginBigmodelCodingPlan");r(GHa,"configureCodingPlanApiKey");r(JHa,"logoutZCodeCli");r(aPn,"persistStandaloneCodingPlanConnection");r(KHa,"createOAuthClient");r(ZHa,"resolveCliZCodeEndpointOrigin");r(CHo,"createDefaultHttpClient");r(EHo,"resolveCodingPlanApiKey");r(YHa,"pollUntilReady");r(XHa,"sleepMs")});async function OHo(e={}){let t=e.env??process.env,n=await rGa(nGa(t));return _Kt({appVersion:t[Ape]??e.appVersion,arch:(0,Bbe.arch)(),clientLanguage:eGa(),clientTimezone:tGa(),deviceMid:n,endpointOrigin:p1(t),osVersion:(0,Bbe.release)(),platform:process.platform,releaseChannel:YL(t),sourceTitle:e.sourceTitle??"cli"})}function eGa(){return Intl.DateTimeFormat().resolvedOptions().locale}function tGa(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function nGa(e){let t=e[QHa]?.trim()||(0,Bbe.homedir)();return(0,DHo.join)(t,".zcode","v2","telemetry-state.json")}async function rGa(e){let t=PHo.get(e);if(t)return t;try{let n=JSON.parse(await(0,RHo.readFile)(e,"utf8"));if(typeof n.deviceMid!="string")return;let o=n.deviceMid.trim();return!o||!/^[\x20-\x7e]+$/.test(o)?void 0:(PHo.set(e,o),o)}catch{return}}var RHo,Bbe,DHo,QHa,PHo,MHo=Y(()=>{"use strict";RHo=require("node:fs/promises"),Bbe=require("node:os"),DHo=require("node:path");ms();QHa="ZCODE_DATA_BASE_DIR",PHo=new Map;r(OHo,"createProviderEndpointRoutingSourceHeaders");r(eGa,"resolveClientLanguage");r(tGa,"resolveClientTimezone");r(nGa,"resolveTelemetryStateFile");r(rGa,"readExistingDeviceMid")});function n3e(e){let t=e.env??process.env,n=YAe(t,oGa),o=iGa(n,e.network),s=NHo.get(o);if(s)return s;let a=new dat({appVersion:e.appVersion,configUrl:n,httpClient:s2e({caCertFile:e.network.caCertFile,env:t,noProxy:e.network.noProxy,proxyUrl:e.network.httpProxy}),logger:e.logger.child({module:"adapters.model.provider_endpoint_routing"}),sourceHeaders:r(()=>OHo({appVersion:e.appVersion,env:t,sourceTitle:e.sourceTitle}),"sourceHeaders")});return NHo.set(o,a),a}function LHo(e){let t=e.env??process.env,n=K0({env:t,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:e.workingDirectory}),s=(e.loggerFactory??rB({env:t})).createLogger("zcode").child({module:"bootstrap.provider_endpoint_routing"});return n3e({appVersion:e.appVersion,env:t,logger:s,network:n.config.network,sourceTitle:e.sourceTitle})}function iGa(e,t){return JSON.stringify({caCertFile:t.caCertFile,configUrl:e,httpProxy:t.httpProxy,noProxy:t.noProxy})}var oGa,NHo,cPn=Y(()=>{"use strict";vw();a7();fOe();W0e();ms();MHo();oGa="/api/v1/agent/configs",NHo=new Map;r(n3e,"resolveProcessProviderEndpointRoutingPort");r(LHo,"createDefaultProviderEndpointRoutingPort");r(iGa,"routingRegistryKey")});async function Ykt(e,t={}){let n=ymr(e);if(!n)throw new Error("\u7F3A\u5C11\u8FDB\u7A0B Provider Registry \u7684 ZCode Built-in / Personal Config \u8DEF\u5F84");let o=new yee,s=t.standalone?t.standalone.credentialStore??jM({env:{...e}}):void 0,a,l=t.standalone?e[OXe]?.trim():void 0,u=new pZe({...n,...l?{zcodeBuiltinFilePath:l,zcodeBuiltinActiveFilePath:n.zcodeBuiltinFilePath,zcodeBuiltinRemote:{controlFilePath:(0,Zkt.join)((0,Zkt.dirname)(n.zcodeBuiltinFilePath),"zcode-builtin-refresh.json"),resolveEndpointKey:r(()=>p1(e),"resolveEndpointKey"),fetchRelease:r((_,b)=>xnr({endpointOrigin:_,signal:b,appVersion:HL,platform:aZe(),request:t.standalone?.request??globalThis.fetch}),"fetchRelease"),onRefreshResult:t.standalone?.onBuiltinRefreshResult}}:{},onZCodeBuiltinRefreshError:t.standalone?.onBuiltinRefreshError,accountSource:o,...s?{createAccountSource(_){return a=new GKe({configSource:_,async resolve({configRevision:b,configuredProviders:w}){let T=await oPn(s,e,{revision:b,providers:w});return{providers:T.providers,states:T.states??{}}}}),a.onDidRefreshError(({error:b})=>{try{t.standalone?.onAccountInitializationError?.(b)}catch{}}),a}}:{},...t.standalone?{importLegacy:r(()=>Jkt({...t.standalone?.legacyCliUserConfigFilePath?{filePath:t.standalone.legacyCliUserConfigFilePath}:{}}),"importLegacy")}:{}}),f=a?u.onDidCheckZCodeBuiltin(async()=>{let[_,b]=await Promise.all([u.configService.read(),a.read()]);_.zcodeBuiltinRevision!==b.basedOnZCodeBuiltinRevision&&await a.refresh("builtin-account-recovery")}):void 0,g=s?.onDidChange?.(async()=>{await a.refresh("standalone-credentials-changed"),await u.registryService.refresh("standalone-credentials-barrier")});try{await u.start();let _=u.registryService.getSnapshot(),b=new Tpe({personalRepository:u.personalRepository});try{let w=await b.read();return Object.freeze({accountSource:a??o,async syncAccountProviderConfig(T){if(a)throw new Error("Standalone Account \u7531\u672C\u8FDB\u7A0B\u7BA1\u7406\uFF0C\u4E0D\u63A5\u6536 Host \u8986\u76D6");let I=o.replace(T,"host-account-config");return await u.registryService.refresh("host-account-config"),I},dispose(){g?.(),f?.(),a?.dispose(),b.dispose(),u.dispose()},...s?{providerRuntimeHeadersPort:SHo(s,e)}:{},runtime:u,snapshot:_,modelSelectionConfigRepository:b,configuredDefaultModelSelection:w})}catch(w){throw g?.(),b.dispose(),w}}catch(_){throw g?.(),f?.(),a?.dispose(),u.dispose(),_}}function FHo(e){let t=e.revision.trim();if(!t)throw new Error("Account Config revision \u4E0D\u80FD\u4E3A\u7A7A");let n=e.basedOnZCodeBuiltinRevision.trim();if(!n)throw new Error("Account Config Built-in revision \u4E0D\u80FD\u4E3A\u7A7A");let o=Qtr(e.providers);for(let[s,a]of o.entries())if(cee(s)&&a.access?.type==="zhipu-account"&&a.access.entitled&&typeof e.states?.[s]?.current!="boolean")throw new Error(`Account State \u7F3A\u5C11 current: ${s}`);return Object.freeze({revision:t,basedOnZCodeBuiltinRevision:n,providers:o,...e.states?{states:e.states}:{}})}var Zkt,Xkt=Y(()=>{"use strict";pA();ms();Zkt=require("node:path");hfe();rpn();ePn();iPn();r(Ykt,"startProcessProviderRegistryRuntime");r(FHo,"parseProcessAccountProviderConfigSnapshot")});async function lPn(e){let t=(0,Ube.randomUUID)(),n=(0,Ube.createHash)("sha256").update(e.dbPath).digest("hex"),o=0,s=!1,a=r(async l=>{let u=vYe.parse({schemaVersion:1,attemptId:t,databaseId:n,databaseKind:"session",sequence:++o,...l});s||=u.phase==="failed",e.onProgress?.(u),await new Promise((f,g)=>{e.output.write(`${JSON.stringify({method:BR.storageStartup,params:u})}
|
|
15249
|
+
`)}var zkt,lHa,uHa,YVo=Y(()=>{"use strict";zkt=require("node:path");GAn();lHa=/^\/([^\s]+)(?:\s+([\s\S]*))?$/,uHa="init";r(ZVo,"resolveZCodeBuiltinPromptCommand");r(dHa,"parseBuiltinPromptCommandInvocation");r(pHa,"buildInitAgentsPrompt")});async function XVo(e){let t=await Zqt((0,BK.join)(e.storageRoot,"agents"));await Kqt((0,BK.join)(e.storageRoot,"v2","agents-state.json"));let n=[{path:(0,BK.join)(e.storageRoot,"agents"),source:"user"},{path:(0,BK.join)(e.workingDirectory,".zcode","agents"),source:"project"}],o=[];for(let l of t.failures)o.push({code:"agent_read_failed",message:"Subagent Markdown migration failed; original file preserved",path:l.path}),e.logger?.warn("Subagent Markdown migration failed",{module:"bootstrap.subagents",path:l.path,error:String(l.error)});let s=vHa(e.storageRoot),a=[];for(let l of n)for(let u of eHo(l.path)){let f=(0,R8.readFileSync)(u,"utf8"),g=qvn({content:f,path:u,source:l.source});if(g.diagnostic&&(o.push(g.diagnostic),e.logger?.warn("Agent profile diagnostic",{code:g.diagnostic.code,message:g.diagnostic.message,module:"bootstrap.subagents",path:u})),g.profile){let _=mHa(g.profile);if(SHa(_,s.disabledAgentIds))continue;a.push(_)}}return e.logger?.debug("Agent profiles loaded",{diagnosticCount:o.length,module:"bootstrap.subagents",profileCount:a.length}),{builtInModelSelectionOverrides:s.builtInModelSelectionOverrides,pluginAgentModelSelectionOverrides:s.pluginAgentModelSelectionOverrides,diagnostics:o,profiles:a}}function mHa(e){if(e.source!=="project"||e.permissionMode===void 0)return e;let{permissionMode:t,...n}=e;return n}function QVo(e){let t=[],n=[],o=new Set([...fHa,...e.reservedProfileNames??[]]);for(let l of e.plugins){if(!l.enabled)continue;let u=l.components.find(f=>f.kind==="agent")?.items??[];for(let f of u){let g=(0,BK.join)(l.rootPath,"agents",`${f.name}.md`),_=hHa({filePath:g,logger:e.logger,plugin:l});_.diagnostic&&t.push(_.diagnostic),_.parsed&&n.push(_.parsed)}}let s=yHa(n),a=[];for(let l of n){let u=e.modelSelectionOverrides?.[Wqt(l.plugin.id,l.bareName)],f={...gHa(l),...u?{modelSelection:u}:{}};a.push(f);let g=l.bareName.trim();s.get(g)===1&&!o.has(g)?a.push({...f,name:g}):o.has(g)?t.push({code:"agent_ambiguous_name",message:`Plugin agent bare name conflicts with an existing profile; use ${f.name}: ${g}`,path:f.path}):(s.get(g)??0)>1&&t.push({code:"agent_ambiguous_name",message:`Plugin agent bare name is ambiguous; use ${f.name}: ${g}`,path:f.path})}return e.logger?.debug("Plugin agent profiles loaded",{diagnosticCount:t.length,module:"bootstrap.subagents",profileCount:a.length}),{builtInModelSelectionOverrides:{},pluginAgentModelSelectionOverrides:{},diagnostics:t,profiles:a}}function hHa(e){try{let t=(0,R8.readFileSync)(e.filePath,"utf8"),n=qvn({content:t,path:e.filePath,source:"user"});return n.diagnostic&&(e.logger?.warn("Plugin agent profile diagnostic",{code:n.diagnostic.code,message:n.diagnostic.message,module:"bootstrap.subagents",path:e.filePath,pluginId:e.plugin.id}),!n.profile)?{diagnostic:n.diagnostic}:n.profile?{...n.diagnostic?{diagnostic:n.diagnostic}:{},parsed:{bareName:n.profile.name,plugin:e.plugin,profile:n.profile}}:{}}catch(t){return{diagnostic:{code:"agent_read_failed",message:t instanceof Error?t.message:`Failed to read plugin agent: ${e.filePath}`,path:e.filePath}}}}function gHa(e){return{...e.profile,name:`${e.plugin.name}:${e.bareName}`}}function _Ha(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yHa(e){let t=new Map;for(let n of e){let o=n.bareName.trim();t.set(o,(t.get(o)??0)+1)}return t}function vHa(e){try{let t=(0,R8.readFileSync)((0,BK.join)(e,"v2","agents-state.json"),"utf8"),n=JSON.parse(t);return{pluginAgentModelSelectionOverrides:eAe(n.pluginAgentModelSelectionOverrides),builtInModelSelectionOverrides:bHa(n.builtInModelSelectionOverrides),disabledAgentIds:new Set(Array.isArray(n.disabledAgentIds)?n.disabledAgentIds.filter(o=>typeof o=="string"&&o.trim().length>0):[])}}catch{return{builtInModelSelectionOverrides:{},pluginAgentModelSelectionOverrides:{},disabledAgentIds:new Set}}}function bHa(e){let t={},n=_Ha(e)?e:{},o=Pu.safeParse(n["general-purpose"]),s=Pu.safeParse(n.Explore);return o.success&&(t["general-purpose"]=o.data),s.success&&(t.Explore=s.data),t}function SHa(e,t){return e.source!=="user"?!1:t.has(Vqt({name:e.name,scope:"user",source:"user"}))}function eHo(e){if(!(0,R8.existsSync)(e))return[];if(!(0,R8.statSync)(e).isDirectory())return[];let t=[];for(let n of(0,R8.readdirSync)(e,{withFileTypes:!0})){let o=(0,BK.join)(e,n.name);if(n.isDirectory()){t.push(...eHo(o));continue}n.isFile()&&/\.(md|markdown)$/iu.test(n.name)&&t.push(o)}return t.sort((n,o)=>n.localeCompare(o))}var R8,BK,fHa,tHo=Y(()=>{"use strict";R8=require("node:fs"),BK=require("node:path");bz();Y0();ms();fHa=new Set(["general-purpose","Explore"]);r(XVo,"loadZCodeAgentProfiles");r(mHa,"sanitizeProjectAgentProfile");r(QVo,"loadPluginAgentProfiles");r(hHa,"parsePluginAgentProfile");r(gHa,"namespacePluginAgentProfile");r(_Ha,"isRecord");r(yHa,"countBareProfileNames");r(vHa,"readAgentState");r(bHa,"normalizeBuiltInSelectionOverrides");r(SHa,"isDisabledUserProfile");r(eHo,"listMarkdownFiles")});function nHo(){let e=Zie(process.platform),t=Zie((0,$kt.arch)()),n=Zie((0,$kt.release)());return{...e&&t?{"X-Platform":`${e}-${t}`}:{},"X-Os-Category":kHa(process.platform),...n?{"X-Os-Version":n}:{}}}function Zie(e){let t=e?.trim();if(!(!t||!wHa.test(t)))return t}function kHa(e){switch(e){case"darwin":return"macos";case"win32":return"windows";default:return"linux"}}var $kt,wHa,rHo=Y(()=>{"use strict";$kt=require("node:os"),wHa=/^[\x20-\x7e]+$/;r(nHo,"createRuntimePlatformHeaders");r(Zie,"normalizePrintableHeaderValue");r(kHa,"normalizeOsCategory")});function oHo(e=process.env,t={}){let n=THa(t.network);return{defaultHeaders:iHo(e,t),codingPlanSignature:xHa(e,t),env:e,...n?{network:n}:{},...t.endpointRoutingPort?{endpointRoutingPort:t.endpointRoutingPort}:{}}}function xHa(e,t){return{configUrl:YAe(e,JJt),headers:iHo(e,t)}}function THa(e){if(!(!e?.caCertFile&&!e?.httpProxy&&!e?.noProxy))return{...e.caCertFile?{caCertFile:e.caCertFile}:{},...e.httpProxy?{httpProxy:e.httpProxy}:{},...e.noProxy?{noProxy:e.noProxy}:{}}}function iHo(e,t={}){let n=t.sourceTitle??CHa(),o=IHa(e,t),s=Zie(Intl.DateTimeFormat().resolvedOptions().locale),a=Zie(Intl.DateTimeFormat().resolvedOptions().timeZone);return{"HTTP-Referer":p1(e),"User-Agent":`ZCode/${o??"unknown"}`,...o?{"X-ZCode-App-Version":o}:{},"X-Title":`Z Code@${n}`,"X-Release-Channel":YL(e),"X-Client-Language":s??"unknown","X-Client-Timezone":a??"unknown","X-ZCode-Agent":"glm",...nHo()}}function IHa(e,t){return Zie(e[Ape]??t.appVersion)}function CHa(){return process.argv.includes("app-server")||process.argv.includes("agent-server")?"electron":"cli"}var sHo=Y(()=>{"use strict";ms();rHo();r(oHo,"createRuntimeAiSdkModelExecutionConfig");r(xHa,"createCodingPlanSignatureConfig");r(THa,"normalizeAiSdkNetworkConfig");r(iHo,"buildCliZCodeSourceHeaders");r(IHa,"resolveAppVersionForHeaders");r(CHa,"detectDefaultProviderSourceTitle")});var qkt,aHo=Y(()=>{"use strict";NK();qkt=class{static{r(this,"ApiProviderModelRuntime")}#e;#t;#n=!1;constructor(t){this.#e=t.registry,this.#t=t.modelAdapter}modelFactory=r(t=>{if(!this.#n)throw new Error("ApiProviderModelRuntime \u5FC5\u987B\u5148 start() \u518D\u521B\u5EFA Model");let n=this.#e.validateSelection(t.selection);if(!n.ok)throw $En(n);let o=t.selection.providerId,s=t.selection.modelId,a=this.#e.getProvider(o);if(!a)throw new Error("Registry Selection \u6821\u9A8C\u4E0E Provider \u7D22\u5F15\u7ED3\u679C\u4E0D\u4E00\u81F4");let l=this.#e.getModel(o,s);if(!l)throw new Error("Registry Selection \u6821\u9A8C\u4E0E Model \u7D22\u5F15\u7ED3\u679C\u4E0D\u4E00\u81F4");return this.#r(a,l,t)},"modelFactory");start(){this.#n||(this.#n=!0)}dispose(){this.#n=!1}#r(t,n,o){let s=n.config,a=o.selection.options.reasoningLevel;return this.#t.createModel({providerId:t.providerId,modelId:n.modelId,providerConfig:t.config,modelConfig:s,...t.config.access.type==="zhipu-account"&&t.config.access.mode==="off-peak"?{requestDependencies:{requestAuth:{source:o.requestDependencies?.requestAuth?.source}}}:{},options:{reasoningLevel:a}})}}});function Wkt(e){let t=e.options.pluginStorageRoot??bbe(e.cliStorageRoot),n=wct({config:e.configResult.config.plugins,env:e.env??process.env,officialPluginRoots:Aje({extraRoots:e.options.officialPluginRoots,logger:e.logger,storageRoot:t,suppressedBuiltins:new Set(e.configResult.config.plugins.suppressedBuiltins)}),officialPluginsEnabledByDefault:$wt,storageRoot:t,workingDirectory:e.workingDirectory});return e.startupTimer.mark("ZCode plugins resolved",{context:{commandRootCount:n.commandRoots.length,diagnosticCount:n.diagnostics.length,enabledPluginCount:n.plugins.filter(o=>o.enabled).length,hookCount:Object.values(n.hooks??{}).reduce((o,s)=>o+(s??[]).reduce((a,l)=>a+l.hooks.length,0),0),mcpServerCount:Object.keys(n.mcpServers).length,pluginCount:n.plugins.length,pluginStorageRoot:t,skillRootCount:n.skillRoots.length},event:"bootstrap.app.startup.plugins.completed",stage:"resolve_plugins"}),n}function cHo(e){e.startupTimer.start("ZCode app startup started",{context:{hasInjectedModelAdapter:e.hasInjectedModelAdapter,resume:e.resume},event:"bootstrap.app.startup.started",stage:"start"})}function lHo(e){e.startupTimer.mark("ZCode app configuration loaded",{context:{configSourceEnv:e.configResult.sources.env,configSourceProject:e.configResult.sources.project.loaded,configSourceUser:e.configResult.sources.user.loaded},event:"bootstrap.app.startup.config.completed",stage:"load_config"})}function uHo(e){e.startupTimer.mark("ZCode storage adapters initialized",{context:{hasInjectedArtifactStore:e.hasInjectedArtifactStore,hasInjectedSessionStore:e.hasInjectedSessionStore,cliStorageRoot:e.cliStorageRoot,storageRoot:e.storageRoot},event:"bootstrap.app.startup.storage.completed",stage:"initialize_storage"})}function dHo(e){e.startupTimer.mark("ZCode MCP adapter initialized",{context:{hasInjectedMcpPort:e.hasInjectedMcpPort,mcpEnabled:e.mcpEnabled,mcpServerCount:Object.keys(e.configuredMcpServers).length,trustedMcpServerCount:e.trustedMcpServerCount},event:"bootstrap.app.startup.mcp.completed",stage:"initialize_mcp"})}function pHo(e){e.startupTimer.mark("ZCode runtime constructed",{context:{hasInjectedModelAdapter:e.hasInjectedModelAdapter,sessionId:e.sessionId},event:"bootstrap.app.startup.runtime.completed",stage:"create_runtime"})}function fHo(e){e.startupTimer.complete("ZCode app startup completed",{context:{sessionId:e.sessionId,workingDirectory:e.workingDirectory},event:"bootstrap.app.startup.completed",stage:"total"})}function mHo(e){e.logger.debug("Runtime config resolved",{mode:e.runtimeConfig.mode,module:"bootstrap",permissionAllowedToolCount:e.configResult.config.permission.allowedTools.length,permissionDisallowedToolCount:e.configResult.config.permission.disallowedTools.length,permissionSourceEnv:e.configResult.sources.env,permissionSourceUserConfig:e.configResult.sources.user.loaded})}var JAn=Y(()=>{"use strict";GOe();qwt();MK();l9();r(Wkt,"resolveStartupPlugins");r(cHo,"startAppStartup");r(lHo,"markConfigurationLoaded");r(uHo,"markStorageAdaptersInitialized");r(dHo,"markMcpAdapterInitialized");r(pHo,"markRuntimeConstructed");r(fHo,"completeAppStartup");r(mHo,"debugRuntimeConfigResolved")});function EHa(e,t,n){let o=e.indexOf(","),s=e.slice(0,5).toLowerCase()==="data:"&&o>=0?e.slice(5,o).split(";"):[],a=(s.shift()?.trim()||t).split(";",1)[0].toLowerCase(),l=o>=0?e.slice(o+1):"";if(s.at(-1)?.trim().toLowerCase()!=="base64"||!/^[A-Za-z0-9+/]*={0,2}$/u.test(l)||l.length%4!==0)throw new Error("fault.attachment.previewArtifactInvalid");if(!a.startsWith("image/")&&!a.startsWith("video/")&&a!=="application/pdf")throw new Error("fault.attachment.previewNotMedia");let u=Buffer.from(l,"base64");if(u.byteLength>n)throw new Error("fault.attachment.previewTooLarge");return{bytes:u,mediaType:a}}async function KAn(e){if(!e?.providerRegistry)throw new Error("createZCodeApp requires a Provider Registry");let t=I4(),n=e.version??"0.0.0",o=e.sessionId??Ov(),s=e.traceContext??vA({sessionId:o}),a=(0,A4.resolve)(e.runtimeConfig?.workingDirectory??process.cwd()),l=Jzo(K0({env:e.env,projectConfigPath:e.projectConfigPath,workingDirectory:a,workspaceIdentity:e.runtimeConfig?.memory?.workspaceIdentity,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,cliOverrides:Gzo(e)}),e),u=e.loggerFactory??rB({env:e.env}),f=u.createLogger("zcode").child({...Qa(s),module:"bootstrap"}),g=new DK(f,{...Qa(s),module:"bootstrap",startupKind:"zcode_app"},t);cHo({hasInjectedModelAdapter:e.modelAdapter!==void 0,resume:e.resume===!0,startupTimer:g}),lHo({configResult:l,startupTimer:g});let _=u.createLogger("zcode").child({...Qa(s),module:"adapters.model"}),b=Bzo({owner:e.telemetryOwner,sessionId:o}),w,T,I;try{let E=zg(l.config.storage.dir),R=k8(E),L=Zzo(R,OCe(e.env??process.env)==="development"),U=await XVo({logger:f,storageRoot:E,workingDirectory:a}),B=U.profiles,z=Wkt({cliStorageRoot:R,configResult:l,env:e.env,logger:f,options:e,startupTimer:g,workingDirectory:a}),$=ekt({cliStorageRoot:R,logger:f}),J=QVo({logger:f,plugins:z.plugins,reservedProfileNames:B.map(kn=>kn.name),modelSelectionOverrides:U.pluginAgentModelSelectionOverrides}).profiles,q=s$o(z),ie=MVo({pluginOutcome:z,workingDirectory:a}),ae=[...B,...J],Ce=e.sessionStore===void 0,pe=e.sessionStore??await n7o(l,g),ze=Qzo(pe),rt=Sbe(a),Pe=e.runtimeConfig?.mode?void 0:e7o(ze,rt),{configuredMcpServers:Tt,runtimeConfig:Ye,untrustedProjectMcpServers:Fe}=T$o({cliStorageRoot:R,configResult:l,options:e,persistedMode:Pe,pluginHooks:z.hooks,pluginMcpServers:z.mcpServers,builtInMcpServers:ie,pluginRuntimeFeatures:q,builtInSubagentModelSelectionOverrides:U.builtInModelSelectionOverrides,subagentOutputRootDir:(0,A4.join)(R,"agents"),subagentProfiles:ae,storageRoot:E,workingDirectory:a,workspaceIdentity:e.runtimeConfig?.memory?.workspaceIdentity}),St=e.browserControlPort;St&&q.browserUse===!0&&Ye.mcp?.servers?.node_repl?.type==="stdio"&&(w=e.nodeReplBrowserBroker??(T=Nkt({browserControlPort:St,logger:f,platform:e.platform})),Tt=zAn(Tt,w),Ye.mcp={...Ye.mcp,servers:zAn(Ye.mcp.servers??{},w)}),g.mark("ZCode runtime configuration resolved",{context:I$o(Ye,a),event:"bootstrap.app.startup.runtime_config.completed",stage:"resolve_runtime_config"});let kt=Uye(z.plugins);Ye.pluginReferenceCatalog=kt;let st,$e=K$o({appVersion:n,logger:f,projectConfigPath:e.projectConfigPath,policy:e.workspaceHookPolicy,policyProvider:e.workspaceHookPolicyProvider,reviewHost:e.workspaceHookReviewHost,workspaceHookTrustEnabled:e.workspaceHookTrustEnabled,runtimeRoot:l.sources.project.workspaceHookRuntimeRoot??{enabled:Ye.hooks?.enabled===!0,timeoutMs:Ye.hooks?.timeoutMs??6e4,maxOutputBytes:Ye.hooks?.maxOutputBytes??32768},sessionId:o,snapshot:l.sources.project.workspaceHookSnapshot,userConfigPath:l.sources.user.path,workingDirectory:a,...e.workspaceHookReviewHost?{emitReviewEvent:r(async kn=>{if(!st)throw new Error("ZCode runtime is not initialized yet.");await st.appendEvent(om(kn.type,o,kn.payload,{traceId:s.traceId}),s)},"emitReviewEvent"),emitAdmissionEvent:r(async kn=>{if(!st)throw new Error("ZCode runtime is not initialized yet.");await st.appendEvent(om(kn.type,o,kn.payload,{traceId:s.traceId}),s)},"emitAdmissionEvent")}:{}}),jt=new UM({allowedTools:new Set(l.config.permission.allowedTools),autoApproveHighRisk:l.config.permission.autoApproveHighRisk,disallowedTools:new Set(l.config.permission.disallowedTools),allowMediumRiskInAutoMode:l.config.permission.allowMediumRiskInAuto}),Je=e.inputHistoryStore??Xzo(pe),Xe=e.artifactStore??yxr({imageCacheRootDir:(0,A4.join)(E,"cli","image-cache"),pdfCacheRootDir:(0,A4.join)(E,"cli","pdf-cache"),rootDir:(0,A4.join)(E,"cli","artifacts"),videoCacheRootDir:(0,A4.join)(E,"cli","video-cache")}),_t=e.imageProcessorPort??y3r(),Dt=Hzo(e.env??process.env),gn=e.sessionMailboxPort??(Dt?F2o({rootDir:zg((e.env??process.env).ZCODE_MAILBOX_ROOT??"~/.zcode/mailbox")}):void 0);uHo({cliStorageRoot:R,hasInjectedArtifactStore:e.artifactStore!==void 0,hasInjectedSessionStore:e.sessionStore!==void 0,startupTimer:g,storageRoot:E});let cn=e.mcpPort??(Ye.mcp?.enabled===!1?void 0:e.mcpPortFactory?.({workingDirectory:a})??Amn({clientVersion:n,env:e.env,logger:f,network:{httpProxy:l.config.network.httpProxy,noProxy:l.config.network.noProxy,caCertFile:l.config.network.caCertFile},workingDirectory:a})),Fn=e.mcpPort===void 0&&cn!==void 0,on=e.executionPort??sne({onToolExecResource:e.onToolExecResource,network:{httpProxy:l.config.network.httpProxy,noProxy:l.config.network.noProxy,caCertFile:l.config.network.caCertFile},outputRootDir:(0,A4.join)(E,"cli","exec"),processEnv:e.env??process.env}),dt=e.executionPort===void 0,we=e.pdfDocumentPort??S3r({executionPort:on}),_e=e.fileSystemPort??hH(),Pt=e.httpClientPort??C3({env:e.env??process.env,timeoutMs:l.config.network.timeout,proxyUrl:l.config.network.httpProxy,noProxy:l.config.network.noProxy,caCertFile:l.config.network.caCertFile}),ut=e.providerEndpointRoutingPort;dHo({configuredMcpServers:Tt,hasInjectedMcpPort:e.mcpPort!==void 0,mcpEnabled:Ye.mcp?.enabled!==!1,startupTimer:g,trustedMcpServerCount:Object.keys(Ye.mcp?.servers??{}).length}),mHo({configResult:l,logger:f,runtimeConfig:Ye});let Mn=r(()=>{if(!st)throw new Error("ZCode runtime is not initialized yet.");return st},"getRuntime"),Dr=!1,gr=r(()=>Qte({env:e.env??process.env,platform:e.platform??process.platform}).selection,"resolveDefaultShellSelection"),eo,to=r(()=>(eo??=(async()=>await e.resolveInitialBashShellSelection?.()??gr())(),eo),"resolveInitialShellSelection"),oo=r(async()=>{Mn().initializeSessionShellEnvironmentIfNeeded(await to())},"initializeSessionShellEnvironment"),ro=r(async()=>{let kn=e.providerRegistry,Nn;try{Nn=await t7o(pe,o)}catch(Vo){f.warn("Session model selection restore failed",{error:Vo instanceof Error?Vo.message:String(Vo),event:"session.model_selection.restore_failed",sessionId:o})}let Ur=Nn&&kn.validateSelection(Nn);Mn().$zRestoredSessionModel={selection:Nn,registry:kn};return Mn().setSessionModelSelection(Ur?.ok?Nn:void 0),Nn},"restorePersistedModelSelection"),Ji=r(async kn=>{let Nn=Mn(),Ur=kn?.onEvent?Nn.subscribeEvents({onSessionEvent:kn.onEvent}):void 0;try{let Vo=kn?.traceContext??s,qe=await ro();await oo();let Kt=await Nn.resumeFromStore({...kn?.abortSignal?{abortSignal:kn.abortSignal}:{},modeOverride:e.runtimeConfig?.mode,persistedMessages:kn?.persistedMessages,traceContext:Vo});return await Nn.activatePausedTargetAfterResume(Vo),Dr=!0,{...Kt,modelSelection:qe}}finally{Ur?.()}},"resumeFromStore"),pi=r(async(kn,Nn)=>{!e.resume||Dr||(await Ji({...Nn?{abortSignal:Nn}:{},traceContext:kn??s}),Dr=!0)},"prepareResume"),Wi=r(async kn=>{await oo(),await pi(kn?.traceContext,kn?.abortSignal)},"prepareUserExecutionBoundary"),Ii=oHo(e.env,{appVersion:n,endpointRoutingPort:ut,network:l.config.network,sourceTitle:e.sourceTitle}),Rs=e.modelAdapter??Ewt({env:e.env,logger:_,modelIoDir:L,modelIoFullRetentionEnabled:e.modelIoFullRetentionEnabled,executionConfig:Ii,statusSink:b.statusSink,streamIdleTimeoutMs:l.config.modelStream.idleTimeoutMs});e.modelAdapter&&b.statusSink&&Rs.addStatusSink(b.statusSink);let ht=zqo();Rs.setModelIoFullRetentionEnabled(e.modelIoFullRetentionEnabled??!1),I=new qkt({registry:e.providerRegistry,modelAdapter:Rs}),I.start();let mr=I.modelFactory,mi=F9o({agentTelemetry:b.agentExecution,appOptions:e,appVersion:n,artifactStore:Xe,configResult:l,fileSystemPort:_e,httpClientPort:Pt,imageProcessorPort:_t,pdfDocumentPort:we,logger:f,mcpPort:cn,modelFactory:mr,permissionService:jt,prepareUserExecutionBoundary:Wi,getRuntime:Mn,runtimeConfig:Ye,sessionId:o,sessionStore:pe,storageRoot:E,traceContext:s,workingDirectory:a}),Ar=qje(pe,f),hi=Ar===void 0?void 0:mVo({concurrency:ht,createActorRuntime:r(({persona:kn,pinnedModel:Nn,runSubagentModel:Ur,sessionId:Vo,submitPort:qe,submitProfile:Kt,escalatePort:Jt,modelRequestAdmission:en})=>lkt({childSessionId:Vo,configOverrides:{workflowActor:{...kn.name===void 0?{}:{name:kn.name},...kn.system===void 0?{}:{persona:kn.system}},...IVo(),...xVo({parentSelection:Mn().getSessionModelSelection(),...Ur===void 0?{}:{runSelection:Ur}},Nn).configOverrides},deps:{agentTelemetry:b.agentExecution,appOptions:e,appVersion:n,artifactStore:Xe,configResult:l,fileSystemPort:_e,httpClientPort:Pt,imageProcessorPort:_t,logger:f,mcpPort:cn,modelFactory:mr,permissionService:jt,runtime:Mn(),runtimeConfig:Ye,sessionId:o,sessionStore:pe,storageRoot:E,workingDirectory:a},request:{opts:{}},traceContext:s,...Kt.kind==="untyped"?{}:{workflowSubmitPort:qe},...Kt.kind==="mono"?{workflowSubmitSchema:{...Kt.schema}}:{},workflowEscalatePort:Jt,...en===void 0?{}:{modelRequestAdmission:en}}),"createActorRuntime"),actorTranscriptStore:pe,artifactStore:Xe,executionPort:on,fileSystemPort:_e,journal:Ar,logger:f,onRunEvent:wVo({getRuntime:Mn,logger:f,sessionId:o}),parentSessionId:o,registerResidencyBlockingWork:r(kn=>{Mn().trackResidencyBlockingWork(kn)},"registerResidencyBlockingWork"),resolveLaunchInputId:r(kn=>{let Nn=Mn().getActiveTurnInfo();return Nn!==void 0&&Nn.turnId===kn.turnId?Nn.inputId:void 0},"resolveLaunchInputId"),...sAn(pe)?{taskLinkStore:pe}:{}}),Js=yVo({executionPort:on,fileSystemPort:_e,logger:f}),qa=bVo({registry:e.providerRegistry,currentSelection:r(()=>Mn().getSessionModelSelection(),"currentSelection")});st=new V2(o,Ye,{agentTelemetry:b.agentExecution,modelRequestAdmission:ht.observer(),eventStore:e.eventStore??zz(),sessionStore:pe,sessionMailboxPort:gn,logger:f,executionPort:on,workspaceHookAdmission:$e?.admission,workspaceHookSnapshot:$e?.snapshot,browserControlPort:St,fileSystemPort:_e,httpClientPort:Pt,imageProcessorPort:_t,pdfDocumentPort:we,artifactStore:Xe,contextSourcePort:e.contextSourcePort??bme({env:e.env}),skillPort:l.config.features.skill&&l.config.skills.enabled?e.skillPort??mG({extraRoots:l.config.skills.roots,extraResolvedRoots:[...z.skillRoots,...$],disabledPaths:[...x8(l.config.skillOverrides),...Ye.dynamicWorkflowEnabled===!1?M$o($):[]]}):void 0,mcpPort:cn,eventSink:e.eventSink,modelFactory:mr,modelIoDir:L,providerRuntimeHeadersPort:e.providerRuntimeHeadersPort,resolveEffectiveModelSelection:e.resolveEffectiveModelSelection,isRemoteWorkspace:r(()=>YJt(Ye.memory?.workspaceIdentity??""),"isRemoteWorkspace"),permissionBroker:e.permissionBroker,permissionService:jt,workflowPort:mi.workflowPort,dynamicWorkflowRunPort:hi,dynamicWorkflowSnippetPort:Js,modelCatalogPort:qa,automationPort:e.automationPort,offPeakPort:e.offPeakPort,appVersion:n,traceContext:s}),pHo({hasInjectedModelAdapter:e.modelAdapter!==void 0,sessionId:o,startupTimer:g}),fHo({sessionId:o,startupTimer:g,workingDirectory:a}),Rwt(u,f);let li=d7o({artifactStore:Xe,customCommandPromptResolver:r(async(kn,Nn)=>{let Ur=ZVo(kn,{dynamicWorkflowEnabled:Ye.dynamicWorkflowEnabled,workingDirectory:a});return Ur!==void 0?Ur:await HVo(kn,{env:e.env,executionPort:on,logger:f,projectConfigPath:e.projectConfigPath,sessionId:o,signal:Nn?.abortSignal,skipUserConfig:e.skipUserConfig,traceContext:Nn?.traceContext??s,userConfigPath:e.userConfigPath,workingDirectory:a})},"customCommandPromptResolver"),inputHistoryStore:Je,logger:f,prepareUserExecutionBoundary:Wi,runtime:st,sessionId:o,traceContext:s}),oa=i7o({agentTelemetry:b.agentExecution,appOptions:e,appVersion:n,artifactStore:Xe,cliStorageRoot:R,configResult:l,eventSink:e.eventSink,imageProcessorPort:_t,pdfDocumentPort:we,logger:f,mcpPort:cn,modelFactory:mr,permissionService:jt,prepareUserExecutionBoundary:Wi,runtime:st,runtimeConfig:Ye,sessionId:o,sessionStore:pe,storageRoot:E,traceContext:s,workingDirectory:a}),Fs=S$o({...hi===void 0?{}:{closeDynamicWorkflowRuns:r(()=>hi.close(),"closeDynamicWorkflowRuns")},configResult:l,configuredMcpServers:Tt,...e.configuredDefaultModelSelection?{configuredDefaultModelSelection:e.configuredDefaultModelSelection}:{},executionPort:on,localSettingStore:ze,logger:f,loggerFactory:u,mcpPort:cn,ownsExecutionPort:dt,ownsMcpPort:Fn,closeNodeReplBrowserBroker:r(async()=>{await T?.close()},"closeNodeReplBrowserBroker"),ownsSessionStore:Ce,prepareUserExecutionBoundary:Wi,prepareResume:pi,projectID:rt,providerRegistry:e.providerRegistry,resolveUiLocale:r(kn=>xEn(kn,e),"resolveUiLocale"),runtime:st,sessionId:o,sessionStore:pe,traceContext:s,untrustedProjectMcpServers:Fe,workingDirectory:a}),Qo=Fs.close,gi=r(async kn=>{let Nn=kn.ref,Ur=kn.mime,Vo;if(kn.messageId&&kn.attachmentIndex!==void 0){let Kt=(await pe.messageWithParts({sessionID:o,messageID:kn.messageId}))?.parts.filter(Jt=>Jt.type==="file")[kn.attachmentIndex];Kt?.type==="file"&&(Ur=Kt.mime,Vo=Kt.metadata?.artifactUri??(Kt.url.startsWith("zcode-artifact://")?Kt.url:void 0),Nn=Vo??(Kt.url.startsWith("data:")?kn.ref:Kt.url))}return{ref:Nn,mediaType:Ur,...Vo?{artifactUri:Vo}:{}}},"resolvePromptAttachment");return{sessionId:o,traceId:s.traceId,runtime:st,respondWorkspaceHookReview:r(kn=>$e?.respond({sessionId:kn.sessionId,taskId:kn.taskId,runId:kn.runId,...kn.remoteSessionId?{remoteSessionId:kn.remoteSessionId}:{},workspaceIdentity:kn.workspaceIdentity,bundleDigest:kn.bundleDigest,reviewFlowId:kn.reviewFlowId,generation:kn.generation,interactionId:kn.interactionId},kn.decision)??Promise.resolve({accepted:!1,reasonCode:"workspace_hooks_require_trust_capable_host"}),"respondWorkspaceHookReview"),toggleWorkspaceHookReviewItem:r(kn=>$e?.toggle({sessionId:kn.sessionId,taskId:kn.taskId,runId:kn.runId,...kn.remoteSessionId?{remoteSessionId:kn.remoteSessionId}:{},workspaceIdentity:kn.workspaceIdentity,bundleDigest:kn.bundleDigest,reviewFlowId:kn.reviewFlowId,generation:kn.generation,interactionId:kn.interactionId},kn.reviewItemId,kn.enabled)??Promise.resolve({accepted:!1,reasonCode:"workspace_hooks_require_trust_capable_host"}),"toggleWorkspaceHookReviewItem"),revokeWorkspaceHookTrust:r(kn=>("hookDeclarationDigests"in kn?$e?.revokeCurrent(kn):$e?.revoke({sessionId:kn.sessionId,taskId:kn.taskId,runId:kn.runId,...kn.remoteSessionId?{remoteSessionId:kn.remoteSessionId}:{},workspaceIdentity:kn.workspaceIdentity,bundleDigest:kn.bundleDigest,reviewFlowId:kn.reviewFlowId,generation:kn.generation,interactionId:kn.interactionId},kn.reviewItemIds))??Promise.resolve({accepted:!1,reasonCode:"workspace_hooks_require_trust_capable_host"}),"revokeWorkspaceHookTrust"),requestWorkspaceHookReview:r(kn=>$e?.requestReview({workspaceIdentity:kn.workspaceIdentity,bundleDigest:kn.bundleDigest})??Promise.resolve({accepted:!1,reasonCode:"workspace_hooks_require_trust_capable_host"}),"requestWorkspaceHookReview"),reloadWorkspaceHookTrust:r(()=>$e?.reloadTrust()??Promise.resolve(),"reloadWorkspaceHookTrust"),setModelIoFullRetentionEnabled:r(kn=>Rs.setModelIoFullRetentionEnabled(kn),"setModelIoFullRetentionEnabled"),readToolResultArtifact:r(kn=>Xe.readToolResultArtifact({uri:kn,trace:s}),"readToolResultArtifact"),writePromptAttachment:r(async kn=>{let Nn=await Xe.writeToolResultArtifact({content:`data:${kn.mime};base64,${Buffer.from(kn.bytes).toString("base64")}`,contentType:"text/plain",retention:"session",sessionId:o,toolCallId:`prompt-attachment-upload-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,toolName:"prompt-attachment:upload",trace:s});return(kn.mime.startsWith("image/")||kn.mime.startsWith("video/")||kn.mime.split(";",1)[0]?.trim().toLowerCase()==="application/pdf")&&Xe.primeMediaAttachmentPath?.({bytes:kn.bytes,mediaType:kn.mime,uri:Nn.uri}).catch(()=>{}),{ref:Nn.uri}},"writePromptAttachment"),readPromptAttachment:r(async kn=>{let{ref:Nn,mediaType:Ur}=await gi(kn);if(Nn.startsWith("zcode-artifact://")){let qe=await Xe.readToolResultArtifact({uri:Nn,trace:s});return EHa(qe.content,Ur,kn.maxBytes)}return{bytes:(await _e.readBinaryFile({path:Nn,maxBytes:kn.maxBytes,trace:s})).content,mediaType:Ur}},"readPromptAttachment"),statPromptAttachment:r(async kn=>{let{ref:Nn,mediaType:Ur,artifactUri:Vo}=await gi(kn);if(Vo){if(!Xe.statToolResultArtifact)throw new m1(nC.statUnsupported);let Kt=await Xe.statToolResultArtifact({uri:Vo,trace:s});return{totalBytes:Kt.bytes,mediaType:Kt.contentType||Ur,...Kt.mtimeMs===void 0?{}:{mtimeMs:Kt.mtimeMs}}}let qe=await _e.stat({path:Nn,trace:s});if(qe.kind!=="file")throw new m1(nC.statNotFile);return{totalBytes:qe.sizeBytes,mediaType:Ur,...qe.mtimeMs===void 0?{}:{mtimeMs:qe.mtimeMs}}},"statPromptAttachment"),resolvePromptAttachmentPreviewSource:r(async kn=>{let Nn=await gi(kn);if(!Nn.mediaType.startsWith("video/"))return{kind:"chunked"};if(Nn.artifactUri){if(!Xe.ensureMediaAttachmentPath)return{kind:"chunked"};try{let Ur=await Xe.ensureMediaAttachmentPath({uri:Nn.artifactUri,mediaType:Nn.mediaType});if(Ur.status==="ready"&&Ur.path.trim())return{kind:"local_path",path:Ur.path,mediaType:Nn.mediaType}}catch{}return{kind:"chunked"}}return(0,A4.isAbsolute)(Nn.ref)?{kind:"local_path",path:Nn.ref,mediaType:Nn.mediaType}:{kind:"chunked"}},"resolvePromptAttachmentPreviewSource"),...Fs,close:r(async()=>{try{await Qo?.()}finally{try{I?.dispose()}finally{await b.shutdown()}}},"close"),...oa,...mi,...hi===void 0?{}:{listDynamicWorkflowRunEvents:r(async kn=>hi.listEvents(kn.runId,{...kn.afterSequence===void 0?{}:{afterSequence:kn.afterSequence},...kn.limit===void 0?{}:{limit:kn.limit}}),"listDynamicWorkflowRunEvents")},...hi===void 0||typeof hi.listArtifacts!="function"||typeof hi.listArtifactItems!="function"||typeof hi.readArtifact!="function"?{}:{listDynamicWorkflowRunArtifacts:r(async kn=>hi.listArtifacts(kn.runId),"listDynamicWorkflowRunArtifacts"),listDynamicWorkflowRunArtifactItems:r(async kn=>hi.listArtifactItems(kn.runId,kn.artifactId,{...kn.afterSequence===void 0?{}:{afterSequence:kn.afterSequence},limit:kn.limit}),"listDynamicWorkflowRunArtifactItems"),readDynamicWorkflowRunArtifact:r(async kn=>hi.readArtifact(kn.runId,kn.artifactId,kn.version),"readDynamicWorkflowRunArtifact")},...hi===void 0||typeof hi.listWorkspaceNodes!="function"||typeof hi.readWorkspaceNodeResult!="function"?{}:{listDynamicWorkflowRunWorkspaceNodes:r(async kn=>hi.listWorkspaceNodes(kn.runId),"listDynamicWorkflowRunWorkspaceNodes"),readDynamicWorkflowRunNodeResult:r(async kn=>hi.readWorkspaceNodeResult(kn.runId,kn.siteId,kn.ordinal,{maxBytes:kn.maxBytes}),"readDynamicWorkflowRunNodeResult")},...hi===void 0?{}:{},...hi===void 0||typeof hi.listRunsForSession!="function"?{}:{listDynamicWorkflowRuns:r(async kn=>hi.listRunsForSession(kn.limit),"listDynamicWorkflowRuns")},...hi===void 0||typeof hi.replayProgressForSession!="function"?{}:{replayDynamicWorkflowRuns:r(async kn=>hi.replayProgressForSession(kn),"replayDynamicWorkflowRuns")},...hi===void 0||typeof hi.resume!="function"?{}:{resumeWorkflowRun:r(async kn=>{let Nn=await hi.resume(kn.workId);return Nn.ok&&await Mn().trackResumedDynamicWorkflowRun({runId:Nn.runId,...Nn.toolCallId===void 0?{}:{toolCallId:Nn.toolCallId},...kn.name===void 0?{}:{name:kn.name},traceContext:s}),Nn},"resumeWorkflowRun")},...hi===void 0?{}:{startSavedWorkflow:r(async kn=>(await Wi({traceContext:s}),await Mn().startSavedWorkflowRun({...kn,traceContext:s})),"startSavedWorkflow")},...hi===void 0||typeof hi.amend!="function"||typeof hi.getScript!="function"?{}:{amendWorkflowRunSettings:r(async kn=>(await Wi({traceContext:s}),await Mn().amendWorkflowRunSettings({...kn,traceContext:s})),"amendWorkflowRunSettings")},...r$o({configResult:l,options:e,workingDirectory:a}),getPluginReferenceCatalog:r(()=>kt,"getPluginReferenceCatalog"),getSkillCatalog:r(async()=>(await Wi({traceContext:s}),await Mn().getSkillCatalog(s)),"getSkillCatalog"),resume:Ji,...li}}catch(E){throw I?.dispose(),b.shutdown().catch(()=>{}),T?.close(),g.fail("ZCode app startup failed",E,{context:{sessionId:o,workingDirectory:a},event:"bootstrap.app.startup.failed",stage:"total"}),E}}var A4,ZAn=Y(()=>{"use strict";A4=require("node:path");f3();W0e();vw();Eme();yme();a7();Msn();Fsn();j2o();xRe();K0e();sdt();Y0();Cwt();nr();ms();g0();wEn();Pwt();kEn();Kzo();l9();wbe();s7o();p7o();o$o();a$o();w$o();C$o();Mje();N$o();Z$o();j9o();BAn();SAn();vVo();SVo();kVo();QEn();TVo();CVo();$An();NVo();GVo();YVo();kbe();tHo();sHo();aHo();JAn();r(EHa,"decodePromptAttachmentDataUrl");r(KAn,"createZCodeApp")});function QAn(e){let t=DHa.parse(e),n=t.model,o=Hkt(typeof n=="string"?n:n?.main),s=typeof n=="object"?Hkt(n?.lite):void 0,a=o||s?{...o?{main:o}:{},...s?{lite:s}:{}}:void 0;return{...a?{model:a}:{},...t.provider?{provider:t.provider}:{}}}function Hkt(e){if(!e)return;let t=e.indexOf("/");if(t<=0||t===e.length-1)return;let n=e.slice(0,t).trim(),o=e.slice(t+1).trim();if(!(!n||!o))return{provider:n,model:o}}var XAn,hHo,Vkt,AHa,PHa,RHa,YAn,DHa,gHo=Y(()=>{"use strict";Fa();XAn=m.record(m.string(),m.string()),hHo=m.record(m.string(),m.unknown()),Vkt=m.number().finite().positive(),AHa=m.object({enabled:m.boolean().optional(),levels:m.array(m.string().min(1)).optional(),defaultLevel:m.string().min(1).optional(),providerOptionsByLevel:m.record(m.string(),hHo).optional()}),PHa=m.object({id:m.string().min(1).optional(),name:m.string().min(1).optional(),attachment:m.boolean().optional(),reasoning:m.union([m.boolean(),AHa]).optional(),tool_call:m.boolean().optional(),structured_output:m.boolean().optional(),supportsImages:m.boolean().optional(),supportsPdf:m.boolean().optional(),supportsVideo:m.boolean().optional(),supportsToolCall:m.boolean().optional(),supportsJsonSchemaOutput:m.boolean().optional(),contextWindow:Vkt.optional(),maxOutputTokens:Vkt.optional(),limit:m.object({context:Vkt.optional(),output:Vkt.optional()}).optional(),modalities:m.object({input:m.array(m.enum(["text","audio","image","video","pdf"])).optional(),output:m.array(m.enum(["text","audio","image","video","pdf"])).optional()}).optional(),options:hHo.optional(),headers:XAn.optional()}).passthrough(),RHa=m.object({kind:m.enum(["anthropic","openai","openai-compatible"]),name:m.string().min(1).optional(),npm:m.never().optional(),options:m.object({apiKey:m.string().optional(),baseURL:m.string().min(1).optional(),apiKeyRequired:m.boolean().optional(),headers:XAn.optional()}).passthrough().optional(),headers:XAn.optional(),models:m.record(m.string(),PHa).optional()}).passthrough(),YAn=m.string().refine(e=>Hkt(e)!==void 0,{message:"Model references must use provider/model format"}),DHa=m.object({provider:m.record(m.string(),RHa).optional(),model:m.union([YAn,m.object({main:YAn.optional(),lite:YAn.optional()}).strict().refine(e=>e.main!==void 0||e.lite!==void 0)]).optional(),small_model:m.never().optional()}).passthrough();r(QAn,"parseLegacyCliModelConfig");r(Hkt,"parseModelTarget")});function MHa(e){switch(e){case"anthropic":return"anthropic-messages";case"openai":return"openai-responses";case"openai-compatible":case void 0:return"openai-chat-completions"}return"openai-chat-completions"}function NHa(e){let t=QAn(e.input),n=uw.empty(),o=dA.empty();for(let[a,l]of Object.entries(t.provider??{})){let u=a.trim();if(!u)continue;let f=u==="builtin:bigmodel"?aee.bigmodel:u==="builtin:zai"?aee.zai:void 0;if(f){let w=l.options?.apiKey?.trim();w&&(n=n.setRule({providerId:f,templateId:f,config:new Tk({group:"standard-personal",access:new xz({apiKey:w})})}));continue}if(u.startsWith("builtin:")||u.startsWith("account:")||l.source!==void 0&&l.source!=="custom")continue;if(BHa(l))throw new Gkt(u);let g=FHa(l),_=g.map(w=>w.modelId),b=l.name?.trim();n=n.setRule({providerId:u,providerName:b&&b!==u?b:void 0,config:new Tk({group:"standard-personal",access:new xz({apiKey:l.options?.apiKey}),api:new _pe({type:MHa(l.kind),baseUrl:l.options?.baseURL,headers:jHa(l.headers,l.options?.headers)}),..._.length>0?{personalModelIds:_,modelOrder:_}:{}})});for(let w of g)w.contextWindow!==void 0&&(o=o.setExact(u,w.modelId,new uA({properties:new lAe({contextWindow:w.contextWindow})})))}let s=LHa(e.input)??void 0;return Object.freeze({providers:n,models:o,defaultModelSelection:s})}async function Jkt(e){let t=e.filePath??U7();try{let n=JSON.parse(await(0,_Ho.readFile)(t,"utf8"));return NHa({input:n})}catch(n){if(UHa(n)||n instanceof Gkt)return null;throw n}}function LHa(e){let t=QAn(e).model?.main;return!t||t.provider===OHa?null:Object.freeze({providerId:t.provider,modelId:t.model})}function FHa(e){let t=new Set,n=[];for(let[o,s]of Object.entries(e.models??{})){if(s.deleted===!0)continue;let a=(s.id??o).trim();if(!a||t.has(a))continue;t.add(a);let l=s.contextWindow??s.limit?.context;n.push({modelId:a,...zHa(l)?{contextWindow:l}:{}})}return n}function jHa(...e){let t=Object.assign({},...e.filter(Boolean));return Object.keys(t).length>0?t:void 0}function BHa(e){return e.options?.apiKeyRequired===!1}function UHa(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function zHa(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0}var _Ho,OHa,Gkt,ePn=Y(()=>{"use strict";_Ho=require("node:fs/promises");ms();vw();gHo();pA();OHa="builtin:zapi",Gkt=class extends Error{static{r(this,"UnsupportedLegacyCliProviderConfigError")}providerId;constructor(t){super(`\u65E7 CLI Provider ${t} \u542B\u6709\u6B63\u5F0F Config \u5C1A\u4E0D\u80FD\u8868\u8FBE\u7684\u6267\u884C\u5B57\u6BB5`),this.name="UnsupportedLegacyCliProviderConfigError",this.providerId=t}};r(MHa,"resolveLegacyProviderApiType");r(NHa,"importLegacyCliPersonalProviderConfig");r(Jkt,"readLegacyCliPersonalProviderConfig");r(LHa,"importLegacyCliConfiguredDefault");r(FHa,"collectLegacyCliModelMembers");r(jHa,"mergeHeaders");r(BHa,"requiresUnsupportedNoAuthentication");r(UHa,"isFileNotFound");r(zHa,"isPositiveInteger")});async function tPn(e){return(await nPn(e)).providers}async function nPn(e,t){if(t)return{zcodeBuiltinRevision:t.revision,providers:t.providers.entries().flatMap(([s,a])=>{let l=a.access,u=a.builtinModelIds?.find(f=>f.trim())?.trim();return l?.type==="zhipu-account"&&l.mode==="individual-coding-plan"&&l.accountType&&u?[{family:l.accountType,modelId:u,providerId:s}]:[]})};let n=e[LV]?.trim();if(!n)throw new Error(`${LV} is required for login`);let o=new UO({bundledFilePath:n,watch:!1});try{let s=await o.read();return nPn(e,s)}finally{o.dispose()}}async function vHo(e,t){let n=(await tPn(t)).filter(o=>o.family===e);if(n.length!==1)throw new Error(`ZCode Built-in Config \u5FC5\u987B\u4E3A ${e} \u58F0\u660E\u552F\u4E00 Individual Coding Plan Provider`);return n[0]}function Yie(e){let t=e.trim();if(!t)throw new Error("Standalone Account Provider ID \u4E0D\u80FD\u4E3A\u7A7A");return`account-provider:${t}:identity`}function t3e(e){let t=e.providerId.trim(),n=e.accountIdentity.trim();if(!t)throw new Error("Standalone Account Provider ID \u4E0D\u80FD\u4E3A\u7A7A");if(!n)throw new Error("Standalone Account Identity \u4E0D\u80FD\u4E3A\u7A7A");return`account-provider:coding-plan:${t}:account:${encodeURIComponent(n)}:api-key`}function rPn(e){let t=e.trim();if(!t)throw new Error("Standalone Account Secret \u4E0D\u80FD\u4E3A\u7A7A");return`key-${(0,yHo.createHash)("sha256").update(t).digest("hex").slice(0,24)}`}async function oPn(e,t,n){let o=await nPn(t,n),s=o.providers,a=s.map(({providerId:b})=>Yie(b)),l=await e.loadMany(a),u=s.flatMap(({family:b,providerId:w})=>{let T=l[Yie(w)]?.trim();if(!T)return[];let I=t3e({providerId:w,accountIdentity:T});return[{accountIdentity:T,credentialKey:I,family:b,providerId:w}]}),f=await e.loadMany(u.map(({credentialKey:b})=>b)),g=new Map(u.map(b=>[b.providerId,b])),_=new uw(s.map(({family:b,providerId:w})=>{let T=g.get(w),I=T?f[T.credentialKey]?.trim():void 0;return!T||!I?[w,new Tk({access:new zj({entitled:!1})})]:[w,new Tk({access:new zj({entitled:!0})})]}));return pAe(o.zcodeBuiltinRevision,_)}async function bHo(e,t){return(await oPn(e,t)).providers.entries().some(([,n])=>n.access?.type==="zhipu-account"?n.access.entitled===!0:!1)}function SHo(e,t){return{shouldRefreshBeforeModelRequest(){return!0},async refreshBeforeModelRequest(n){n.abortSignal?.throwIfAborted();let o=n.providerId.trim(),s=n.accountAccess;if(!s||s.mode!=="individual-coding-plan")throw new Error(`Standalone Account Provider \u8BF7\u6C42\u8EAB\u4EFD\u65E0\u6548: ${o}`);let a=(await e.load(Yie(o)))?.trim();if(!a)throw new Error(`Standalone Account Provider \u51ED\u636E\u5DF2\u7ECF\u5931\u6548: ${o}`);let l=(await e.load(t3e({providerId:o,accountIdentity:a})))?.trim();if(!l)throw new Error(`Standalone Account Provider \u7F3A\u5C11\u8BF7\u6C42\u51ED\u636E: ${o}`);return{headersApplied:!0,requestAuth:{apiKey:l}}}}}var yHo,iPn=Y(()=>{"use strict";yHo=require("node:crypto");pA();hfe();r(tPn,"readStandaloneCodingPlanProviders");r(nPn,"readStandaloneCodingPlanCatalog");r(vHo,"resolveStandaloneCodingPlanProvider");r(Yie,"standaloneAccountIdentityCredentialKey");r(t3e,"standaloneAccountProviderCredentialKey");r(rPn,"createStandaloneAccountIdentityFromSecret");r(oPn,"readStandaloneAccountProviderConfigSnapshot");r(bHo,"hasStandaloneCodingPlanAccess");r(SHo,"createStandaloneProviderRuntimeHeadersPort")});function UK(e){if(e?.aborted)throw sPn(e)}async function wHo(e,t,n){if(!n){await e(t);return}await Promise.race([e(t),xHo(n)])}async function kHo(e){let t;try{return await Promise.race([e.callbackServer.waitForCallback(),new Promise((n,o)=>{t=setTimeout(()=>o(e.createTimeoutError()),e.timeoutMs)}),xHo(e.signal)])}finally{t&&clearTimeout(t)}}function xHo(e){return e?new Promise((t,n)=>{if(e.aborted){n(sPn(e));return}e.addEventListener("abort",()=>n(sPn(e)),{once:!0})}):new Promise(()=>{})}function sPn(e){return e.reason??new Error("Login cancelled.")}var THo=Y(()=>{"use strict";r(UK,"throwIfAborted");r(wHo,"sleepWithAbort");r(kHo,"waitForCallbackWithAbort");r(xHo,"rejectOnAbort");r(sPn,"abortReason")});async function WHa(e={}){let t=e.credentialStore??jM({env:e.env});return bHo(t,e.env??process.env)}async function VHa(e={}){if((e.env??process.env).ZCODE_CLI_OAUTH_CALLBACK_STDIN==="1"){let $zEnv=e.env??process.env;UK(e.abortSignal);let $zStore=e.credentialStore??jM({env:$zEnv}),$zHttp=e.httpClient??CHo($zEnv),$zPayload;try{$zPayload=JSON.parse(require("node:fs").readFileSync(0,"utf8"))}catch($zError){throw new m9("invalid_callback","Unable to read the Z.AI OAuth callback.",{cause:$zError})}if(!$zPayload||typeof $zPayload.callbackUrl!=="string"||typeof $zPayload.state!=="string")throw new m9("invalid_callback","The Z.AI OAuth callback payload is invalid.");let $zUrl;try{$zUrl=new URL($zPayload.callbackUrl)}catch($zError){throw new m9("invalid_callback","The Z.AI OAuth callback URL is invalid.",{cause:$zError})}if($zUrl.protocol!=="zcode:"||$zUrl.hostname!=="zai-auth"||$zUrl.pathname.replace(/\/+$/u,"")!=="/callback")throw new m9("invalid_callback","The Z.AI OAuth callback target is invalid.");let $zCode=$zUrl.searchParams.get("code")??$zUrl.searchParams.get("authCode"),$zState=$zUrl.searchParams.get("state");if(!$zCode||!$zState||$zState!==$zPayload.state)throw new m9("invalid_callback","The Z.AI OAuth callback state is invalid or expired.");let $zResponse=await $zHttp.request({maxResponseBytes:65536,body:new TextEncoder().encode(JSON.stringify({provider:"zai",code:$zCode,redirect_uri:"zcode://zai-auth/callback",state:$zState})),headers:{"Content-Type":"application/json"},method:"POST",trace:e.trace,url:"https://zcode.z.ai/api/v1/oauth/token"},e.abortSignal),$zText=new TextDecoder().decode($zResponse.body),$zEnvelope;try{$zEnvelope=JSON.parse($zText)}catch($zError){throw new m9("token_exchange_failed",$zResponse.status<200||$zResponse.status>=300?"OAuth HTTP error "+$zResponse.status+" (empty or non-JSON response)":"OAuth response is not valid JSON",{cause:$zError})}let $zMessage=typeof $zEnvelope?.msg==="string"&&$zEnvelope.msg.trim()?$zEnvelope.msg.trim():void 0;if($zResponse.status<200||$zResponse.status>=300)throw new m9("token_exchange_failed",$zMessage??"OAuth HTTP error "+$zResponse.status);if($zEnvelope?.code!==0)throw new m9("token_exchange_failed",$zMessage??"Z.AI token exchange failed.");let $zData=$zEnvelope.data,$zAccessToken=$zData?.zai?.access_token,$zJwtToken=$zData?.token,$zUser=$zData?.user;if(typeof $zAccessToken!=="string"||typeof $zJwtToken!=="string"||!$zUser||typeof $zUser!=="object")throw new m9("token_exchange_failed","Z.AI token response is missing credentials or user data.");UK(e.abortSignal);try{await $zStore.saveZaiLoginCredentials({accessToken:$zAccessToken,jwtToken:$zJwtToken,user:$zUser})}catch($zError){throw new m9("credential_write_failed","Login succeeded but writing credentials failed.",{cause:$zError})}let $zApiKey=await EHo({accessToken:$zAccessToken,env:$zEnv,httpClient:$zHttp,family:"zai",resolver:e.apiKeyResolver}),$zConfig;try{$zConfig=await aPn({accountIdentity:$zUser.user_id,apiKey:$zApiKey,credentialStore:$zStore,env:$zEnv,personalProviderConfigPath:e.personalProviderConfigPath,providerId:"zai"})}catch($zError){throw new m9("config_update_failed","Login succeeded but updating ZCode config failed.",{cause:$zError})}return{configPath:$zConfig.path,credentialsPath:$zStore.filePath,model:$zConfig.mainModel,providerId:"zai",user:$zUser}}let t=e.env??process.env,n=e.now??Date.now,o=e.sleep??XHa;UK(e.abortSignal);let s=e.pollToken??HZr(),a=e.credentialStore??jM({env:t}),l=KHa(e,t),u=await l.init({pollToken:s});await e.onAuthorizeUrl?.(u),UK(e.abortSignal);let f=e.noBrowser?void 0:await(e.openBrowser??Ydn)(u.authorize_url);f&&await e.onBrowserOpen?.(f);let g=await YHa({abortSignal:e.abortSignal,initData:u,now:n,oauthClient:l,onPollStatus:e.onPollStatus,pollToken:s,sleep:o,timeoutMs:e.timeoutMs??IHo});UK(e.abortSignal);try{await a.saveZaiLoginCredentials({accessToken:g.zai.access_token,jwtToken:g.token,user:g.user})}catch(w){throw new m9("credential_write_failed","Login succeeded but writing credentials failed.",{cause:w})}let _=await EHo({accessToken:g.zai.access_token,env:t,httpClient:e.httpClient,family:"zai",resolver:e.apiKeyResolver}),b;try{b=await aPn({accountIdentity:g.user.user_id,apiKey:_,credentialStore:a,env:t,personalProviderConfigPath:e.personalProviderConfigPath,providerId:"zai"})}catch(w){throw new m9("config_update_failed","Login succeeded but updating ZCode config failed.",{cause:w})}return{...f?{browser:f}:{},configPath:b.path,credentialsPath:a.filePath,model:b.mainModel,providerId:"zai",user:g.user}}async function HHa(e={}){let t=e.env??process.env;if(t.ZCODE_CLI_BIGMODEL_REUSE_SESSION!=="0"){UK(e.abortSignal);let $bStore=e.credentialStore??jM({env:t}),$bToken,$bApiKey;try{$bToken=(await $bStore.load(R1.bigmodelAccessToken))?.trim()}catch{}if($bToken)try{$bApiKey=await EHo({accessToken:$bToken,env:t,httpClient:e.httpClient??CHo(t),family:"bigmodel",resolver:e.apiKeyResolver})}catch{}if($bApiKey){UK(e.abortSignal);let $bConfig=await aPn({accountIdentity:rPn($bApiKey),apiKey:$bApiKey,credentialStore:$bStore,env:t,personalProviderConfigPath:e.personalProviderConfigPath,providerId:"bigmodel"});return{configPath:$bConfig.path,model:$bConfig.mainModel,providerId:"bigmodel"}}}UK(e.abortSignal);let n=e.httpClient??CHo(t),o=e.state??MZr(),s=e.callbackServer??await YOe({callbackPath:qHa,state:o}),a=OZr({httpClient:n}),l=a.buildAuthorizeUrl({redirectUri:s.callbackUrl,state:o});await e.onAuthorizeUrl?.({authorize_url:l,callback_url:s.callbackUrl,state:o}),UK(e.abortSignal);let u=e.noBrowser?void 0:await(e.openBrowser??Ydn)(l);u&&await e.onBrowserOpen?.(u),UK(e.abortSignal);try{let f=await kHo({callbackServer:s,createTimeoutError:r(()=>new m9("auth_timeout","Authorization timed out. Please retry login."),"createTimeoutError"),signal:e.abortSignal,timeoutMs:e.timeoutMs??IHo}),g=await require(require("node:path").join(__dirname,"cli-config.cjs")).exchangeBigmodelOAuthCode({code:f.code,redirectUri:s.callbackUrl,state:o,httpClient:n,abortSignal:e.abortSignal,trace:e.trace}),_=await EHo({accessToken:g.accessToken,env:t,httpClient:n,family:"bigmodel",resolver:e.apiKeyResolver}),b=e.credentialStore??jM({env:t}),w=rPn(_);await b.saveMany({[R1.activeProvider]:"bigmodel",[R1.bigmodelAccessToken]:g.accessToken,[R1.zcodeJwtToken]:g.zcodeJwtToken,...g.refreshToken?{[R1.bigmodelRefreshToken]:g.refreshToken}:{},[R1.bigmodelUserInfo]:JSON.stringify({id:w})});let T=await aPn({accountIdentity:w,apiKey:_,credentialStore:b,env:t,personalProviderConfigPath:e.personalProviderConfigPath,providerId:"bigmodel"});return{...u?{browser:u}:{},configPath:T.path,model:T.mainModel,providerId:"bigmodel"}}finally{await s.close()}}async function GHa(e){let t=e.apiKey.trim();if(!t)throw new m9("config_update_failed","API key must not be empty.");let n=e.credentialStore??jM({env:e.env}),o=await aPn({accountIdentity:rPn(t),apiKey:t,credentialStore:n,env:e.env??process.env,personalProviderConfigPath:e.personalProviderConfigPath,providerId:e.providerId});return{configPath:o.path,model:o.mainModel,providerId:e.providerId}}async function JHa(e={}){let t=e.credentialStore??jM({env:e.env}),n=(await tPn(e.env??process.env)).map(({providerId:f})=>f),o=n.map(Yie),s=await t.loadMany(o),a=n.flatMap(f=>{let g=s[Yie(f)]?.trim();return g?[t3e({providerId:f,accountIdentity:g})]:[]}),l=[...Object.values(R1),...o,...a],u=await t.loadMany(l);return await t.deleteIfValues(Object.fromEntries(Object.entries(u).flatMap(([f,g])=>g===null?[]:[[f,g]]))),{credentialsPath:t.filePath}}async function aPn(e){let t=await vHo(e.providerId,e.env),n=t.providerId,o=t.modelId,s=t3e({providerId:n,accountIdentity:e.accountIdentity});await e.credentialStore.saveMany({[Yie(n)]:e.accountIdentity,[s]:e.apiKey});let a=e.personalProviderConfigPath??e.env[tte]?.trim()??(0,Kkt.join)((0,Kkt.dirname)(e.credentialStore.filePath),MXe),l=new Cpe({filePath:a,importLegacy:r(()=>Jkt({}),"importLegacy"),pollingIntervalMs:!1}),u=new Tpe({personalRepository:l});try{await u.saveConfiguredDefault({providerId:n,modelId:o})}finally{u.dispose(),l.dispose()}return{mainModel:`${n}/${o}`,path:a}}function KHa(e,t){let n=e.baseUrl??Bee(ZHa(t)).apiBaseUrl;if(e.httpClient)return Xdn({baseUrl:n,httpClient:e.httpClient});let o=K0({env:t});return Xdn({baseUrl:n,httpClient:s2e({env:t,proxyUrl:o.config.network.httpProxy,noProxy:o.config.network.noProxy,caCertFile:o.config.network.caCertFile,timeoutMs:o.config.network.timeout})})}function ZHa(e){return p1(e)}function CHo(e){let t=K0({env:e});return s2e({env:e,proxyUrl:t.config.network.httpProxy,noProxy:t.config.network.noProxy,caCertFile:t.config.network.caCertFile,timeoutMs:t.config.network.timeout})}async function EHo(e){return(e.resolver??$Zr({httpClient:e.httpClient??CHo(e.env)})).resolve({accessToken:e.accessToken,family:e.family})}async function YHa(e){let t=e.initData.expires_at*1e3,n=Math.min(e.now()+e.timeoutMs,t),o=Math.max($Ha,e.initData.poll_interval_sec*1e3);for(;e.now()<n;){UK(e.abortSignal);let s=await e.oauthClient.poll({flowId:e.initData.flow_id,pollToken:e.pollToken});if(await e.onPollStatus?.(s),s.status==="ready")return s;if(s.status==="failed")throw new m9("auth_failed","Authorization failed. Please retry login.");await wHo(e.sleep,Math.min(o,Math.max(0,n-e.now())),e.abortSignal)}throw new m9("auth_timeout","Authorization timed out. Please retry login.")}function XHa(e){return new Promise(t=>setTimeout(t,e))}var Kkt,IHo,$Ha,qHa,m9,AHo=Y(()=>{"use strict";adt();vw();a7();ms();hfe();ePn();Kkt=require("node:path");iPn();THo();IHo=300*1e3,$Ha=1e3,qHa="/oauth/callback/bigmodel";r(WHa,"hasConfiguredStandaloneCodingPlan");m9=class extends Error{static{r(this,"ZCodeCliLoginError")}code;constructor(t,n,o={}){super(n,o),this.name="ZCodeCliLoginError",this.code=t}};r(VHa,"loginZCodeCli");r(HHa,"loginBigmodelCodingPlan");r(GHa,"configureCodingPlanApiKey");r(JHa,"logoutZCodeCli");r(aPn,"persistStandaloneCodingPlanConnection");r(KHa,"createOAuthClient");r(ZHa,"resolveCliZCodeEndpointOrigin");r(CHo,"createDefaultHttpClient");r(EHo,"resolveCodingPlanApiKey");r(YHa,"pollUntilReady");r(XHa,"sleepMs")});async function OHo(e={}){let t=e.env??process.env,n=await rGa(nGa(t));return _Kt({appVersion:t[Ape]??e.appVersion,arch:(0,Bbe.arch)(),clientLanguage:eGa(),clientTimezone:tGa(),deviceMid:n,endpointOrigin:p1(t),osVersion:(0,Bbe.release)(),platform:process.platform,releaseChannel:YL(t),sourceTitle:e.sourceTitle??"cli"})}function eGa(){return Intl.DateTimeFormat().resolvedOptions().locale}function tGa(){return Intl.DateTimeFormat().resolvedOptions().timeZone}function nGa(e){let t=e[QHa]?.trim()||(0,Bbe.homedir)();return(0,DHo.join)(t,".zcode","v2","telemetry-state.json")}async function rGa(e){let t=PHo.get(e);if(t)return t;try{let n=JSON.parse(await(0,RHo.readFile)(e,"utf8"));if(typeof n.deviceMid!="string")return;let o=n.deviceMid.trim();return!o||!/^[\x20-\x7e]+$/.test(o)?void 0:(PHo.set(e,o),o)}catch{return}}var RHo,Bbe,DHo,QHa,PHo,MHo=Y(()=>{"use strict";RHo=require("node:fs/promises"),Bbe=require("node:os"),DHo=require("node:path");ms();QHa="ZCODE_DATA_BASE_DIR",PHo=new Map;r(OHo,"createProviderEndpointRoutingSourceHeaders");r(eGa,"resolveClientLanguage");r(tGa,"resolveClientTimezone");r(nGa,"resolveTelemetryStateFile");r(rGa,"readExistingDeviceMid")});function n3e(e){let t=e.env??process.env,n=YAe(t,oGa),o=iGa(n,e.network),s=NHo.get(o);if(s)return s;let a=new dat({appVersion:e.appVersion,configUrl:n,httpClient:s2e({caCertFile:e.network.caCertFile,env:t,noProxy:e.network.noProxy,proxyUrl:e.network.httpProxy}),logger:e.logger.child({module:"adapters.model.provider_endpoint_routing"}),sourceHeaders:r(()=>OHo({appVersion:e.appVersion,env:t,sourceTitle:e.sourceTitle}),"sourceHeaders")});return NHo.set(o,a),a}function LHo(e){let t=e.env??process.env,n=K0({env:t,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:e.workingDirectory}),s=(e.loggerFactory??rB({env:t})).createLogger("zcode").child({module:"bootstrap.provider_endpoint_routing"});return n3e({appVersion:e.appVersion,env:t,logger:s,network:n.config.network,sourceTitle:e.sourceTitle})}function iGa(e,t){return JSON.stringify({caCertFile:t.caCertFile,configUrl:e,httpProxy:t.httpProxy,noProxy:t.noProxy})}var oGa,NHo,cPn=Y(()=>{"use strict";vw();a7();fOe();W0e();ms();MHo();oGa="/api/v1/agent/configs",NHo=new Map;r(n3e,"resolveProcessProviderEndpointRoutingPort");r(LHo,"createDefaultProviderEndpointRoutingPort");r(iGa,"routingRegistryKey")});async function Ykt(e,t={}){let n=ymr(e);if(!n)throw new Error("\u7F3A\u5C11\u8FDB\u7A0B Provider Registry \u7684 ZCode Built-in / Personal Config \u8DEF\u5F84");let o=new yee,s=t.standalone?t.standalone.credentialStore??jM({env:{...e}}):void 0,a,l=t.standalone?e[OXe]?.trim():void 0,u=new pZe({...n,...l?{zcodeBuiltinFilePath:l,zcodeBuiltinActiveFilePath:n.zcodeBuiltinFilePath,zcodeBuiltinRemote:{controlFilePath:(0,Zkt.join)((0,Zkt.dirname)(n.zcodeBuiltinFilePath),"zcode-builtin-refresh.json"),resolveEndpointKey:r(()=>p1(e),"resolveEndpointKey"),fetchRelease:r((_,b)=>xnr({endpointOrigin:_,signal:b,appVersion:HL,platform:aZe(),request:t.standalone?.request??globalThis.fetch}),"fetchRelease"),onRefreshResult:t.standalone?.onBuiltinRefreshResult}}:{},onZCodeBuiltinRefreshError:t.standalone?.onBuiltinRefreshError,accountSource:o,...s?{createAccountSource(_){return a=new GKe({configSource:_,async resolve({configRevision:b,configuredProviders:w}){let T=await oPn(s,e,{revision:b,providers:w});return{providers:T.providers,states:T.states??{}}}}),a.onDidRefreshError(({error:b})=>{try{t.standalone?.onAccountInitializationError?.(b)}catch{}}),a}}:{},...t.standalone?{importLegacy:r(()=>Jkt({...t.standalone?.legacyCliUserConfigFilePath?{filePath:t.standalone.legacyCliUserConfigFilePath}:{}}),"importLegacy")}:{}}),f=a?u.onDidCheckZCodeBuiltin(async()=>{let[_,b]=await Promise.all([u.configService.read(),a.read()]);_.zcodeBuiltinRevision!==b.basedOnZCodeBuiltinRevision&&await a.refresh("builtin-account-recovery")}):void 0,g=s?.onDidChange?.(async()=>{await a.refresh("standalone-credentials-changed"),await u.registryService.refresh("standalone-credentials-barrier")});try{await u.start();let _=u.registryService.getSnapshot(),b=new Tpe({personalRepository:u.personalRepository});try{let w=await b.read();return Object.freeze({accountSource:a??o,async syncAccountProviderConfig(T){if(a)throw new Error("Standalone Account \u7531\u672C\u8FDB\u7A0B\u7BA1\u7406\uFF0C\u4E0D\u63A5\u6536 Host \u8986\u76D6");let I=o.replace(T,"host-account-config");return await u.registryService.refresh("host-account-config"),I},dispose(){g?.(),f?.(),a?.dispose(),b.dispose(),u.dispose()},...s?{providerRuntimeHeadersPort:SHo(s,e)}:{},runtime:u,snapshot:_,modelSelectionConfigRepository:b,configuredDefaultModelSelection:w})}catch(w){throw g?.(),b.dispose(),w}}catch(_){throw g?.(),f?.(),a?.dispose(),u.dispose(),_}}function FHo(e){let t=e.revision.trim();if(!t)throw new Error("Account Config revision \u4E0D\u80FD\u4E3A\u7A7A");let n=e.basedOnZCodeBuiltinRevision.trim();if(!n)throw new Error("Account Config Built-in revision \u4E0D\u80FD\u4E3A\u7A7A");let o=Qtr(e.providers);for(let[s,a]of o.entries())if(cee(s)&&a.access?.type==="zhipu-account"&&a.access.entitled&&typeof e.states?.[s]?.current!="boolean")throw new Error(`Account State \u7F3A\u5C11 current: ${s}`);return Object.freeze({revision:t,basedOnZCodeBuiltinRevision:n,providers:o,...e.states?{states:e.states}:{}})}var Zkt,Xkt=Y(()=>{"use strict";pA();ms();Zkt=require("node:path");hfe();rpn();ePn();iPn();r(Ykt,"startProcessProviderRegistryRuntime");r(FHo,"parseProcessAccountProviderConfigSnapshot")});async function lPn(e){let t=(0,Ube.randomUUID)(),n=(0,Ube.createHash)("sha256").update(e.dbPath).digest("hex"),o=0,s=!1,a=r(async l=>{let u=vYe.parse({schemaVersion:1,attemptId:t,databaseId:n,databaseKind:"session",sequence:++o,...l});s||=u.phase==="failed",e.onProgress?.(u),await new Promise((f,g)=>{e.output.write(`${JSON.stringify({method:BR.storageStartup,params:u})}
|
|
15250
15250
|
`,_=>_?g(_):f())})},"report");try{return await a({phase:"checking",elapsedMs:0}),await fH.openStartup({dbPath:e.dbPath},{onProgress:a})}catch(l){if(!s)try{await a({phase:"failed",elapsedMs:0,errorCode:SAe(l),...Ppe(l)})}catch{}throw l}}async function jHo(e){let{createInterface:t}=await import("node:readline"),{zcodeStoragePathReadySchema:n,classifyDatabaseStartupError:o}=await Promise.resolve().then(()=>(ms(),umr)),s=t({input:e.input}),a,l=new Promise((_,b)=>{a=setTimeout(()=>b(Object.assign(new Error("Storage observation handshake timed out"),{kind:"startup_status_timeout"})),3e4),s.once("line",w=>{try{if(w.length>1024)throw new Error("Invalid storage acknowledgement");let T=n.parse(JSON.parse(w));_(T.reuse??!1)}catch(T){b(T)}}),s.once("close",()=>b(Object.assign(new Error("Storage preparation input closed"),{kind:"transport_closed"})))});l.catch(()=>{});let u,f,g=r(_=>new Promise((b,w)=>{e.output.write(`${JSON.stringify(_)}
|
|
15251
15251
|
`,T=>T?w(T):b())}),"write");try{await g({method:"startup/storagePath",params:{path:e.dbPath}});let _=await l;clearTimeout(a),s.close(),_||(u=await lPn(e),u.close(),u=void 0),await g({method:"startup/storagePrepared",params:{}})}catch(_){f=_;try{await g({method:"startup/storageState",params:{schemaVersion:1,attemptId:(0,Ube.randomUUID)(),databaseId:(0,Ube.createHash)("sha256").update(e.dbPath).digest("hex"),databaseKind:"session",sequence:1,phase:"failed",elapsedMs:0,errorCode:o(_),...Ppe(_)}})}catch{}throw _}finally{clearTimeout(a),s.close();try{u?.close()}catch(_){if(!f)throw _}}}var Ube,BHo=Y(()=>{"use strict";Ube=require("node:crypto");f3();ms();r(lPn,"openProtocolStartupStorage");r(jHo,"prepareProtocolStartupStorage")});function UHo(e){globalThis.AI_SDK_LOG_WARNINGS=t=>{try{let n=Array.isArray(t.warnings)?t.warnings:[];e.warn("AI SDK model warning",{event:"model.sdk.warning",module:"bootstrap.zcode_protocol",status:"completed",model:Xie(t.model),provider:Xie(t.provider),warningCount:n.length,warnings:n.map(sGa)})}catch{}}}function sGa(e){if(!e||typeof e!="object")return{value:Xie(e)};let t=e;return{type:Xie(t.type),feature:Xie(t.feature),message:Xie(t.message),details:Xie(t.details)}}function Xie(e){return typeof e=="string"?e:void 0}var zHo=Y(()=>{"use strict";r(UHo,"installZCodeProtocolAiSdkWarningLogger");r(sGa,"summarizeWarning");r(Xie,"stringValue")});function qHo(e){return{async resolveHeaders(t){let n=e.resolveContext(),o=e.resolveWorkspace({...t.workspaceIdentity?{workspaceIdentity:t.workspaceIdentity}:{},...t.workspacePath?{workspacePath:t.workspacePath}:{}});if(!n||!o)return{ok:!1,reason:"official_auth_unavailable"};$Ho+=1;try{return await n.requestClient(va.interactionRequestOfficialMcpAuthHeaders,{mcpKey:t.mcpKey,pluginId:t.pluginId,requestId:`official-mcp-auth:${$Ho}`,targetOrigin:t.targetOrigin,workspace:o},OGt,t.signal?{signal:t.signal}:{})}catch{return{ok:!1,reason:"official_auth_unavailable"}}}}}var $Ho,WHo=Y(()=>{"use strict";ms();$Ho=0;r(qHo,"createOfficialMcpAuthHeadersPort")});function VHo(e){return"method"in e&&"id"in e}function HHo(e){return"method"in e&&!("id"in e)}function GHo(e){return"id"in e&&"result"in e}function JHo(e){return"id"in e&&"error"in e}function aGa(e){let t=e?.issues;if(!Array.isArray(t)||t.length===0)return;let n=t.slice(0,5).map(s=>`${Array.isArray(s.path)&&s.path.length>0?s.path.join("."):"(root)"}: ${s.message??"invalid"}`),o=t.length>5?` (+${t.length-5} more)`:"";return n.join("; ")+o}function yl(e,t){try{return e.parse(t)}catch(n){let o=aGa(n);throw new sf(-32602,o?`Invalid params \u2014 ${o}`:"Invalid params",n)}}function zK(e,t){if(t!==void 0&&t!==e.stateRevision)throw new sf(-32009,"Session state revision mismatch",{actualRevision:e.stateRevision,expectedRevision:t})}function KHo(e){if(e instanceof sf)return{code:e.code,data:e.data,message:e.message};if(e instanceof Error){let t="code"in e&&typeof e.code=="string"?e.code:void 0;return{code:-32603,data:{name:e.name,stack:e.stack,...t?{code:t}:{}},message:e.message}}return{code:-32603,message:String(e)}}function cGa(e){return FV()}function ZHo(e,t){let n=vA({sessionId:e,traceId:t?.traceId??cGa(e)});return t?.spanId&&(n.spanId=t.spanId),t?.parentId&&(n.parentId=t.parentId,n.parentSpanId=t.parentId),n}function r3e(e){return{traceId:e.traceId,...e.spanId?{spanId:e.spanId}:{},...e.parentId??e.parentSpanId?{parentId:e.parentId??e.parentSpanId}:{}}}function Xy(e,t,n={}){let o=e.sessions.get(t);if(!o)throw e.logger?.warn("ZCode Protocol session runtime missing",{activeSessionCount:e.sessions.size,event:"zcode_protocol.session.require_missing",hasSessionStore:!!e.deps.sessionStore,module:"bootstrap.zcode_protocol",operation:n.operation??"unknown",...n.deliveryKind?{deliveryKind:n.deliveryKind}:{},sessionId:t}),new sf($ee.sessionUnavailable,`Session is not active: ${t}`);return o}function Qkt(e){return e.loggerFactory?.createLogger("zcode").child({module:"bootstrap.zcode_protocol"})}var sf,Nw=Y(()=>{"use strict";nr();ms();sf=class extends Error{static{r(this,"ProtocolRequestError")}code;data;constructor(t,n,o){super(n),this.code=t,this.data=o,this.name="ProtocolRequestError"}};r(VHo,"isRequest");r(HHo,"isNotification");r(GHo,"isResponse");r(JHo,"isErrorResponse");r(aGa,"summarizeParamsError");r(yl,"parseParams");r(zK,"assertExpectedRevision");r(KHo,"toProtocolError");r(cGa,"createProtocolTraceId");r(ZHo,"createProtocolRootTraceContext");r(r3e,"protocolTraceFromTraceContext");r(Xy,"requireSession");r(Qkt,"createProtocolLogger")});function eGo(e){return{sessionId:e,rounds:[],networkEntries:[],cache:null}}function XHo(e,t){return e.has(t)?!1:(e.add(t),e.size>ete.dedupe&&e.delete(e.values().next().value),!0)}function QHo(e){return Object.fromEntries(Object.entries(e).slice(0,lGa).map(([t,n])=>[t.slice(0,YHo),n.slice(0,YHo)]))}function $K(e){return e!==void 0&&Number.isFinite(e)&&e>=0?e:void 0}function tGo(e,t){if(t.type!==lt.ModelNetworkStatus||String(t.sessionId)!==e.app.sessionId)return;let n=t.payload,o=tKt({taskId:e.app.sessionId,traceId:t.traceId,eventId:String(t.id),payload:{...n,model:{providerId:n.providerId,modelId:n.modelId}}});if(!o)return;let s=uPn.get(e);if(s||(s={snapshot:eGo(e.app.sessionId),seenEvents:new Set,completedRequests:new Set,hasUnknownCacheUsage:!1},uPn.set(e,s)),!XHo(s.seenEvents,String(t.id)))return;let{type:a,taskId:l,eventId:u,inputId:f,...g}=o,_=Date.parse(n.timestamp),b=Number.isFinite(_)?_:t.timestamp.getTime(),w=s.snapshot;if(w.networkEntries=[...w.networkEntries,{...g,recordedAt:b,maxAttempts:n.maxAttempts,requestHeaders:QHo(g.requestHeaders),responseHeaders:QHo(g.responseHeaders),...g.message?{message:g.message.slice(0,uGa)}:{}}].slice(-ete.network),n.type!=="model_request_completed"||n.querySource!=="main_turn"||!XHo(s.completedRequests,n.requestId))return;let T=n.usage,I=$K(T?.inputTokens),E=$K(T?.outputTokens),R=$K(T?.cacheReadTokens),L=$K(n.durationMs),U=$K(n.timeToFirstContentMs),B=L!==void 0&&U!==void 0&&L>U?L-U:null;s.hasUnknownCacheUsage||=I===void 0||R===void 0;let z=w.cache,$=(z?.totalInputTokens??0)+(I??0),J=(z?.totalCacheReadTokens??0)+(R??0),q=(z?.hitRateRequestCount??0)+1;w.cache={hitRateRequestCount:q,totalInputTokens:$,totalCacheReadTokens:J,hitRate:!s.hasUnknownCacheUsage&&$>0?J/$:null},w.rounds=[...w.rounds,{eventKey:String(t.id),requestId:n.requestId,requestIndex:q,recordedAt:b,usage:{inputTokens:I,outputTokens:E,totalTokens:$K(T?.totalTokens)??(I!==void 0&&E!==void 0?I+E:void 0),reasoningTokens:$K(T?.reasoningTokens),cachedInputTokens:R,cachedWriteInputTokens:$K(T?.cacheWriteTokens)},hitRate:I!==void 0&&I>0&&R!==void 0?R/I:null,generationDurationMs:B,tokensPerSecond:TZt(E,B)}].slice(-ete.rounds)}function dGa(e){return uPn.get(e)?.snapshot??eGo(e.app.sessionId)}function nGo(e,t){let n=xZt.parse(t);return dGa(Xy(e,n.sessionId))}var uPn,lGa,YHo,uGa,dPn=Y(()=>{"use strict";nr();ms();Nw();uPn=new WeakMap,lGa=32,YHo=512,uGa=2048;r(eGo,"emptySnapshot");r(XHo,"remember");r(QHo,"boundedHeaders");r($K,"token");r(tGo,"observeSessionDebug");r(dGa,"readSessionDebug");r(nGo,"querySessionDebug")});function i3e(e){return pGa.has(e??"interactive")}var o3e,pGa,pPn=Y(()=>{"use strict";o3e=["interactive","fork","workflow_parent"],pGa=new Set(o3e);r(i3e,"isTaskListSessionType")});function mGa(e){return fGa.test(e)}function hGa(e){return{filename:e.fileName,mimeType:e.mime,sizeBytes:e.bytes}}function rGo(e){return e.mime.split(";",1)[0]?.trim().toLowerCase().startsWith("image/")??!1}function oGo(e){return e.mime.split(";",1)[0]?.trim().toLowerCase().startsWith("video/")??!1}function iGo(e){return e.mime.split(";",1)[0]?.trim().toLowerCase()==="application/pdf"}function gGa(e){if(!e.startsWith("data:"))return e;let t=e.indexOf(",");if(t===-1)return;let n=e.slice(0,t),o=e.slice(t+1);if(!n.includes(";base64"))return decodeURIComponent(o);try{return Buffer.from(o,"base64").toString("utf8")}catch{return}}async function _Ga(e,t){let n=hGa(t);if(!mGa(t.ref))return oGo(t)?{path:t.ref,type:"video",...n}:{path:t.ref,type:rGo(t)?"image":iGo(t)?"pdf":"file",...n};if(rGo(t))return{content:t.ref,path:t.fileName,type:"image",...n};if(oGo(t))return{content:t.ref,path:t.fileName,type:"video",...n};if(iGo(t))return{content:t.ref,path:t.fileName,type:"pdf",...n};if(t.bytes>65536)return{type:"file",...n};try{let o=await e.readToolResultArtifact(t.ref),s=gGa(o.content);return s!==void 0?{content:s,path:t.fileName,type:"file",...n}:{type:"file",...n}}catch{return{type:"file",...n}}}async function h9(e,t){if(!t||t.length===0)return;let n=await Promise.all(t.map(o=>_Ga(e,o)));return n.length>0?n:void 0}var fGa,s3e=Y(()=>{"use strict";fGa=/^[a-zA-Z][a-zA-Z\d+.-]*:\/\//;r(mGa,"isUriAttachmentRef");r(hGa,"displayMetaOf");r(rGo,"isImageRef");r(oGo,"isVideoRef");r(iGo,"isPdfRef");r(gGa,"decodeDataUrlText");r(_Ga,"mapAttachmentRef");r(h9,"mapAttachmentRefsToTurnAttachments")});function yGa(e){e.residencyFinalizationCount=(e.residencyFinalizationCount??0)+1;let t=!1;return()=>{t||(t=!0,e.residencyFinalizationCount=Math.max(0,(e.residencyFinalizationCount??1)-1))}}function g9(e,t){let n=yGa(e);try{return t().finally(n)}catch(o){return n(),Promise.reject(o)}}async function vGa(e,t){let n=e.sessions.get(t);n&&(e.v4Gateway?.assertSessionRuntimeDeactivatable(t),n.unsubscribe?.(),e.v4Gateway?.deactivateSession(t),e.sessions.delete(t),await n.app.close?.(),await n.eventStore.deleteSession(t))}function aGo(e){return{deactivate:r(t=>vGa(e,t),"deactivate"),listSessionIds:r(()=>[...e.sessions.keys()],"listSessionIds"),readResidencyFacts:r(t=>{let n=e.sessions.get(t);return n?{hasPendingInteractions:e.v4Interactions.hasPendingForSession(t),hasQueuedCommands:e.v4Gateway?.hasResidencyBlockingCommands(t)??!1,hasLegacySubscriber:n.legacyStreamSubscribed===!0,hasResidencyBlockingWork:n.activeAbortController!==void 0||(n.residencyFinalizationCount??0)>0||n.app.runtime.hasResidencyBlockingWork(),hasSubscribers:e.v4Gateway?.hasConversationSubscribers(t)??!1,lastActivityAt:n.updatedAt,persisted:n.persistence==="immediate"}:null},"readResidencyFacts"),onDeactivated:r((t,n)=>{e.logger?.info("Session resident runtime deactivated",{...sGo(n),event:"zcode_protocol.session.resident_deactivated",sessionId:t})},"onDeactivated"),onError:r((t,n,o)=>{e.logger?.warn("Session resident deactivation failed",{...sGo(o),error:n instanceof Error?n.message:String(n),event:"zcode_protocol.session.resident_deactivation_failed",sessionId:t})},"onError")}}function sGo(e){return{highWaterCount:e.highWaterCount,idleMs:e.idleMs,idleTimeoutMs:e.idleTimeoutMs,reason:e.reason,residentCountBefore:e.residentCountBefore,targetCount:e.targetCount}}var a3e=Y(()=>{"use strict";r(yGa,"acquireSessionResidencyFinalization");r(g9,"runWithSessionResidencyFinalization");r(vGa,"deactivateSessionRecord");r(aGo,"createSessionResidentPoolHost");r(sGo,"deactivationLogContext")});async function D8(e,t,n){let o=n.modelExecution?.selectionScope==="execution";if(!o&&t.restoreWarning&&e.hasUsableRuntimeModelTarget?.(t)===!0&&(e.logger?.info?.("v4 restoreWarning cleared by model catalog recovery",{sessionId:t.app.sessionId,warningType:t.restoreWarning.type}),t.restoreWarning=void 0),!o&&t.restoreWarning)throw new txt("restoreWarning",t.restoreWarning.message);o||await e.ensureModelReady?.(t),t.persistence==="deferred"&&(t.persistence="immediate");let s=t.activeAutomationId,a=t.activeOffPeakTaskId,l=t.activeBotDeliveryTarget,u=SGa(n),f=wGa(n),g=bGa(n,u,f);u&&(t.activeAutomationId=u),f&&(t.activeOffPeakTaskId=f),t.activeBotDeliveryTarget=n.botDeliveryTarget;let _;try{_=await t.app.sendInput({text:n.content,...n.attachments?{attachments:n.attachments}:{}},{delivery:"start_turn",...n.intent?.requestedDelivery==="guide"?{queueDelivery:"guide"}:{},...n.browserAmbientContext?{browserAmbientContext:n.browserAmbientContext}:{},inputId:n.inputId,...n.inputPresentation?{inputPresentation:n.inputPresentation}:{},...fPn({automationId:u,offPeakTaskId:f,offPeakRunType:n.offPeakRunType}),intent:n.intent,...n.modelExecution?{modelExecution:n.modelExecution}:{},...n.sharedContextRefs?{sharedContextRefs:n.sharedContextRefs}:{},...g?{toolDisallowlist:g}:{},...n.requireIdle?{requireIdle:!0}:{},queryId:n.inputId})}catch(w){throw ext(t,s,a,l),await e.afterLegacyStateMutation?.(t,"prompt_failed"),w}if(_.kind==="rejected")throw ext(t,s,a,l),new txt("activePrompt",`Core prompt admission rejected: ${_.reason}`);if(_.kind==="queued")return ext(t,s,a,l),{admission:_,turnStarted:Promise.resolve()};let b=g9(t,async()=>{let w="prompt_completed";try{await _.completion}catch(T){w="prompt_failed",e.logger?.warn?.("v4 background turn failed",{error:T instanceof Error?T.message:String(T),inputId:n.inputId,sessionId:t.app.sessionId})}finally{ext(t,s,a,l),await e.afterLegacyStateMutation?.(t,w)}});return b.catch(()=>{}),e.logger?.info?.("v4 prompt admitted",{attachmentCount:n.attachments?.length??0,inputId:n.inputId,sessionId:t.app.sessionId,textLength:n.content.length}),{admission:_,completion:b,turnStarted:Promise.resolve()}}function ext(e,t,n,o){e.activeAutomationId=t,e.activeOffPeakTaskId=n,e.activeBotDeliveryTarget=o}function bGa(e,t=e.automationId,n=e.offPeakTaskId){let o=new Set(e.toolDisallowlist??[]);if(t)for(let s of kGa)o.add(s);if(n)for(let s of xGa)o.add(s);return o.size>0?[...o]:void 0}function SGa(e){let t=e.automationId?.trim();if(t)return t;let n=e.inputId.trim();if(!n.startsWith(cGo))return;let o=n.indexOf(":"),s=o>=0?n.slice(0,o):n;return s.length>cGo.length?s:void 0}function wGa(e){let t=e.offPeakTaskId?.trim();if(t)return t;let n=e.inputId.trim();if(!n.startsWith(lGo))return;let o=n.indexOf(":"),s=o>=0?n.slice(0,o):n;return s.length>lGo.length?s:void 0}function fPn(e){return e.automationId?{automationId:e.automationId}:e.offPeakTaskId?{offPeakTaskId:e.offPeakTaskId,...e.offPeakRunType?{offPeakRunType:e.offPeakRunType}:{}}:{}}var txt,cGo,kGa,lGo,xGa,zbe=Y(()=>{"use strict";a3e();txt=class extends Error{static{r(this,"V4PromptRejectedError")}reasonCode;turnStartUncertain=!1;constructor(t,n){super(n),this.reasonCode=t,this.name="V4PromptRejectedError"}};r(D8,"startPromptTurn");r(ext,"clearPromptRecordState");r(bGa,"buildTurnToolDisallowlist");r(SGa,"resolveTurnAutomationId");r(wGa,"resolveTurnOffPeakTaskId");r(fPn,"turnBackgroundAttributionOf");cGo="automation-",kGa=["CronCreate","CronUpdate","CronDelete"],lGo="offpeak-",xGa=["OffPeakCreate","SendMessage","Workflow"]});function Wp(e,t){if(t===null)throw new c3e("(null)");let n=e.getRecord(t);if(!n)throw new c3e(t);return n}var c3e,cN=Y(()=>{"use strict";c3e=class extends Error{static{r(this,"V4SessionNotFoundError")}constructor(t){super(`v4 command session not found: ${t}`),this.name="V4SessionNotFoundError"}};r(Wp,"requireRecord")});function nxt(e){let t=e.requestAuth?TGa(e.requestAuth):void 0;return{...e.memoryExtraction?{memoryExtraction:e.memoryExtraction}:{},selectionScope:"execution",...t?{requestDependencies:{requestAuth:{source:{resolve:r(async()=>t,"resolve")}}}}:{},...e.subagents?{subagents:e.subagents}:{}}}function TGa(e){return Object.freeze({...e.apiKey?{apiKey:e.apiKey}:{},...e.headers?{headers:Object.freeze({...e.headers})}:{}})}var mPn=Y(()=>{"use strict";r(nxt,"createModelExecutionContext");r(TGa,"freezeRequestAuth")});function uGo(e,t,n){if(e.turnId!==t.turnId||e.outputAt!==void 0||t.type!==lt.CompactStarted&&t.type!==lt.CompactCompleted&&t.type!==lt.CompactFailed)return!1;let o=t.payload,s=e.details??=[],a=`compact:${o.operationId}`,l=s.find(u=>u.id===a);if(!l&&t.type===lt.CompactStarted){if(s.length>=Ez)return e.truncated=!0,!0;l={id:a,stage:"compaction",start:n,source:"cli"},s.push(l)}if(l&&t.type!==lt.CompactStarted&&l.end===void 0){if(n<l.start)return e.clockInvalid=!0,!0;l.end=n,l.outcome=o.status==="interrupted"?"cancelled":t.type===lt.CompactCompleted?"completed":"failed"}return!0}var dGo=Y(()=>{"use strict";nr();ms();r(uGo,"observeLocalTtftCompaction")});var rxt,pGo=Y(()=>{"use strict";rxt=class{static{r(this,"LocalTtftClockWatch")}timer;constructor(t,n){let o=t(),s=Date.now();this.timer=setInterval(()=>{let a=t(),l=Date.now(),u=a-o,f=u>5e3||u<0||Math.abs(l-s-u)>100;o=a,s=l,n(f)},1e3),this.timer.unref()}dispose(){clearInterval(this.timer)}}});function mGo(e,t){let n=t,o=l3e(n.launchInputId);if(o===void 0)return null;let s=l3e(t.toolCallId);if(t.eventType===IGa){let a=l3e(n.actorSessionId),l=EGa(t.payload.actor);return a===void 0||l===void 0?null:rC.parse({...e,kind:"workflow.lifecycle",phase:"actor-spawned",sourceCommandId:o,runId:t.runId,...s===void 0?{}:{toolCallId:s},agentId:l,childSessionId:a})}if(t.eventType===CGa){let a=AGa(t.payload.status);if(a===void 0)return null;let l=a==="stopped"?PGa(t.payload.stopReason):void 0,u=l3e(DGa(t.payload.error)?.message),f=a==="completed"?void 0:u??(a==="stopped"?RGa(l):void 0);return rC.parse({...e,kind:"workflow.lifecycle",phase:"run-settled",sourceCommandId:o,runId:t.runId,...s===void 0?{}:{toolCallId:s},status:a,...l===void 0?{}:{stopReason:l},...f===void 0?{}:{errorMessage:f}})}return null}function EGa(e){if(typeof e!="object"||e===null)return;let t=e,n=l3e(t.siteId);if(!(n===void 0||typeof t.ordinal!="number"||!Number.isFinite(t.ordinal)))return`${n}@${t.ordinal}`}function AGa(e){return e==="completed"||e==="errored"||e==="stopped"?e:void 0}function PGa(e){return e==="user"||e==="model"||e==="provider"||e==="interrupted"||e==="superseded"?e:void 0}function RGa(e){return e===void 0?fGo:`${fGo} (${e})`}function DGa(e){return typeof e=="object"&&e!==null?e:void 0}function l3e(e){return typeof e=="string"&&e.length>0?e:void 0}var IGa,CGa,fGo,hGo=Y(()=>{"use strict";g0();IGa="actor-created",CGa="run-settled",fGo="Workflow run stopped";r(mGo,"workflowLifecycleFactFromProgress");r(EGa,"actorRefString");r(AGa,"settledStatus");r(PGa,"settledStopReason");r(RGa,"stoppedMessage");r(DGa,"errorRecord");r(l3e,"optionalString")});function Bd(e){return typeof e=="string"&&e.length>0?e:void 0}function Y2(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function oxt(e){if(e)try{return new URL(e).hostname||void 0}catch{return}}function X2(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function OGa(e,t){if(e!=="Skill")return{};let n=X2(t),o=Bd(n.qualifiedName),s=Bd(n.pluginId),a=Bd(n.source);return{...o?{skillQualifiedName:o}:{},...s?{skillPluginId:s}:{},...a?{skillSource:a}:{}}}function gPn(e){let t=X2(e._meta),n=X2(t.zcode),o=X2(t.claudeCode);return Bd(e.parentToolCallId)??Bd(e.parentToolUseId)??Bd(t.parentToolCallId)??Bd(t.parentToolUseId)??Bd(n.parentToolCallId)??Bd(n.parentToolUseId)??Bd(o.parentToolCallId)??Bd(o.parentToolUseId)}function gGo(e,t={}){let n=Bd(e.parentToolCallId)??Bd(t.parentToolCallId),o=Bd(e.childToolCallId)??Bd(t.childToolCallId),s=Bd(e.agentId)??Bd(t.agentId),a=Bd(e.agentType)??Bd(t.agentType),l=Bd(e.childSessionId)??Bd(t.childSessionId);return{...n?{parentToolCallId:n}:{},...o?{childToolCallId:o}:{},...s?{agentId:s}:{},...a?{agentType:a}:{},...l?{childSessionId:l}:{},...e.background===!0?{background:!0}:{}}}function MGa(e){let t=e.timestamp instanceof Date?e.timestamp.getTime():Number(e.timestamp);return Number.isFinite(t)&&t>=0?t:0}function NGa(e,t){if(!e||!t)return{};let n=NKt(e);return!n||n.automationId!==t?{automationId:t}:{automationId:t,taskTrigger:n.trigger,...n.scheduledAt!==void 0?{scheduledAt:n.scheduledAt}:{}}}function LGa(e){let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return}let n=X2(t);return Bd(X2(n.automation).automationId)}function FGa(e){return GV({totalTokens:Y2(e.totalTokens),inputTokens:Y2(e.inputTokens),outputTokens:Y2(e.outputTokens),cacheReadTokens:Y2(e.cacheReadTokens)??Y2(e.cacheTokens),cacheWriteTokens:Y2(e.cacheWriteTokens),reasoningTokens:Y2(e.reasoningTokens)})}function jGa(e){if(!e)return;let t=e.detail?.kind==="command"?e.detail.command:void 0,n=e.detail?.kind==="filesystem"||e.detail?.kind==="patch"?e.detail.filesystem:void 0,o=e.detail?.kind==="patch"?e.detail.patch:void 0,s={...e.totalMs!==void 0?{totalMs:e.totalMs}:{},...e.permissionWaitMs!==void 0?{permissionWaitMs:e.permissionWaitMs}:{},...t?.runMs!==void 0?{commandRunMs:t.runMs}:{},...t?.firstOutputMs!==void 0?{firstOutputMs:t.firstOutputMs}:{},...t?.noOutputMs!==void 0?{noOutputMs:t.noOutputMs}:{},...t?.exitCode!==void 0?{exitCode:t.exitCode}:{},...t?.timedOut!==void 0?{timedOut:t.timedOut}:{},...t?.outputBytes!==void 0?{outputBytes:t.outputBytes}:{},...t?.category!==void 0?{commandCategory:t.category}:{},...t?.name!==void 0?{commandName:t.name}:{},...t?.count!==void 0?{commandCount:t.count}:{},...t?.status!==void 0?{commandStatus:t.status}:{},...n?.readMs!==void 0?{fsReadMs:n.readMs}:{},...n?.writeMs!==void 0?{fsWriteMs:n.writeMs}:{},...n?.fileCount!==void 0?{fileCount:n.fileCount}:{},...n?.totalBytes!==void 0?{totalBytes:n.totalBytes}:{},...n?.maxFileBytes!==void 0?{maxFileBytes:n.maxFileBytes}:{},...n?.workspaceKind!==void 0?{workspaceKind:n.workspaceKind}:{},...o?.matchMs!==void 0?{patchMatchMs:o.matchMs}:{},...o?.hunkCount!==void 0?{hunkCount:o.hunkCount}:{},...o?.matchAttempts!==void 0?{matchAttempts:o.matchAttempts}:{}};return Object.keys(s).length>0?s:void 0}function BGa(e){return e==="success"?"success":e==="cancelled"?"interrupted":"failed"}function _Go(e,t){return`${e}\0${t??""}`}function vGo(e){return e===void 0||e==="main_turn"||e==="subagent"||e==="workflow_child"}function UGa(e){return vGo(e.querySource)&&(e.querySource!==void 0||e.stopReason!=="tool_internal")}function zGa(e){switch(e){case"completed":case"failed":case"interrupted":return e;default:return null}}var yGo,hPn,$be,qbe,_Pn=Y(()=>{"use strict";nr();ms();hGo();g0();yGo=2e3,hPn=class{static{r(this,"BoundedKeySet")}keys=new Set;add(t){if(this.keys.has(t))return!1;if(this.keys.add(t),this.keys.size>yGo){let n=this.keys.values().next().value;typeof n=="string"&&this.keys.delete(n)}return!0}deletePrefix(t){for(let n of this.keys)n.startsWith(t)&&this.keys.delete(n)}},$be=class{static{r(this,"BoundedValueMap")}values=new Map;get(t){return this.values.get(t)}set(t,n){if(this.values.delete(t),this.values.set(t,n),this.values.size>yGo){let o=this.values.keys().next().value;typeof o=="string"&&this.values.delete(o)}}delete(t){this.values.delete(t)}deletePrefix(t){for(let n of this.values.keys())n.startsWith(t)&&this.values.delete(n)}};r(Bd,"optionalString");r(Y2,"nonNegative");r(oxt,"providerHostname");r(X2,"recordValue");r(OGa,"skillTelemetryFactFields");r(gPn,"streamingParentToolCallId");r(gGo,"mirroredSubagentToolFields");r(MGa,"eventTimestamp");r(NGa,"automationAdmission");r(LGa,"cronCreateAutomationId");r(FGa,"totalTokensOf");r(jGa,"toToolPerformanceFact");r(BGa,"terminalStatus");r(_Go,"modelRequestQueueKey");r(vGo,"isStepUsageQuerySource");r(UGa,"isStepUsageModelComplete");r(zGa,"compactTerminalStatus");qbe=class{static{r(this,"ConversationTelemetryFactNormalizer")}firstStreamChunks=new hPn;sourceCommandByTurn=new $be;toolNameByCall=new $be;modelBySession=new $be;completedModelRequests=new $be;normalize(t,n,o){let s=n.turnId?String(n.turnId):void 0,a=s?`${t}\0${s}`:void 0,l={...o?.memoryEnabled!==void 0?{memoryEnabled:o.memoryEnabled}:{},version:1,eventId:String(n.id),eventSeq:Math.max(0,Math.floor(n.sequenceNumber)),occurredAt:MGa(n),sessionId:t,...s?{turnId:s}:{}},u=a?this.sourceCommandByTurn.get(a):void 0;switch(n.type){case lt.TurnStarted:{let f=n.payload,g=f.backgroundSource==="bash"||f.backgroundSource==="subagent"||f.backgroundSource==="workflow"?f.backgroundSource:void 0,_=Bd(f.inputId);return a&&_&&this.sourceCommandByTurn.set(a,_),rC.parse({...l,kind:"turn.started",..._?{sourceCommandId:_}:{},...NGa(_,Bd(f.automationId)),...Bd(f.offPeakTaskId)?{offPeakTaskId:Bd(f.offPeakTaskId)}:{},...f.offPeakRunType?{offPeakRunType:f.offPeakRunType}:{},...f.executionKind?{executionKind:f.executionKind}:{},...f.inputSource?{inputSource:f.inputSource}:{},...g?{backgroundSource:g}:{}})}case lt.ModelNetworkStatus:{let f=n.payload;if(f.type==="model_request_queued"||f.type==="model_request_admitted")return null;let g=String(f.providerId),_=String(f.modelId);this.modelBySession.set(t,{modelName:_,modelProvider:g});let b=rC.parse({...l,kind:"model.request.status",...u?{sourceCommandId:u}:{},requestId:String(f.requestId),status:f.type,providerId:g,modelId:_,...f.providerKind?{providerKind:f.providerKind}:{},...oxt(f.baseURL)?{providerHostname:oxt(f.baseURL)}:{},transport:f.transport,...f.querySource?{querySource:f.querySource}:{},...f.queryId?{queryId:String(f.queryId)}:{},attempt:f.attempt,maxAttempts:f.maxAttempts,...f.type==="model_request_completed"?{durationMs:f.durationMs}:{},...f.type==="model_request_failed"?{...f.durationMs!==void 0?{durationMs:f.durationMs}:{},reason:f.reason,retryable:f.retryable,...f.statusCode!==void 0?{statusCode:f.statusCode}:{}}:{},...f.type==="model_retry_scheduled"?{delayMs:f.delayMs,nextAttempt:f.nextAttempt,reason:f.reason,...f.statusCode!==void 0?{statusCode:f.statusCode}:{}}:{},...f.type==="model_stream_stalled"?{idleMs:f.idleMs,timeoutMs:f.timeoutMs}:{}}),w=Bd(f.querySource);if(f.type==="model_request_completed"&&vGo(w)){let T=_Go(t,w),I=this.completedModelRequests.get(T)??[];I.push({requestId:String(f.requestId),providerId:g,modelId:_,...f.providerKind?{providerKind:f.providerKind}:{},...oxt(f.baseURL)?{providerHostname:oxt(f.baseURL)}:{}}),this.completedModelRequests.set(T,I)}return b}case lt.ModelStreaming:{let f=n.payload,g=X2(n.payload),_=f.kind==="text_delta"?"text":f.kind==="reasoning_delta"?"thought":null;if(!_)return null;let b=gPn(g),w=`${t}\0${s??""}\0${_}\0${String(f.partId??"")}\0${b??""}`;return rC.parse({...l,kind:"stream.chunk",...u?{sourceCommandId:u}:{},channel:_,chunkLength:f.delta.length,firstChunk:this.firstStreamChunks.add(w),...f.assistantMessageId?{assistantMessageId:String(f.assistantMessageId)}:{},...f.partId?{partId:String(f.partId)}:{},...b?{parentToolCallId:b}:{}})}case lt.ToolCallScheduled:{let f=n.payload,g=X2(n.payload),_=String(f.toolCallId);return this.toolNameByCall.set(`${a??t}\0${_}`,f.toolName),rC.parse({...l,kind:"tool.lifecycle",...u?{sourceCommandId:u}:{},phase:"scheduled",toolCallId:_,toolName:f.toolName,...gGo(g)})}case lt.ToolCallStarted:case lt.ToolCallProgress:case lt.ToolCallResult:case lt.ToolCallError:{let f=n.payload,g=X2(n.payload),_=String(f.toolCallId),b=`${a??t}\0${_}`,T=("toolName"in f?Bd(f.toolName):void 0)??this.toolNameByCall.get(b),I=n.type===lt.ToolCallResult?f:null,E=n.type===lt.ToolCallError?f:null,R=X2(I?.result.display),L=jGa(I?.result.perf),U=n.type===lt.ToolCallStarted?"started":n.type===lt.ToolCallProgress?"progress":n.type===lt.ToolCallResult?I?.result.success===!1?"failed":"completed":"failed",B=U==="completed"&&T==="CronCreate"?LGa(I?.result.content):void 0;return(U==="completed"||U==="failed")&&this.toolNameByCall.delete(b),rC.parse({...l,kind:"tool.lifecycle",...u?{sourceCommandId:u}:{},phase:U,toolCallId:_,...T?{toolName:T}:{},...B?{automationId:B}:{},...I?{durationMs:I.duration}:{},...E?{errorCode:E.error.code??E.error.type}:{},...E?{errorMessage:E.error.message}:{},...I?.result.error?{errorCode:I.result.error.code??I.result.error.type}:{},...I?.result.error?{errorMessage:I.result.error.message}:{},...OGa(T,E?.skillMetadata??I?.skillMetadata),...gGo(g,R),...L?{performance:L}:{}})}case lt.PermissionRequested:case lt.PermissionResolved:case lt.PermissionDenied:{let f=n.payload,g=X2(f),_=n.type===lt.PermissionRequested?f:null,b=n.type===lt.PermissionResolved?f:null,w=n.type===lt.PermissionDenied?f:null;return rC.parse({...l,kind:"permission.lifecycle",...u?{sourceCommandId:u}:{},phase:_?"requested":b?"resolved":"denied",...Bd(_?.requestId??b?.requestId)?{requestId:Bd(_?.requestId??b?.requestId)}:{},toolCallId:String(f.toolCallId),..._?.toolName?{toolName:_.toolName}:w?.toolName?{toolName:w.toolName}:{},...Bd(g.childSessionId)?{childSessionId:Bd(g.childSessionId)}:{},...g.background===!0?{background:!0}:{},...b?{decision:b.decision}:{}})}case lt.ModelComplete:{let f=n.payload,g=_Go(t,Bd(f.querySource)),_=this.completedModelRequests.get(g)??[],b=_.shift();if(_.length>0?this.completedModelRequests.set(g,_):this.completedModelRequests.delete(g),!UGa(f))return null;let w=X2(f.usage);return rC.parse({...l,kind:"usage.delta",...u?{sourceCommandId:u}:{},...b?{requestId:b.requestId,providerId:b.providerId,modelId:b.modelId,...b.providerKind?{providerKind:b.providerKind}:{},...b.providerHostname?{providerHostname:b.providerHostname}:{}}:{},inputTokens:Y2(w.inputTokens)??0,outputTokens:Y2(w.outputTokens)??0,totalTokens:FGa(w),reasoningTokens:Y2(w.reasoningTokens)??0,cacheReadTokens:Y2(w.cacheReadTokens)??Y2(w.cacheTokens)??0,cacheWriteTokens:Y2(w.cacheWriteTokens)??0})}case lt.DynamicWorkflowRunProgress:return mGo(l,n.payload);case lt.SubagentSpawned:case lt.SubagentStopped:{let f=X2(n.payload),g=Bd(f.agentId),_=Bd(f.childSessionId);return!g||!_?null:rC.parse({...l,kind:"subagent.lifecycle",...u?{sourceCommandId:u}:{},phase:n.type===lt.SubagentSpawned?"spawned":"stopped",agentId:g,...Bd(f.agentType)?{agentType:Bd(f.agentType)}:{},childSessionId:_,...Bd(f.parentToolCallId)?{parentToolCallId:Bd(f.parentToolCallId)}:{},background:f.background===!0,...Bd(f.status)?{status:Bd(f.status)}:{},...n.type===lt.SubagentStopped&&Bd(f.error)?{errorMessage:Bd(f.error)}:{}})}case lt.TurnComplete:{let f=n.payload,g=Bd(f.inputId)??u,_=rC.parse({...l,kind:"turn.terminal",...g?{sourceCommandId:g}:{},status:BGa(f.resultType),resultType:f.resultType,durationMs:f.duration,tokenCount:f.tokenCount,toolCallCount:f.toolCallCount,...f.resultType==="cancelled"?{errorCode:"USER_INTERRUPT",errorMessage:"User stopped generation"}:{},...f.backgroundSubagentResultConsumed?{backgroundSubagentResultConsumed:!0}:{},...f.workflowResultConsumed?{workflowResultConsumed:!0}:{}});return this.clearTurn(a),_}case lt.TurnError:{let f=n.payload,g=Bd(f.inputId)??u,_=rC.parse({...l,kind:"turn.terminal",...g?{sourceCommandId:g}:{},status:"failed",errorCode:f.error.code??f.error.type,errorMessage:f.error.message,...f.error.retryable!==void 0?{errorRetryable:f.error.retryable}:{},...f.backgroundSubagentResultConsumed?{backgroundSubagentResultConsumed:!0}:{},...f.workflowResultConsumed?{workflowResultConsumed:!0}:{},turnPhase:f.turnPhase});return this.clearTurn(a),_}case lt.CompactCompleted:case lt.CompactFailed:{let f=n.payload,g=zGa(f.status);if(!g)return null;let b=this.modelBySession.get(t)??(o?.modelName||o?.modelProvider?{modelName:o.modelName??"",modelProvider:o.modelProvider??""}:void 0);return rC.parse({...l,kind:"compaction.terminal",...f.sourceCommandId?{sourceCommandId:f.sourceCommandId}:{},operationId:f.operationId,...f.messageId?{messageId:String(f.messageId)}:{},...f.summaryMessageId?{summaryMessageId:String(f.summaryMessageId)}:{},status:g,trigger:f.trigger,...f.compactReason?{compactReason:f.compactReason}:{},...f.reason?{reason:f.reason}:{},...f.attempt!==void 0?{attempt:f.attempt}:{},...f.maxAttempts!==void 0?{maxAttempts:f.maxAttempts}:{},...f.startedAt!==void 0?{startedAt:f.startedAt}:{},...f.endedAt!==void 0?{endedAt:f.endedAt}:{},...f.preCompactTokenCount!==void 0?{preCompactTokenCount:f.preCompactTokenCount}:{},...f.postCompactTokenCount!==void 0?{postCompactTokenCount:f.postCompactTokenCount}:{},...f.truePostCompactTokenCount!==void 0?{truePostCompactTokenCount:f.truePostCompactTokenCount}:{},...b||{}})}default:return null}}clearTurn(t){t&&(this.sourceCommandByTurn.delete(t),this.firstStreamChunks.deletePrefix(`${t}\0`),this.toolNameByCall.deletePrefix(`${t}\0`))}clearSession(t){let n=`${t}\0`;this.sourceCommandByTurn.deletePrefix(n),this.firstStreamChunks.deletePrefix(n),this.toolNameByCall.deletePrefix(n),this.modelBySession.delete(t),this.completedModelRequests.deletePrefix(n)}}});var bGo,ixt,SGo=Y(()=>{"use strict";dGo();pGo();nr();_Pn();bGo=require("node:crypto");g0();ixt=class{static{r(this,"LocalTtftRecorder")}now;onDrop;onCheckpoint;instanceId=(0,bGo.randomUUID)();clockWatch;preparationSubscriptions=new Map;normalizer=new qbe;requestState=new Map;queueSources=new Map;checkpointSignatures=new Map;completed=new Map;records=new Map;constructor(t=Gj,n=()=>{},o=()=>{}){this.now=t,this.onDrop=n,this.onCheckpoint=o}receive(t,n){return this.prune(),!t.ttft||this.records.has(t.commandId)||this.completed.has(t.commandId)?!0:this.records.size>=Kpe?!1:(this.records.set(t.commandId,{...t.ttft,instanceId:this.instanceId,commandId:t.commandId,...t.sessionId?{sessionId:t.sessionId}:{},receivedAt:this.now(),sendMode:n?"queued":"idle",details:[]}),this.clockWatch??=new rxt(this.now,o=>{if(o)for(let s of this.records.values())s.outputAt===void 0&&(s.clockInvalid=!0,this.checkpoint(s));this.prune(),this.records.size||(this.clockWatch?.dispose(),this.clockWatch=void 0)}),this.preparationSubscriptions.set(t.commandId,NSr(t.commandId,o=>{let s=this.records.get(t.commandId);if(!(!s||s.sessionId&&s.sessionId!==o.sessionId||s.turnId&&s.turnId!==o.turnId)){if(s.sessionId=o.sessionId,s.turnId=o.turnId,o.stage==="execution")s.executionAt??=o.start;else{let a=s.details??=[],l=a.findIndex(f=>f.id===o.id),u={id:o.id,stage:o.stage,start:o.start,end:o.end,outcome:o.outcome,source:"cli"};l>=0?a[l]=u:a.length<Ez?a.push(u):s.truncated=!0}this.checkpoint(s)}})),!0)}checkpoint(t){let n=JSON.stringify({...t,revision:void 0});if(this.checkpointSignatures.get(t.commandId)!==n){this.checkpointSignatures.set(t.commandId,n),t.revision=(t.revision??0)+1;try{this.onCheckpoint({...t,details:t.details?.map(o=>({...o}))})}catch{}}}admitted(t){let n=this.records.get(t);n&&(n.admittedAt??=this.now(),this.checkpoint(n))}event(t,n){if(!this.records.size)return;if(this.queueEvent(t,n),n.type===lt.CompactStarted||n.type===lt.CompactCompleted||n.type===lt.CompactFailed){let s=this.forSession(t);s&&uGo(s,n,this.now())&&this.checkpoint(s)}let o=this.normalizer.normalize(t,n);if(o&&this.fact(o,n.type===lt.TurnStarted?n.payload.executionStartedAt:void 0),n.type===lt.ModelNetworkStatus){let s=n.payload,a=this.forSession(t);if(a&&s.modelCall){a.requestId===s.requestId&&(a.logicalCallId=s.modelCall.logicalCallId);let l=a.details?.find(u=>u.requestId===s.requestId&&u.stage==="attempt");l&&(l.logicalCallId=s.modelCall.logicalCallId),this.checkpoint(a)}}if(n.type===lt.ModelStreaming){let s=n.payload;if(gPn(n.payload))return;if(s.kind==="tool_call"&&s.toolName?.trim()){this.output(t,n.turnId?String(n.turnId):void 0,"tool");return}if(!s.delta?.trim())return;let a=s.kind==="text_delta"?"text":s.kind==="reasoning_delta"?"reasoning":s.kind==="tool_input_delta"?"tool":void 0;a&&this.output(t,n.turnId?String(n.turnId):void 0,a)}}queueEvent(t,n){if(n.type===lt.TurnSteerQueued){let o=n.payload,s=o.intent?.sourceCommandId??o.inputId,a=s?this.records.get(s):void 0;a&&(!a.sessionId||a.sessionId===t)&&(a.sessionId=t,a.sendMode="queued",this.queueSources.set(o.pendingInputId,a.commandId),this.checkpoint(a))}if(n.type===lt.TurnSteerDrained){let o=n.payload;for(let s of o.drainedInputs??[]){if(s.delivery!=="guide")continue;let a=s.intent?.sourceCommandId??this.queueSources.get(s.pendingInputId),l=a?this.records.get(a):void 0;l?.sessionId===t&&(l.sendMode="guided",this.checkpoint(l),this.retire(l))}}if(n.type===lt.TurnSteerDiscarded){let o=n.payload;if(o.reason==="promoted")return;for(let s of o.pendingInputIds){let a=this.queueSources.get(s),l=a?this.records.get(a):void 0;l?.sessionId===t&&(l.terminal=o.reason==="turn_failed"?"failed":"cancelled",this.checkpoint(l),this.retire(l))}}}fact(t,n){this.prune();let o=t.sourceCommandId?this.records.get(t.sourceCommandId):void 0;if(!(!o||o.sessionId&&o.sessionId!==t.sessionId)){if(t.kind==="turn.started"){o.sessionId=t.sessionId,o.turnId=t.turnId,o.executionAt??=n,this.checkpoint(o);return}if(o.turnId===void 0&&t.kind==="turn.terminal"&&(o.turnId=t.turnId),o.turnId===t.turnId){if(t.kind==="model.request.status"&&o.outputAt===void 0){if(t.querySource!=="main_turn"&&t.querySource!=="compact")return;let s=t.querySource==="main_turn"?"response":"preparation",a=o.details??=[],l=`attempt:${t.requestId}`,u=a.find(f=>f.id===l);if(t.status==="model_request_started"&&!u){this.requestState.set(o.commandId,s),a.length<Ez?(u={id:l,stage:"attempt",start:this.now(),requestId:t.requestId,role:s,source:"cli"},a.push(u)):o.truncated=!0;for(let f of a)f.stage==="retry_wait"&&f.end===void 0&&f.role===s&&(f.end=this.now(),f.outcome="completed");s==="response"&&(o.requestAt??=this.now(),o.queryId??=t.queryId,o.requestId=t.requestId,o.model=t.modelId.slice(0,128),o.provider=t.providerId.slice(0,128))}(t.status==="model_request_failed"||t.status==="model_request_completed")&&u&&u.end===void 0&&(u.end=this.now(),u.outcome=t.status==="model_request_failed"?"failed":"completed",s==="response"&&t.status==="model_request_failed"&&o.requestId===t.requestId&&this.requestState.set(o.commandId,"failed")),t.status==="model_retry_scheduled"&&!a.some(f=>f.id===`retry:${t.requestId}`)&&(a.length<Ez?a.push({id:`retry:${t.requestId}`,stage:"retry_wait",start:this.now(),requestId:t.requestId,role:s,source:"cli"}):o.truncated=!0)}this.checkpoint(o),t.kind==="tool.lifecycle"&&t.phase==="scheduled"&&!t.parentToolCallId&&this.output(t.sessionId,t.turnId,"tool"),t.kind==="turn.terminal"&&(o.terminal=t.status==="success"?"completed":t.status==="failed"?"failed":"cancelled",this.checkpoint(o),this.retire(o))}}}output(t,n,o){for(let s of this.records.values())if(!(this.requestState.get(s.commandId)==="failed"||this.requestState.get(s.commandId)==="preparation")){if(s.sessionId===t&&s.turnId===n&&s.requestAt!==void 0&&s.outputAt===void 0){s.outputAt=this.now(),s.outputKind=o,this.preparationSubscriptions.get(s.commandId)?.(),this.preparationSubscriptions.delete(s.commandId);let a=s.details?.find(l=>l.id===`attempt:${s.requestId}`);a&&a.end===void 0&&(a.end=s.outputAt,a.outcome="first_output")}s.sessionId===t&&s.turnId===n&&s.requestAt!==void 0&&o==="text"&&this.retire(s)}}retire(t){if(this.forget(t.commandId),this.records.delete(t.commandId),this.records.size||(this.clockWatch?.dispose(),this.clockWatch=void 0),this.completed.set(t.commandId,t),this.completed.size>Kpe){this.completed.delete(this.completed.keys().next().value);try{this.onDrop()}catch{}}}forSession(t,n){return this.prune(),[...this.completed.values(),...this.records.values()].reverse().find(o=>o.sessionId===t&&(n?o.commandId===n:o.turnId!==void 0))}clear(){this.clockWatch?.dispose(),this.clockWatch=void 0;for(let t of this.preparationSubscriptions.values())t();this.preparationSubscriptions.clear(),this.records.clear(),this.requestState.clear(),this.queueSources.clear(),this.checkpointSignatures.clear(),this.completed.clear()}forget(t){this.preparationSubscriptions.get(t)?.(),this.preparationSubscriptions.delete(t),this.requestState.delete(t),this.checkpointSignatures.delete(t);for(let[n,o]of this.queueSources)o===t&&this.queueSources.delete(n)}prune(){let t=this.now();for(let n of[this.records,this.completed])for(let[o,s]of n)t-s.receivedAt>FHt&&(this.forget(o),n.delete(o))}}});function sxt(e,t,n){return`${e}\0${t}\0${n}`}function $Ga(e){return{fileName:e.fileName,mime:e.mime,totalBytes:e.totalBytes,totalChunks:e.totalChunks,checksum:e.checksum}}function wGo(e,t){return e.fileName===t.fileName&&e.mime===t.mime&&e.totalBytes===t.totalBytes&&e.totalChunks===t.totalChunks&&e.checksum===t.checksum}function qGa(e,t){if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n+=1)if(e[n]!==t[n])return!1;return!0}var kGo,axt,xGo=Y(()=>{"use strict";kGo=require("node:crypto");g0();r(sxt,"uploadKey");r($Ga,"metadataOf");r(wGo,"sameMetadata");r(qGa,"sameBytes");axt=class{static{r(this,"AttachmentUploadRegistry")}options;staged=new Map;committed=new Map;stagedBytes=0;constructor(t){this.options=t}begin(t){this.pruneExpired();let n=sxt(t.connectionId,t.sessionId,t.uploadId),o=$Ga(t),s=this.committed.get(n);if(s){if(!wGo(s.metadata,o))throw new Error("fault.attachment.beginConflict");return{uploadId:t.uploadId,state:"committed",nextChunkIndex:s.nextChunkIndex,ref:s.ref}}let a=this.staged.get(n);if(a){if(!wGo(a.metadata,o))throw new Error("fault.attachment.beginConflict");return a.expiresAt=this.options.now()+fc.attachmentUploadTtlMs,{uploadId:t.uploadId,state:"staging",nextChunkIndex:a.chunks.length}}if(this.staged.size>=fc.attachmentUploadMaxConcurrent)throw new Error("fault.attachment.tooManyUploads");if(t.totalChunks>0&&t.totalBytes>t.totalChunks*fc.attachmentChunkMaxBytes)throw new Error("fault.attachment.chunkCountInsufficient");return this.staged.set(n,{key:n,connectionId:t.connectionId,sessionId:t.sessionId,uploadId:t.uploadId,metadata:o,chunks:[],receivedBytes:0,expiresAt:this.options.now()+fc.attachmentUploadTtlMs,commitPromise:null}),{uploadId:t.uploadId,state:"staging",nextChunkIndex:0}}chunk(t){this.pruneExpired();let n=sxt(t.connectionId,t.sessionId,t.uploadId),o=this.staged.get(n);if(!o)throw new Error("fault.attachment.uploadNotFound");if(o.commitPromise)throw new Error("fault.attachment.commitInProgress");let s=new Uint8Array(Buffer.from(t.dataBase64,"base64"));if(t.chunkIndex<o.chunks.length){if(!qGa(o.chunks[t.chunkIndex],s))throw new Error("fault.attachment.chunkConflict");return{uploadId:t.uploadId,nextChunkIndex:o.chunks.length}}if(t.chunkIndex>o.chunks.length)throw new Error("fault.attachment.chunkGap");if(t.chunkIndex>=o.metadata.totalChunks)throw new Error("fault.attachment.tooManyChunks");if(s.byteLength===0)throw new Error("fault.attachment.emptyChunk");if(o.receivedBytes+s.byteLength>o.metadata.totalBytes)throw new Error("fault.attachment.totalBytesExceeded");if(this.stagedBytes+s.byteLength>fc.attachmentUploadMaxStagedBytes)throw new Error("fault.attachment.stagingCapacityExceeded");return o.chunks.push(s),o.receivedBytes+=s.byteLength,o.expiresAt=this.options.now()+fc.attachmentUploadTtlMs,this.stagedBytes+=s.byteLength,{uploadId:t.uploadId,nextChunkIndex:o.chunks.length}}async commit(t){this.pruneExpired();let n=sxt(t.connectionId,t.sessionId,t.uploadId),o=this.committed.get(n);if(o)return{ref:o.ref};let s=this.staged.get(n);if(!s)throw new Error("fault.attachment.uploadNotFound");if(s.commitPromise)return s.commitPromise;let a=this.commitStaged(s);s.commitPromise=a;try{return await a}catch(l){throw this.staged.get(n)===s&&(s.commitPromise=null),l}}async abort(t){this.pruneExpired();let n=sxt(t.connectionId,t.sessionId,t.uploadId),o=this.staged.get(n);if(o?.commitPromise){await o.commitPromise;return}this.deleteStaged(n)}clearConnection(t){this.clearWhere(n=>n.connectionId===t);for(let[n,o]of this.committed)o.connectionId===t&&this.committed.delete(n)}clearSession(t){this.clearWhere(n=>n.sessionId===t);for(let[n,o]of this.committed)o.sessionId===t&&this.committed.delete(n)}clear(){this.staged.clear(),this.committed.clear(),this.stagedBytes=0}pruneExpired(){let t=this.options.now();this.clearWhere(n=>n.expiresAt<=t&&n.commitPromise===null);for(let[n,o]of this.committed)o.expiresAt<=t&&this.committed.delete(n)}async commitStaged(t){if(t.chunks.length!==t.metadata.totalChunks||t.receivedBytes!==t.metadata.totalBytes)throw new Error("fault.attachment.uploadIncomplete");let n=(0,kGo.createHash)("sha256");for(let l of t.chunks)n.update(l);if(`sha256:${n.digest("hex")}`!==t.metadata.checksum)throw new Error("fault.attachment.checksumMismatch");let o=new Uint8Array(t.metadata.totalBytes),s=0;for(let l of t.chunks)o.set(l,s),s+=l.byteLength;let{ref:a}=await this.options.putSessionAttachment(t.sessionId,{fileName:t.metadata.fileName,mime:t.metadata.mime,bytes:o});return this.staged.get(t.key)===t&&this.deleteStaged(t.key),this.committed.set(t.key,{connectionId:t.connectionId,sessionId:t.sessionId,uploadId:t.uploadId,metadata:t.metadata,nextChunkIndex:t.chunks.length,ref:a,expiresAt:this.options.now()+fc.attachmentUploadTtlMs}),{ref:a}}deleteStaged(t){let n=this.staged.get(t);n&&(this.staged.delete(t),this.stagedBytes-=n.receivedBytes)}clearWhere(t){for(let[n,o]of this.staged)t(o)&&this.deleteStaged(n)}}});var u3e,cxt,TGo=Y(()=>{"use strict";u3e=class extends Error{static{r(this,"V4SubscribeSessionUnavailableError")}sessionId;reasonCode;constructor(t,n,o,s){super(`${o} (${n})`,s),this.sessionId=t,this.reasonCode=n,this.name="V4SubscribeSessionUnavailableError"}},cxt=class{static{r(this,"ColdSessionResumeCoordinator")}host;flights=new Map;constructor(t){this.host=t}ensureResumed(t,n,o){let s=this.flights.get(t);if(s)return this.host.onDebug?.(`cold resume joined existing flight session=${t}`),s;this.host.onDebug?.(`cold resume flight created session=${t}`);let a=this.resume(t,n,o).finally(()=>{this.flights.delete(t),this.host.onDebug?.(`cold resume flight cleared session=${t}`)});return this.flights.set(t,a),a}clear(){this.flights.clear()}async resume(t,n,o){let s=this.host.resumePersistedSession;if(!s)throw new u3e(t,"fault.subscribe.sessionNotFound",`Session is not active: ${t}`);let a;try{a=o?await s.call(this.host,t,n,o):await s.call(this.host,t,n)}catch(l){throw this.host.onError?.("v4.subscribe.resume",l,{phase:"resumePersistedSession",sessionId:t}),new u3e(t,"fault.subscribe.resumeFailed",`Failed to resume persisted session ${t}: ${l instanceof Error?l.message:String(l)}`,{cause:l})}if(a.status==="notFound")throw new u3e(t,"fault.subscribe.sessionNotFound",`Session is not active and not persisted: ${t}`);return a.persistedMessages}}});function d3e(e){return`queue_${e}`}var WGa,lxt,uxt,dxt=Y(()=>{"use strict";g0();WGa="@global";r(d3e,"queueItemIdForCommand");lxt=class{static{r(this,"AsyncGateRegistry")}tails=new Map;async acquire(t){let n=this.tails.get(t)??Promise.resolve(),o,s=new Promise(u=>{o=u}),a=n.then(()=>s);this.tails.set(t,a),await n;let l=!1;return()=>{l||(l=!0,o(),this.tails.get(t)===a&&this.tails.delete(t))}}},uxt=class{static{r(this,"CommandInbox")}host;inFlight=new Map;liveInputs=new Map;settled=new Map;admissionSeq=new Map;keyGates=new lxt;sessionGates=new lxt;constructor(t){this.host=t}async handle(t){let n=wPe(t);if(!n.ok)return this.ackOnly({commandId:this.extractCommandId(t),status:"rejected",reasonCode:"proto.invalidPayload",message:n.error.message,revisionAtDecision:0});let o=n.envelope,s={sessionId:o.sessionId,commandId:o.commandId},a=this.bucketKey(o.sessionId),l=await this.keyGates.acquire(this.keyGateKey(s));try{let u=this.inFlight.get(a)?.get(o.commandId);if(u)return this.ackOnly(this.retryAck(await u.final));let f=await this.lookupExact(s);if(f)return this.ackOnly(this.retryAck(f));let g=await this.sessionGates.acquire(a);try{let _=this.inFlight.get(a)?.get(o.commandId);if(_)return g(),this.ackOnly(this.retryAck(await _.final));let b=await this.lookupExact(s);if(b)return g(),this.ackOnly(this.retryAck(b));let w=this.decide(o);if(w.kind==="ack")return w.remember&&this.rememberSettled(a,o.commandId,w.ack),g(),this.ackOnly(w.ack);let T=(this.admissionSeq.get(a)??0)+1,I=this.host.now?.()??Date.now();this.admissionSeq.set(a,T);let E,R=new Promise(B=>{E=B}),L={ack:w.ack,final:R,resolveFinal:E};this.mapFor(this.inFlight,a).set(o.commandId,L),l();let U=!1;return{kind:"execute",envelope:o,ack:w.ack,admissionSeq:T,admittedAt:I,queueItemId:d3e(o.commandId),settle:r(B=>{if(U)return;U=!0;let z=this.liveInputs.get(a)?.get(o.commandId),$={...w.ack,...B};this.inFlight.get(a)?.delete(o.commandId),z?z.ack=$:this.rememberSettled(a,o.commandId,$),L.resolveFinal($),g()},"settle")}}catch(_){throw g(),_}}catch(u){return this.ackOnly(this.queryUnavailableAck(s,u))}finally{l()}}async query(t){return Promise.all(t.map(n=>this.queryOne(n)))}pinLiveInput(t,n,o){let s=this.bucketKey(t),a=this.inFlight.get(s)?.get(n.sourceCommandId)?.ack;this.mapFor(this.liveInputs,s).set(n.sourceCommandId,{intent:n,ack:o??a??{commandId:n.sourceCommandId,status:"accepted",revisionAtDecision:0}}),this.settled.get(s)?.delete(n.sourceCommandId)}releaseLiveInput(t,n){let o=this.bucketKey(t.sessionId),s=this.liveInputs.get(o)?.get(t.commandId);this.liveInputs.get(o)?.delete(t.commandId),(n??s?.ack)&&this.rememberSettled(o,t.commandId,n??s.ack)}hasPinnedSessionState(t){let n=this.bucketKey(t);return(this.inFlight.get(n)?.size??0)>0||(this.liveInputs.get(n)?.size??0)>0}clearSession(t){let n=this.bucketKey(t);return this.hasPinnedSessionState(t)?!1:(this.inFlight.delete(n),this.liveInputs.delete(n),this.settled.delete(n),this.admissionSeq.delete(n),!0)}async queryOne(t){let n=await this.keyGates.acquire(this.keyGateKey(t));try{return{key:t,result:await this.lookupExact(t)??"unknown"}}catch(o){return{key:t,result:this.queryUnavailableAck(t,o)}}finally{n()}}async lookupExact(t){let n=this.bucketKey(t.sessionId),o=this.inFlight.get(n)?.get(t.commandId);if(o)return await o.final;let s=this.liveInputs.get(n)?.get(t.commandId);if(s)return s.ack;let a=this.settled.get(n)?.get(t.commandId);if(a)return this.touchSettled(n,t.commandId,a),a;for(let l of[this.host.lookupTranscriptCommand,this.host.lookupTimelineCommand,this.host.lookupChildCommand,this.host.lookupDiscardedCommand]){let u=await l?.(t);if(u)return u}return null}decide(t){let n=t.sessionId===null?0:this.host.getRevision(t.sessionId);if(n===null||t.type!=="createSession"&&t.sessionId===null)return{kind:"ack",remember:!1,ack:{commandId:t.commandId,status:"rejected",reasonCode:"proto.sessionNotFound",revisionAtDecision:0}};if(cYt.has(t.type)){if(t.baseRevision===void 0)return{kind:"ack",remember:!1,ack:{commandId:t.commandId,status:"rejected",reasonCode:"proto.missingBaseRevision",revisionAtDecision:n}};let a=t.sessionId===null?null:this.host.getLogEpoch(t.sessionId);if(lYt.has(t.type)&&t.baseLogEpoch!==a)return{kind:"ack",remember:!1,ack:{commandId:t.commandId,status:"stale",reasonCode:"proto.staleLogEpoch",revisionAtDecision:n}};if(t.baseRevision!==n)return{kind:"ack",remember:!1,ack:{commandId:t.commandId,status:"stale",reasonCode:"proto.staleRevision",revisionAtDecision:n}}}let o=this.host.validateRowTarget?.(t);if(o?.verdict==="stale")return{kind:"ack",remember:!1,ack:{commandId:t.commandId,status:"stale",reasonCode:o.reasonCode,message:o.message,revisionAtDecision:n}};if(o?.verdict==="reject")return{kind:"ack",remember:!1,ack:{commandId:t.commandId,status:"rejected",reasonCode:o.reasonCode,message:o.message,revisionAtDecision:n}};let s=this.host.guard?.(t)??{verdict:"allow"};return s.verdict==="stale"?{kind:"ack",remember:!1,ack:{commandId:t.commandId,status:"stale",reasonCode:s.reasonCode,message:s.message,revisionAtDecision:n}}:s.verdict==="reject"?{kind:"ack",remember:!1,ack:{commandId:t.commandId,status:"rejected",reasonCode:s.reasonCode,message:s.message,revisionAtDecision:n}}:s.verdict==="noop"?{kind:"ack",remember:!0,ack:{commandId:t.commandId,status:"noop",reasonCode:s.reasonCode,revisionAtDecision:n,result:s.result}}:{kind:"execute",ack:{commandId:t.commandId,status:"accepted",revisionAtDecision:n}}}retryAck(t){return t.status==="failed"?t:{...t,status:"duplicate"}}queryUnavailableAck(t,n){return{commandId:t.commandId,status:"failed",reasonCode:"fault.command.queryUnavailable",revisionAtDecision:t.sessionId===null?0:this.host.getRevision(t.sessionId)??0}}ackOnly(t){return{kind:"ack",ack:t}}bucketKey(t){return t??WGa}keyGateKey(t){return`${this.bucketKey(t.sessionId)}\0${t.commandId}`}mapFor(t,n){let o=t.get(n);return o||(o=new Map,t.set(n,o)),o}touchSettled(t,n,o){let s=this.mapFor(this.settled,t);s.delete(n),s.set(n,o)}rememberSettled(t,n,o){let s=this.mapFor(this.settled,t);for(s.delete(n),s.set(n,o);s.size>fc.idempotencyTablePerSession;){let a=s.keys().next().value;if(a===void 0)break;s.delete(a)}}extractCommandId(t){if(typeof t=="object"&&t!==null&&"commandId"in t){let n=t.commandId;if(typeof n=="string")return n}return""}}});function IGo(e){return e.op==="workflowRun.updated"||e.op==="workflowRun.removed"}function CGo(e,t){let n=-1;for(let a=e.length-1;a>=0;a-=1)if(IGo(e[a])){n=a;break}if(n<0)return e;let o=t===void 0?null:{op:"state.updated",patch:{workflowRuns:iQe(t)}},s=[];for(let a=0;a<e.length;a+=1){let l=e[a];if(!IGo(l)){s.push(l);continue}a===n&&o!==null&&s.push(o)}return s}function EGo(e){for(let t of e)if(t.op!=="workflowRun.updated"&&t.op!=="workflowRun.removed")return null;return Mz(e)+VGa}var VGa,AGo=Y(()=>{"use strict";g0();r(IGo,"isWorkflowRunDelta");r(CGo,"encodeConversationDeltasForLegacy");VGa=64;r(EGo,"workflowRunDeltaGrowthUpperBound")});function PGo(e,t){if(!t)return[];if(e.type===lt.ToolCallStarted){let o=e.payload;return[{op:"row.upserted",row:{...t,status:"running",startedAt:e.timestamp.getTime(),...o.display?.kind==="mcp_tool"?{display:o.display}:{}}}]}if(t.toolName!=="Bash"||t.status!=="running"||t.backgrounded)return[];let n=Aee.safeParse(e.payload.outputPreview);return n.success?[{op:"row.upserted",row:{...t,outputPreview:n.data}}]:[]}function RGo(e){return e.map(t=>{if(t.op!=="row.upserted"&&t.op!=="row.appended"||t.row.kind!=="toolCall"||!t.row.outputPreview||t.row.status==="running"&&!t.row.backgrounded)return t;let{outputPreview:n,...o}=t.row;return{...t,row:o}})}var DGo=Y(()=>{"use strict";g0();nr();r(PGo,"projectToolActivity");r(RGo,"clearSettledOutputPreviews")});function OGo(e,t){return e?t.reviewFlowId!==e.reviewFlowId?"cross_flow":t.generation>e.generation?"same_flow_advance":t.generation<e.generation?"same_flow_stale":t.interactionId===e.interactionId?"same_flow_replay":"same_flow_conflict":"no_current"}var MGo=Y(()=>{r(OGo,"verdictWorkspaceHookReviewRequest")});function yPn(e){let t=HGa.find(n=>e.startsWith(n));return t?e.slice(t.length):null}function _9(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function NGo(e){return _9(typeof e=="string"?pxt(e):e)}function GGa(e){let t=_9(e),n=[t?.app_ref,t?.app,_9(t?.target)?.app_ref];for(let o of n){let s=NGo(o)?.pid;if(typeof s=="number"&&Number.isInteger(s)&&s>0)return s}return null}function JGa(e){let t=_9(e),n=[t?.app_ref,t?.app,_9(t?.target)?.app_ref];for(let o of n){let s=NGo(o)?.bundle_id;if(typeof s=="string"&&s.trim())return s.trim()}return null}function LGo(e,t){let n=GGa(e);if(n!==null)return t.get(n);let o=JGa(e);if(!o)return;let s=[...t.values()].filter(a=>a.bundleId===o);return s.length===1?s[0]:void 0}function pxt(e){if(!e)return;let t=e.split(`
|
|
15252
15252
|
|
|
@@ -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
|
`)}
|