@easbot/utils 0.3.4 → 0.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,82 +1,65 @@
1
- import {c}from'./chunks/chunk-2ISW3RDH.mjs';export{c as Filesystem,a as Glob,b as MIME_TYPES}from'./chunks/chunk-2ISW3RDH.mjs';import {m,b}from'./chunks/chunk-DJ7NLT2Q.mjs';export{m as Log,o as PackageRegistry,n as Semver,l as addMinutesInTimezone,a as formatLocalISO,b as formatLocalISOCompact,f as formatLogTime,g as formatLogTimeMs,h as getTimezoneOffset,i as getTimezoneParts,j as isValidTimezone,k as normalizeTimezone,c as now,d as nowLocalISO,e as parseLocalISO}from'./chunks/chunk-DJ7NLT2Q.mjs';import {b as b$1,a}from'./chunks/chunk-DAYGB2XR.mjs';export{a as Lock}from'./chunks/chunk-UZ52E7FE.mjs';import {k,c as c$1,i}from'./chunks/chunk-V6YNYGNC.mjs';import se from'fs/promises';import De,{z}from'zod';import {randomBytes,createHash}from'crypto';import be,{dirname,join}from'path';import ze,{existsSync,readdirSync,statSync}from'fs';import {execSync,spawn}from'child_process';import {createRequire}from'module';import {Hono}from'hono';export{Hono}from'hono';import {serve}from'@hono/node-server';import {createNodeWebSocket}from'@hono/node-ws';export{createNodeWebSocket}from'@hono/node-ws';import {streamSSE}from'hono/streaming';import {cors}from'hono/cors';export{cors}from'hono/cors';import {logger}from'hono/logger';export{logger}from'hono/logger';import {compress}from'hono/compress';export{compress}from'hono/compress';import {secureHeaders}from'hono/secure-headers';export{secureHeaders}from'hono/secure-headers';import {timeout}from'hono/timeout';export{timeout}from'hono/timeout';import {HTTPException}from'hono/http-exception';export{HTTPException}from'hono/http-exception';export{validator}from'hono/validator';import {zValidator}from'@hono/zod-validator';export{zValidator}from'@hono/zod-validator';import {minimatch}from'minimatch';import {setTimeout as setTimeout$1}from'timers/promises';import {config}from'dotenv';import {fileURLToPath}from'url';import ro from'markdown-it';import _n from'yaml';import {ProxyAgent,getGlobalDispatcher,setGlobalDispatcher}from'undici';import {AsyncLocalStorage}from'async_hooks';k();k();function sr(e,t){for(let r=e.length-1;r>=0;r-=1){let n=e[r];if(n!==void 0&&t(n,r,e))return n}}k();var ot;(r=>{function e(n,o,s){let a=0,i=n.length-1;for(;a<=i;){let l=Math.floor((a+i)/2),p=n[l];if(p===void 0)break;let c=s(p);if(c===o)return {found:true,index:l};c<o?a=l+1:i=l-1;}return {found:false,index:a}}r.search=e;function t(n,o,s){let a=s(o),i=0,l=n.length;for(;i<l;){let p=Math.floor((i+l)/2),c=n[p];if(c===void 0)break;s(c)<a?i=p+1:l=p;}return n.splice(i,0,o),n}r.insert=t;})(ot||(ot={}));k();var st;(s=>{function e(a){let i=new TextEncoder().encode(a),l=Array.from(i,p=>String.fromCharCode(p)).join("");return btoa(l).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}s.base64Encode=e;function t(a){let i=atob(a.replace(/-/g,"+").replace(/_/g,"/")),l=Uint8Array.from(i,p=>p.charCodeAt(0));return new TextDecoder().decode(l)}s.base64Decode=t;async function r(a,i="SHA-256"){let p=new TextEncoder().encode(a),c=await crypto.subtle.digest(i,p);return Array.from(new Uint8Array(c)).map(k=>k.toString(16).padStart(2,"0")).join("")}s.hash=r;function n(a){if(!a)return;let i=2166136261;for(let l=0;l<a.length;l++)i^=a.charCodeAt(l),i=Math.imul(i,16777619);return (i>>>0).toString(36)}s.checksum=n;function o(a,i=5e5){if(!a)return;if(a.length<=i)return n(a);let l=4096,c=[0,Math.floor(a.length*.25),Math.floor(a.length*.5),Math.floor(a.length*.75),a.length-l].map(d=>{let g=Math.max(0,Math.min(a.length-l,d-Math.floor(l/2)));return n(a.slice(g,g+l))??""}).join(":");return `${a.length}:${c}`}s.sampledChecksum=o;})(st||(st={}));k();k();var ae;(d=>{let e={event:"evt",session:"ses",message:"msg",permission:"per",question:"que",user:"usr",part:"prt",pty:"pty",tool:"tool",workspace:"wrk",command:"cmd",task:"task",heartbeat:"hb",agent:"ag",subagent:"sub",hook:"hok",compaction:"cmp",context:"ctx",experience:"exp",pattern:"pat",knowledge:"knw",evolution:"evo",result:"res"};function t(g){return De.string().startsWith(e[g])}d.schema=t;let r=26,n=0,o=0;function s(g,k){return i(g,false,k)}d.ascending=s;function a(g,k){return i(g,true,k)}d.descending=a;function i(g,k,C){if(!C)return p(g,k);if(!C.startsWith(e[g]))throw new Error(`ID ${C} does not start with ${e[g]}`);return C}function l(g){let k="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",C="",W=randomBytes(g);for(let q=0;q<g;q++){let Y=W[q];Y!==void 0&&(C+=k[Y%62]);}return C}function p(g,k,C){let W=C??Date.now();W!==n&&(n=W,o=0),o++;let q=BigInt(W)*BigInt(4096)+BigInt(o);q=k?~q:q;let Y=Buffer.alloc(6);for(let V=0;V<6;V++)Y[V]=Number(q>>BigInt(40-8*V)&BigInt(255));return e[g]+"_"+Y.toString("hex")+l(r-12)}d.create=p;function c(g){let k=g.split("_")[0];if(!k)return 0;let C=g.slice(k.length+1,k.length+13),W=BigInt("0x"+C);return Number(W/BigInt(4096))}d.timestamp=c;})(ae||(ae={}));var it;(p=>{p.DEFAULT_MAX_CHARS=4e3,p.DIRECTION="head",p.DIR=c.join(process.env.EASBOT_DATA_PATH??`${process.cwd()}/data`,"context-output"),p.GLOB=c.join(p.DIR,"*");let o=10080*60*1e3;function s(c,d,g){return g?`[Content truncated. Source: ${g}
2
- Full ${d} saved to: ${c}
3
- Use Read tool with offset/limit parameters to view specific sections.]`:`[Content truncated. Full ${d} saved to: ${c}
4
- Use Read tool with offset/limit parameters to view specific sections.]`}async function a(c$1,d={}){let g=d.maxChars??4e3,k=d.direction??p.DIRECTION,C=d.label??"content",W=d.sourcePath,q=c.join(process.env.EASBOT_DATA_PATH??`${process.cwd()}/data`,"context-output"),Y=d.dir??q;if(c$1.length<=g)return {content:c$1,truncated:false};let V=ae.ascending("context"),J=c.join(Y,V);await se.mkdir(Y,{recursive:true}).catch(()=>{}),await se.writeFile(J,c$1,"utf-8");let fe=c$1.length-g,ie;k==="head"?ie=c$1.slice(0,g):ie=c$1.slice(-g);let pe=s(J,C,W),Te=`${fe} characters truncated`;return {content:k==="head"?`${ie}
1
+ export{a as Lock}from'./chunks/chunk-UZ52E7FE.mjs';import {G as G$1,D,c as c$1}from'./chunks/chunk-LBWRSUJC.mjs';export{H as $,j as HTTPException,d as Hono,c as Lazy,D as PKG,A as PkgShell,G as Shell,g as compress,e as cors,s as createNodeWebSocket,B as createPkgShell,p as createRESTServer,n as createRPCServer,m as createServer,r as createStreamingServer,q as createWebSocketServer,y as detectPlatform,w as escapeCommandArg,x as escapeCommandArgSafe,z as joinCommandArgs,a as lazy,b as lazyAsync,f as logger,u as needsShellExecution,t as parseCommand,v as parseCommandWithOptions,E as readableStreamToText,h as secureHeaders,C as shell,o as startServer,i as timeout,k as validator,F as whichSync,l as zValidator}from'./chunks/chunk-LBWRSUJC.mjs';import {d,a}from'./chunks/chunk-6HZ7Q7NO.mjs';export{d as Filesystem,b as Glob,c as MIME_TYPES,a as Wildcard}from'./chunks/chunk-6HZ7Q7NO.mjs';import {m,b}from'./chunks/chunk-T3MZ3YS3.mjs';export{m as Log,o as PackageRegistry,n as Semver,l as addMinutesInTimezone,a as formatLocalISO,b as formatLocalISOCompact,f as formatLogTime,g as formatLogTimeMs,h as getTimezoneOffset,i as getTimezoneParts,j as isValidTimezone,k as normalizeTimezone,c as now,d as nowLocalISO,e as parseLocalISO}from'./chunks/chunk-T3MZ3YS3.mjs';import'./chunks/chunk-DAYGB2XR.mjs';import {k,c,i}from'./chunks/chunk-V6YNYGNC.mjs';import pe from'fs/promises';import fe,{z}from'zod';import {randomBytes}from'crypto';import {config}from'dotenv';import ze,{dirname,join}from'path';import {existsSync,readdirSync,statSync}from'fs';import {xdgConfig}from'xdg-basedir';import {fileURLToPath}from'url';import Mn from'markdown-it';import Tt from'yaml';import {ProxyAgent,getGlobalDispatcher,setGlobalDispatcher}from'undici';import {AsyncLocalStorage}from'async_hooks';k();k();function tn(t,e){for(let n=t.length-1;n>=0;n-=1){let r=t[n];if(r!==void 0&&e(r,n,t))return r}}k();var Ce;(n=>{function t(r,o,i){let a=0,s=r.length-1;for(;a<=s;){let l=Math.floor((a+s)/2),p=r[l];if(p===void 0)break;let c=i(p);if(c===o)return {found:true,index:l};c<o?a=l+1:s=l-1;}return {found:false,index:a}}n.search=t;function e(r,o,i){let a=i(o),s=0,l=r.length;for(;s<l;){let p=Math.floor((s+l)/2),c=r[p];if(c===void 0)break;i(c)<a?s=p+1:l=p;}return r.splice(s,0,o),r}n.insert=e;})(Ce||(Ce={}));k();var _e;(i=>{function t(a){let s=new TextEncoder().encode(a),l=Array.from(s,p=>String.fromCharCode(p)).join("");return btoa(l).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}i.base64Encode=t;function e(a){let s=atob(a.replace(/-/g,"+").replace(/_/g,"/")),l=Uint8Array.from(s,p=>p.charCodeAt(0));return new TextDecoder().decode(l)}i.base64Decode=e;async function n(a,s="SHA-256"){let p=new TextEncoder().encode(a),c=await crypto.subtle.digest(s,p);return Array.from(new Uint8Array(c)).map(m=>m.toString(16).padStart(2,"0")).join("")}i.hash=n;function r(a){if(!a)return;let s=2166136261;for(let l=0;l<a.length;l++)s^=a.charCodeAt(l),s=Math.imul(s,16777619);return (s>>>0).toString(36)}i.checksum=r;function o(a,s=5e5){if(!a)return;if(a.length<=s)return r(a);let l=4096,c=[0,Math.floor(a.length*.25),Math.floor(a.length*.5),Math.floor(a.length*.75),a.length-l].map(u=>{let f=Math.max(0,Math.min(a.length-l,u-Math.floor(l/2)));return r(a.slice(f,f+l))??""}).join(":");return `${a.length}:${c}`}i.sampledChecksum=o;})(_e||(_e={}));k();k();var j;(u=>{let t={event:"evt",session:"ses",message:"msg",permission:"per",question:"que",user:"usr",part:"prt",pty:"pty",tool:"tool",workspace:"wrk",command:"cmd",task:"task",heartbeat:"hb",agent:"ag",subagent:"sub",hook:"hok",compaction:"cmp",context:"ctx",experience:"exp",pattern:"pat",knowledge:"knw",evolution:"evo",result:"res"};function e(f){return fe.string().startsWith(t[f])}u.schema=e;let n=26,r=0,o=0;function i(f,m){return s(f,false,m)}u.ascending=i;function a(f,m){return s(f,true,m)}u.descending=a;function s(f,m,g){if(!g)return p(f,m);if(!g.startsWith(t[f]))throw new Error(`ID ${g} does not start with ${t[f]}`);return g}function l(f){let m="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",g="",S=randomBytes(f);for(let w=0;w<f;w++){let v=S[w];v!==void 0&&(g+=m[v%62]);}return g}function p(f,m,g){let S=g??Date.now();S!==r&&(r=S,o=0),o++;let w=BigInt(S)*BigInt(4096)+BigInt(o);w=m?~w:w;let v=Buffer.alloc(6);for(let F=0;F<6;F++)v[F]=Number(w>>BigInt(40-8*F)&BigInt(255));return t[f]+"_"+v.toString("hex")+l(n-12)}u.create=p;function c(f){let m=f.split("_")[0];if(!m)return 0;let g=f.slice(m.length+1,m.length+13),S=BigInt("0x"+g);return Number(S/BigInt(4096))}u.timestamp=c;})(j||(j={}));var Oe;(p=>{p.DEFAULT_MAX_CHARS=4e3,p.DIRECTION="head",p.DIR=d.join(process.env.EASBOT_DATA_PATH??`${process.cwd()}/data`,"context-output"),p.GLOB=d.join(p.DIR,"*");let o=10080*60*1e3;function i(c,u,f){return f?`[Content truncated. Source: ${f}
2
+ Full ${u} saved to: ${c}
3
+ Use Read tool with offset/limit parameters to view specific sections.]`:`[Content truncated. Full ${u} saved to: ${c}
4
+ Use Read tool with offset/limit parameters to view specific sections.]`}async function a(c,u={}){let f=u.maxChars??4e3,m=u.direction??p.DIRECTION,g=u.label??"content",S=u.sourcePath,w=d.join(process.env.EASBOT_DATA_PATH??`${process.cwd()}/data`,"context-output"),v=u.dir??w;if(c.length<=f)return {content:c,truncated:false};let F=j.ascending("context"),L=d.join(v,F);await pe.mkdir(v,{recursive:true}).catch(()=>{}),await pe.writeFile(L,c,"utf-8");let ae=c.length-f,W;m==="head"?W=c.slice(0,f):W=c.slice(-f);let le=i(L,g,S),Re=`${ae} characters truncated`;return {content:m==="head"?`${W}
5
5
 
6
- ...${Te}...
6
+ ...${Re}...
7
7
 
8
- ${pe}`:`...${Te}...
8
+ ${le}`:`...${Re}...
9
9
 
10
- ${pe}
10
+ ${le}
11
11
 
12
- ${ie}`,truncated:true,outputPath:J,originalLength:c$1.length,removedLength:fe,label:C}}p.truncate=a;function i(c){return c.truncated?s(c.outputPath,c.label):""}p.formatHint=i;async function l(){let c$1=ae.timestamp(ae.create("context",false,Date.now()-o)),g=(await se.readdir(p.DIR).catch(()=>[])).filter(k=>k.startsWith("context_"));for(let k of g)ae.timestamp(k)>=c$1||await se.unlink(c.join(p.DIR,k)).catch(()=>{});}p.cleanup=l;})(it||(it={}));k();var at;(i=>{let e="New session - ",t="Child session - ";i.parentTitlePrefix=e,i.childTitlePrefix=t;function o(l=false){return (l?t:e)+b(new Date)}i.createDefault=o;function s(l){return new RegExp(`^(${e}|${t})\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}[+-]\\d{2}:\\d{2}$`).test(l)}i.isDefault=s;function a(l){let p=l.match(/^(.+) \(fork #(\d+)\)$/);if(p){let c=p[1]??"",d=parseInt(p[2]??"0",10);return `${c} (fork #${d+1})`}return `${l} (fork #1)`}i.getForked=a;})(at||(at={}));k();k();function Yt(e){let t,r=false,n=()=>(r||(t=e(),r=true),t);return n.reset=()=>{r=false,t=void 0;},n}var _e=Yt;function Vt(e){let t,r=()=>(t||(t=e()),t);return r.reset=()=>{t=void 0;},r}var lr=Vt,me;(r=>(r.lazy=Yt,r.lazyAsync=Vt))(me||(me={}));k();k();k();var re=m.create({service:"server"});function le(e={}){let t=e.port??3e3,r=e.hostname??"0.0.0.0",n=new Hono({strict:true,getPath:a=>{try{return new URL(a.url).pathname}catch{return a.url}}});if(e.onError?n.onError(e.onError):n.onError((a,i)=>(re.error("Server error",{error:a.message,stack:a.stack}),a instanceof HTTPException?a.getResponse():i.json({error:"Internal Server Error",message:a.message},500))),e.onNotFound?n.notFound(e.onNotFound):n.notFound(a=>a.json({error:"Not Found",path:a.req.path},404)),!e.websockets&&e.cors&&n.use(cors(typeof e.cors=="boolean"?{origin:"*"}:e.cors)),n.use(logger((a,...i)=>re.info(a,i))),!e.websockets&&e.secureHeaders&&n.use(secureHeaders()),!e.websockets&&e.compression&&n.use(compress({encoding:"gzip"})),!e.websockets&&e.timeout&&n.use(timeout(e.timeout)),e.middlewares)for(let a of e.middlewares)a.path?n.use(a.path,a.handler):n.use(a.handler);if(e.routes)for(let a of e.routes){let i=a.middlewares||[],l=a.method.toUpperCase();a.validation?n.on(l,a.path,zValidator("json",a.validation),...i,a.handler):n.on(l,a.path,...i,a.handler);}e.rpc&&n.post("/rpc/:method",async a=>{let i=a.req.param("method"),l=e.rpc?.[i];if(!l)return a.json({error:"RPC method not found"},404);try{let p=await a.req.json(),c=await l(p,a);return a.json({result:c})}catch(p){return re.error("RPC error",{method:i,error:p.message}),a.json({error:"RPC execution failed",message:p.message},500)}}),e.fetch&&n.all("*",async a=>await e.fetch(a.req.raw));let o=null,s={url:new URL(`http://${r}:${t}`),port:t,hostname:r,hono:n,async stop(a=false){return o?new Promise((i,l)=>{a&&o.closeAllConnections?.(),o.close(p=>{p?(re.error("Error closing server",{error:p.message}),l(p)):(o=null,re.info(`Server on port ${t} stopped`),i());}),setTimeout(()=>{re.warn(`Server shutdown timeout on port ${t}`),o=null,i();},5e3);}):Promise.resolve()},get raw(){return o||void 0}};return re.debug("createServer: calling serve()",{port:t,hostname:r}),o=serve({fetch:n.fetch,port:t,hostname:r}),re.debug("createServer: serve() returned, server created"),re.info(`Server running on http://${r}:${t}`),s}function lt(e){return le({rpc:e,port:3e3})}function fr(e,t=3e3,r="0.0.0.0"){return le({fetch:e,port:t,hostname:r})}function ct(e,t={}){return le({...t,routes:e})}function ut(e,t={}){return le({...t,websockets:e})}function dt(e,t={}){let r=Object.entries(e).map(([n,o])=>({method:"get",path:`/stream/${n}`,handler:s=>streamSSE(s,async a=>{for await(let i of o(s))await a.writeSSE(i);})}));return le({...t,routes:r,streaming:true})}k();var ce=m.create({service:"build-api"});async function an(){try{return {available:!0,version:(await import('./chunks/main-ZMRSNK7G.mjs')).version||"unknown"}}catch(e){return ce.warn("esbuild not available",{error:e.message}),{available:false}}}async function Ne(){let e=await an();if(!e.available)throw new Error("esbuild is required but not installed. Please install it using: pnpm add -D esbuild");e.version&&e.version<"0.17.0"&&ce.warn(`esbuild version ${e.version} may have limited features. Consider upgrading to 0.17+`);}function hr(e){if(e!==void 0)return typeof e=="boolean"?{target:void 0}:typeof e=="string"?{target:e}:e}function ln(e){let t=hr(e.compile);t&&ce.warn("compile option is no longer supported (Bun runtime removed). The option will be ignored.");let r={entryPoints:e.entrypoints,outdir:e.outdir,bundle:e.bundle??true,conditions:e.conditions,external:e.external,format:e.format??"esm",platform:e.platform??(e.target==="browser"?"browser":"node"),minify:e.minify??false,treeShaking:true,splitting:e.splitting,sourcemap:br(e.sourcemap),sourcesContent:true,define:e.define,inject:e.inject,legalComments:"eof",loader:e.loader,entryNames:e.entryNames,chunkNames:e.chunkNames,assetNames:e.assetNames,publicPath:e.publicPath,tsconfig:e.tsconfig,charset:"utf8",color:true,logLevel:"info",logLimit:50,plugins:e.plugins??[],metafile:true,write:e.write??true};return t?.outfile&&!e.outdir&&(r.outfile=t.outfile,delete r.outdir),e.target&&(r.target=yr(e.target)),e.minify===true&&(r.minifyWhitespace=true,r.minifyIdentifiers=true,r.minifySyntax=true),xr(r)}function br(e){return !e||e==="none"?false:e}function yr(e){let t={browser:"es2020",node:"node16",bun:"esnext"};return e?t[e]||e:"esnext"}function xr(e){let t={};for(let r of Object.keys(e))e[r]!==void 0&&(t[r]=e[r]);return t}function je(e){if(e!==void 0)return e.replace(/\\/g,"/")}function nn(e,t,r){let n=[];if(e.outputFiles)for(let s of e.outputFiles)n.push({path:je(s.path)||s.path,size:s.contents?.length||0});if(e.metafile?.outputs)for(let[s,a]of Object.entries(e.metafile.outputs)){let i=a;n.some(l=>l.path===s||l.path===je(s))||n.push({path:je(s)||s,size:i.bytes||0});}let o=[];if(e.errors?.length>0)for(let s of e.errors)o.push({level:"error",message:s.text||String(s),path:s.location?.file,position:s.location?{line:s.location.line,column:s.location.column}:void 0});if(e.warnings?.length>0)for(let s of e.warnings)o.push({level:"warning",message:s.text||String(s),path:s.location?.file,position:s.location?{line:s.location.line,column:s.location.column}:void 0});return {outputs:n,success:e.errors?.length===0,logs:o,metafile:e.metafile}}async function pt(e){ce.info("Build started",{entrypoints:e.entrypoints,target:e.target,format:e.format,compile:typeof e.compile}),await Ne();let t=await import('./chunks/main-ZMRSNK7G.mjs'),r=Date.now();try{let n=ln(e);ce.debug("esbuild options",n);let o=await t.build(n),s=Date.now();return ce.info("Build completed",{duration:s-r,outputs:(o?.outputFiles?.length??0)>0||Object.keys(o.metafile?.outputs||{}).length>0}),nn(o,r,s)}catch(n){let o=Date.now(),s=n.message;return ce.error("Build failed",{error:s,duration:o-r}),n&&typeof n=="object"&&"errors"in n?nn(n):{outputs:[],success:false,logs:[{level:"error",message:s}],metafile:void 0}}}var Rr={build:pt},cn=Rr;k();k();function oe(e){let t=[],r="",n=0;for(;n<e.length&&(e[n]===" "||e[n]===" ");)n++;for(;n<e.length;){let o=e[n];if(o===" "||o===" "){for(r.length>0&&(t.push(r),r="");n<e.length&&(e[n]===" "||e[n]===" ");)n++;continue}if(o==='"'){for(n++;n<e.length;){let s=e[n];if(s==="\\"&&n+1<e.length){let a=e[n+1];if(a==='"'||a==="\\"||a==="$"||a==="`"){r+=a,n+=2;continue}}if(s==='"'){n++;break}r+=s,n++;}continue}if(o==="'"){for(n++;n<e.length;){let s=e[n];if(s==="'"){n++;break}r+=s,n++;}continue}r+=o,n++;}return r.length>0&&t.push(r),t}function un(e){return /[|&;<>()$`!#]/.test(e)}function dn(e){let t=oe(e);if(t.length===0)return {command:"",args:[]};let r={command:t[0],args:t.slice(1)};if(r.args.length>0){let n=r.args[r.args.length-1];try{let o=JSON.parse(n);typeof o=="object"&&o!==null&&!Array.isArray(o)&&(r.options=o,r.args=r.args.slice(0,-1));}catch{}}return r}function mt(e,t=process.platform==="win32"?"windows":"unix"){return t==="windows"?e.includes(" ")||e.includes("&")||e.includes("|")||e.includes("<>")||e.includes("^")||e.includes('"')||e.includes("%")?`"${e.replace(/%/g,"%%").replace(/"/g,'^"')}"`:e:e.includes(" ")||e.includes("'")||e.includes('"')||e.includes("$")||e.includes("`")||e.includes("\\")||e.includes("!")||e.includes("#")||e.includes("&")||e.includes("*")||e.includes("?")||e.includes("|")||e.includes("<")||e.includes(">")||e.includes("(")||e.includes(")")||e.includes(";")?`'${e.replace(/'/g,"'\\''")}'`:e}var Pr=new Set(["&&","||","|",";","&",">","<",">>","<<","2>","2>>","1>","1>>","2>&1","2>&2","1>&1","1>&2",">&","<&",">&1","<&1",">&2","<&2"]);function fn(e,t=process.platform==="win32"?"windows":"unix"){return Pr.has(e)?e:mt(e,t)}function pn(){return process.platform==="win32"?"windows":"unix"}function ge(e,t,r=process.platform==="win32"?"windows":"unix"){let n=t.map(o=>fn(o,r));return [e,...n].join(" ")}function mn(e){if(e==null)return "";if(typeof e=="string")return e;if(Array.isArray(e))return e.map(t=>mn(t)).join(" ");if(e&&typeof e=="object"){if("raw"in e)return String(e.raw);if("toString"in e&&typeof e.toString=="function")return e.toString();if(e instanceof ReadableStream)throw new Error("ReadableStream expressions are not yet supported")}return String(e)}function Mr(e,t,r){return {stdout:e,stderr:t,exitCode:r,text(n="utf-8"){return e.toString(n)},json(){let n=e.toString("utf-8");return JSON.parse(n)},arrayBuffer(){let n=e.buffer;if(n instanceof ArrayBuffer)return n.slice(e.byteOffset,e.byteOffset+e.byteLength);let o=new ArrayBuffer(e.byteLength),s=new Uint8Array(o),a=new Uint8Array(n,e.byteOffset,e.byteLength);return s.set(a),o},bytes(){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)},blob(){let n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return new Blob([n])}}}function he(e,t={}){let r=oe(e);if(r.length===0)throw new Error("Empty shell command");let n=async()=>{let s=await _.run(r,{cwd:t.cwd,env:t.env}),a=Mr(Buffer.from(s.stdout,"utf-8"),Buffer.from(s.stderr,"utf-8"),s.code);if(s.code!==0&&!t.nothrow)throw Object.assign(new Error(`Command failed with exit code ${s.code}: ${e}
13
- ${s.stderr}`),{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode});return a},o=n();return Object.defineProperty(o,"stdin",{get(){throw new Error("stdin is not yet supported in EasbotShell. Use PKG.spawn for interactive commands.")},enumerable:true}),o.cwd=function(s){return he(e,{...t,cwd:s})},o.env=function(s){return he(e,{...t,env:s})},o.quiet=function(){return he(e,{...t,quiet:true})},o.lines=async function*(){let i=(await n()).text().split(/\r?\n/);for(let l of i)l.trim()&&(yield l);},o.text=async function(s="utf-8"){return (await n()).text(s)},o.json=async function(){return (await n()).json()},o.arrayBuffer=async function(){return (await n()).arrayBuffer()},o.blob=async function(){return (await n()).blob()},o.nothrow=function(){return he(e,{...t,nothrow:true})},o.throws=function(s){return he(e,{...t,nothrow:!s})},o}var Pe=class{constructor(t={}){c$1(this,"options");this.options=t;}call(t,...r){let n="";for(let o=0;o<t.length;o++)n+=t[o],o<r.length&&r[o]!==void 0&&(n+=mn(r[o]));return he(n,this.options)}braces(t){let r=t.match(/^(.*?)\{([^}]+)\}(.*)$/);if(!r)return [t];let[,n="",o="",s=""]=r,a=o.split(",").map(l=>l.trim()),i=[];for(let l of a){let p=`${n}${l}${s}`;p.includes("{")?i.push(...this.braces(p)):i.push(p);}return i}escape(t){return process.platform==="win32"?t.replace(/([&|<>^"%])/g,"^$1"):t.replace(/(["\s'$`\\!*?#&;()<>|])/g,"\\$1")}env(t){return ue({...this.options,env:t})}cwd(t){return ue({...this.options,cwd:t})}nothrow(){return ue({...this.options,nothrow:true})}throws(t){return ue({...this.options,nothrow:!t})}};function ue(e={}){let t=new Pe(e);return new Proxy(t,{apply(r,n,o){return t.call(o[0],...o.slice(1))}})}var gn=ue();function hn(e){return e.replace(/\\/g,"/")}function bn(e){return createHash("md5").update(e).digest("hex").slice(0,8)}var ee=new Map,_;(j=>{let e=m.create({service:"pkg"});async function t(S){let m=S?[S]:["npm","pnpm","bun"];for(let f of m){let u=await j.which(f);if(u)return {name:f,path:u}}}j.packageManager=t;async function r(S,m){if(!S)return process.execPath;let f=m?.PATH||process.env.PATH||process.env.Path||"",u=process.env.EASBOT_BIN_PATH,y=u?f+be.delimiter+u:f,x=bn(y),h=`${S}:${x}`;if(ee.has(h))return ee.get(h);let R=process.platform==="win32"?"where":"which";try{let{spawn:v}=await import('child_process');return new Promise(T=>{let O=v(R,[S],{env:{...process.env,PATH:y},stdio:["pipe","pipe","ignore"],windowsHide:!0}),D="",$="";O.stdout?.on("data",z=>{D+=z.toString();}),O.stderr?.on("data",z=>{$+=z.toString();}),O.on("close",z=>{if(z===0&&D.trim()){let A=D.trim().split(`
14
- `),L=A.length>0?A[0]?.trim():null;if(L){ee.set(h,L),T(L);return}}ee.set(h,null),T(null);}),setTimeout(()=>{O.kill(),ee.set(h,null),T(null);},5e3);})}catch{return ee.set(h,null),null}}j.which=r;function n(S,m){if(!S)return process.execPath;let f=m?.PATH||process.env.PATH||process.env.Path||"",u=process.env.EASBOT_BIN_PATH,y=u?f+be.delimiter+u:f,x=bn(y),h=`${S}:${x}`;if(ee.has(h))return ee.get(h);let R=process.platform==="win32"?"where":"which";try{let v=execSync(`${R} ${S}`,{encoding:"utf-8",stdio:["pipe","pipe","ignore"],env:{...process.env,PATH:y},timeout:5e3,windowsHide:!0});if(v.trim()){let T=v.trim().split(`
15
- `),O=T.length>0?T[0]?.trim():null;if(O)return ee.set(h,O),O}}catch{}return ee.set(h,null),null}j.whichSync=n;function o(){ee.clear();}j.clearWhichCache=o;let s=createRequire(import.meta.url);async function a$1(S,m,f){try{let u=[];if(f?.extraPaths)for(let y of f.extraPaths){let x=be.join(y,"node_modules");u.push(x);}return m&&u.push(m),u.length>0?s.resolve(S,{paths:u}):s.resolve(S)}catch(u){throw new Error(`Cannot resolve module "${S}"${m?` from "${m}"`:""}: ${u instanceof Error?u.message:String(u)}`)}}j.resolve=a$1;function i(S){return {get name(){return be.basename(S)},async exists(){try{return await se.access(S),!0}catch{return false}},async getSize(){try{return (await se.stat(S)).size}catch{return}},async text(){return await se.readFile(S,"utf-8")},textSync(){return ze.readFileSync(S,"utf-8")},jsonSync(){let m=ze.readFileSync(S,"utf-8");return JSON.parse(m)},async bytes(){e.debug("[PKG.file.bytes] reading file:",{filePath:S});let m=await se.readFile(S);return e.debug("[PKG.file.bytes] read succeeded, size:",{size:m.length}),new Uint8Array(m.buffer,m.byteOffset,m.byteLength)},async arrayBuffer(){let m=await se.readFile(S);return m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength)},get type(){let m=be.extname(S).toLowerCase();return {".txt":"text/plain",".html":"text/html",".htm":"text/html",".css":"text/css",".js":"application/javascript",".json":"application/json",".xml":"application/xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".pdf":"application/pdf",".zip":"application/zip",".wav":"audio/wav",".mp3":"audio/mpeg",".mp4":"video/mp4",".webm":"video/webm"}[m]||"application/octet-stream"},async write(m){let f;if(m instanceof Response){let u=await m.arrayBuffer();f=new Uint8Array(u);}else f=m;await se.writeFile(S,f);},async json(){let m=await se.readFile(S,"utf-8");return JSON.parse(m)},async stat(){return await se.stat(S)}}}j.file=i;async function l(S,m,f){let u;if(m instanceof Response){let y=await m.arrayBuffer();u=new Uint8Array(y);}else u=m;await se.writeFile(S,u,f?{mode:f.mode}:void 0);}j.write=l;function p(S,m,f){ze.writeFileSync(S,m,f?{mode:f.mode}:void 0);}j.writeSync=p;function c(S,m="utf-8"){return ze.readFileSync(S,m)}j.readSync=c;function d(S,m){let f,u;if(typeof S=="object"&&"cmd"in S){let v=S;f=v.cmd,u={cwd:v.cwd,env:v.env,stdout:v.stdout,stderr:v.stderr,stdin:v.stdin,signal:v.signal,windowsHide:v.windowsHide,shell:v.shell};}else f=Array.isArray(S)?S:[S],u=m||{};if(!f||f.length===0||!f[0])throw new Error("Spawn command cannot be empty");let y=[u.stdin==="inherit"?"inherit":u.stdin==="null"?"ignore":"pipe",u.stdout==="inherit"?"inherit":u.stdout==="null"?"ignore":"pipe",u.stderr==="inherit"?"inherit":u.stderr==="null"?"ignore":"pipe"],x={cwd:u.cwd,env:u.env?{...process.env,...u.env}:process.env,stdio:y,timeout:u.timeout};u.shell!==void 0&&(x.shell=u.shell),process.platform==="win32"&&(x.windowsHide=u.windowsHide??true);let h=spawn(f[0],f.slice(1),x),w;if(u.signal){w=()=>{h.kill();},u.signal.addEventListener("abort",w,{once:true});let v=()=>{w&&(u.signal?.removeEventListener("abort",w),w=void 0);};h.on("close",v),h.on("error",v);}let R=new Promise((v,T)=>{let O=false,D=()=>{O||(O=true,h.removeAllListeners());};if(h.on("close",$=>{D(),v($??0);}),h.on("error",$=>{D(),T($);}),u.timeout!==false){let $=u.timeout||3e5;setTimeout(()=>{if(!O){e.debug(`Process timeout after ${$}ms, killing process`,{cmd:f.join(" ")}),D();try{h.kill("SIGKILL");}catch{}T(new Error(`Process timeout after ${$}ms: ${f.join(" ")}`));}},$);}});return {stdout:h.stdout,stderr:h.stderr,stdin:h.stdin,pid:h.pid,exited:R,exitCode:h.exitCode,kill:v=>h.kill(v)}}j.spawn=d;async function g(S,m){let f=m?.stdin??"null",u=m?.stdout??"pipe",y=m?.stderr??"pipe",x=d(S,{cwd:m?.cwd,env:m?.env,stdin:f,stdout:u,stderr:y,windowsHide:m?.windowsHide,shell:m?.shell,timeout:m?.timeout}),h=[],w=[];u==="pipe"&&x.stdout?.on("data",v=>{h.push(v);}),y==="pipe"&&x.stderr?.on("data",v=>{w.push(v);});let R=m?.timeout&&m.timeout>0?setTimeout(()=>{try{x.kill("SIGKILL");}catch{}x.stdout?.destroy(),x.stderr?.destroy(),x.stdin?.end();},m.timeout):void 0;try{let v=await x.exited;return clearTimeout(R),u==="pipe"&&x.stdout?.destroy(),y==="pipe"&&x.stderr?.destroy(),f==="pipe"&&x.stdin?.end(),{code:v,stdout:Buffer.concat(h).toString("utf-8"),stderr:Buffer.concat(w).toString("utf-8")}}catch(v){return clearTimeout(R),u==="pipe"&&x.stdout?.destroy(),y==="pipe"&&x.stderr?.destroy(),f==="pipe"&&x.stdin?.end(),{code:-1,stdout:Buffer.concat(h).toString("utf-8"),stderr:Buffer.concat(w).toString("utf-8")||(v instanceof Error?v.message:String(v))}}}j.run=g;async function k(S,m={},f={}){let u=d(S,{cwd:m.cwd,env:m.env,stdout:"pipe",stderr:"pipe",stdin:"null"}),y="",x="";u.stdout?.on("data",w=>{let R=w.toString("utf-8");y+=R,f.onStdout?.(R);}),u.stderr?.on("data",w=>{let R=w.toString("utf-8");x+=R,f.onStderr?.(R);});let h=m.timeout&&m.timeout>0?setTimeout(()=>{try{u.kill("SIGKILL");}catch{}u.stdout?.destroy(),u.stderr?.destroy();},m.timeout):void 0;try{let w=await u.exited;return clearTimeout(h),f.onExit?.(w),{code:w,stdout:y,stderr:x}}catch(w){clearTimeout(h);let R=w instanceof Error?w.message:String(w);return {code:-1,stdout:y,stderr:x||R}}}j.runWithStream=k;async function C(S){if(typeof S.pipeThrough=="function")try{let y=new TextDecoderStream("utf-8"),h=S.pipeThrough(y).getReader(),w="";try{for(;;){let{done:R,value:v}=await h.read();if(R)break;w+=v;}return w}finally{h.releaseLock();}}catch{}let m=S.getReader(),f=new TextDecoder("utf-8"),u=[];try{for(;;){let{done:y,value:x}=await m.read();if(y)break;u.push(f.decode(x,{stream:!0}));}return u.push(f.decode()),u.join("")}finally{m.releaseLock();}}j.readableStreamToText=C;async function W(S){let m=[];return new Promise((f,u)=>{S.on("data",y=>{typeof y=="string"?m.push(Buffer.from(y)):m.push(y);}),S.on("end",()=>{try{let x=Buffer.concat(m).toString("utf-8");f(x);}catch(y){u(y);}}),S.on("error",y=>{u(y);});})}j.nodeReadableStreamToText=W;function q(S,m=0){let R=new TextEncoder().encode(S),v=R.length,T,O=0;if(v>=16){let A=v-16,L=m+2654435761+2246822519|0,te=m+2246822519|0,K=m+0|0,X=m-2654435761|0;for(;O<=A;)L=D(L,z(R,O)),O+=4,te=D(te,z(R,O)),O+=4,K=D(K,z(R,O)),O+=4,X=D(X,z(R,O)),O+=4;T=$(L,1)+$(te,7)+$(K,12)+$(X,18)|0;}else T=m+374761393|0;for(T=T+v|0;O+4<=v;)T=T+z(R,O)*3266489917|0,T=$(T,17)*668265263|0,O+=4;for(;O<v;)T=T+R[O]*374761393|0,T=$(T,11)*2654435761|0,O++;return T^=T>>>15,T=T*2246822519|0,T^=T>>>13,T=T*3266489917|0,T^=T>>>16,T>>>0;function D(A,L){return A=A+L*2246822519|0,A=$(A,13),A=A*2654435761|0,A}function $(A,L){return A<<L|A>>>32-L|0}function z(A,L){return (A[L]|A[L+1]<<8|A[L+2]<<16|A[L+3]<<24)>>>0}}j.xxHash32=q;function Y(S){let m=0;for(let f of S){let u=f.codePointAt(0)||f.charCodeAt(0);u<127?m+=1:u>=4352&&u<=4447||u>=9001&&u<=9002||u>=11904&&u<=42191&&u!==12351||u>=44032&&u<=55203||u>=63744&&u<=64255||u>=65040&&u<=65049||u>=65072&&u<=65135||u>=65280&&u<=65376||u>=65504&&u<=65510?m+=2:m+=1;}return m}j.stringWidth=Y;class V{constructor(m){c$1(this,"pattern");this.pattern=m;}async*scan(m){let f=b$1.stream(this.pattern,{cwd:m?.cwd,absolute:m?.absolute,follow:m?.followSymlinks,dot:m?.dot,nodir:m?.onlyFiles});for await(let u of f)yield hn(u);}*scanSync(m){let f=a(this.pattern,{cwd:m?.cwd,absolute:m?.absolute,follow:m?.followSymlinks,dot:m?.dot,nodir:m?.onlyFiles});for(let u of f)yield hn(u);}match(m){return minimatch(m,this.pattern)}}j.Glob=V,j.stdin=process.stdin,j.stdout=process.stdout,j.stderr=process.stderr,j.sleep=S=>new Promise(m=>setTimeout(m,S)),j.color=(S,m)=>({black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",brightBlack:"\x1B[90m",brightRed:"\x1B[91m",brightGreen:"\x1B[92m",brightYellow:"\x1B[93m",brightBlue:"\x1B[94m",brightMagenta:"\x1B[95m",brightCyan:"\x1B[96m",brightWhite:"\x1B[97m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m",bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",blink:"\x1B[5m",inverse:"\x1B[7m",hidden:"\x1B[8m",strikethrough:"\x1B[9m",reset:"\x1B[0m"})[S.toLowerCase()]||null,j.hash={xxHash32:j.xxHash32},j.build=cn.build,j.server=le,j.nodeWebSocket=createNodeWebSocket,j.restServer=ct,j.rpcServer=lt,j.streamingServer=dt,j.webSocketServer=ut;})(_||(_={}));var Ar=_.readableStreamToText;_.nodeReadableStreamToText;_.which;var Lr=_.whichSync;_.spawn;_.run;var xn=200,wn={bash:{login:true,posix:true},dash:{login:true,posix:true},fish:{deny:true,login:true},ksh:{login:true,posix:true},nu:{deny:true},powershell:{ps:true},pwsh:{ps:true},sh:{login:true,posix:true},zsh:{login:true,posix:true}},ne;(m$1=>{let e=m.create({service:"shell"});async function t(f,u){let y=f.pid;if(!(!y||u?.exited?.())){if(process.platform==="win32"){await new Promise(x=>{let h=spawn("taskkill",["/pid",String(y),"/f","/t"],{stdio:"ignore",windowsHide:true});h.once("exit",()=>x()),h.once("error",()=>x());});return}try{process.kill(-y,"SIGTERM"),await setTimeout$1(xn),u?.exited?.()||process.kill(-y,"SIGKILL");}catch{f.kill("SIGTERM"),await setTimeout$1(xn),u?.exited?.()||f.kill("SIGKILL");}}}m$1.killTree=t;function r(f){if(process.platform!=="win32"||!f.includes("/")&&!f.includes("\\")&&!f.includes(":"))return f;let u=c.normalize(f);return C(u)==="bash"&&g()||u}function n(f){return wn[C(f)]}function o(f){return n(f)?.deny!==true}function s(f){return c.isAbsolute(f)}function a(f){let u=r(f);if(s(u))return c.stat(u)?.isFile()?u:void 0;let y=_.whichSync(u);return y?c.normalize(y):void 0}function i(){return Array.from(new Set([_.whichSync("pwsh"),_.whichSync("powershell"),g(),process.env.COMSPEC||"cmd.exe"].filter(f=>!!f).map(r)))}async function l(){let f=await c.readText("/etc/shells").catch(()=>"");return f?Array.from(new Set(f.split(`
16
- `).filter(u=>u.trim()&&!u.startsWith("#")))):["/bin/bash","/bin/zsh","/bin/sh"]}function p(f,u){if(f&&(!u?.acceptable||o(f))){let y=a(f);if(y)return y}return process.platform==="win32"?i()[0]:k()}m$1.defaultPreferred=_e(()=>p(process.env.SHELL)),m$1.defaultAcceptable=_e(()=>p(process.env.SHELL,{acceptable:true}));function g(){if(process.platform!=="win32")return;if(process.env.EASBOT_GIT_BASH_PATH)return c.normalize(process.env.EASBOT_GIT_BASH_PATH);let f=_.whichSync("git");if(!f)return;let u=c.normalize(be.join(f,"..","..","bin","bash.exe"));if((c.stat(u)?.size??0)>0)return u}m$1.gitbash=g;function k(){if(process.platform==="win32"){let u=g();return u||"/bin/sh"}if(process.platform==="darwin")return "/bin/zsh";let f=_.whichSync("bash");return f?c.normalize(f):"/bin/sh"}function C(f){return be.posix.basename(c.toUnixPath(f)).toLowerCase()}m$1.name=C;function W(f){return n(f)?.login===true}m$1.login=W;function q(f){return n(f)?.posix===true}m$1.posix=q;function Y(f){return n(f)?.ps===true}m$1.ps=Y;function V(f){let u=r(f),y=C(u);return {path:u,name:y,acceptable:o(y)}}function J(f,u,y){let x=C(f),h=oe(u),w=ge(h[0]??u,h.slice(1));return x==="nu"||x==="fish"?["-c",w]:x==="zsh"?["-l","-c",`
17
- [[ -f ~/.zshenv ]] && source ~/.zshenv >/dev/null 2>&1 || true
18
- [[ -f "\${ZDOTDIR:-$HOME}/.zshrc" ]] && source "\${ZDOTDIR:-$HOME}/.zshrc" >/dev/null 2>&1 || true
19
- cd -- "$1"
20
- ${w}
21
- `,"easbot",y]:x==="bash"?["-l","-c",`${process.platform==="win32"?`cmd /c chcp 65001 >nul 2>&1 || true
22
- `:""}shopt -s expand_aliases
23
- [[ -f ~/.bashrc ]] && source ~/.bashrc >/dev/null 2>&1 || true
24
- cd -- "$1"
25
- ${w}
26
- `,"easbot",y]:/^cmd(\.exe)?$/i.test(x)?["/c",`chcp 65001 >nul 2>&1 && ${w}`]:Y(x)?["-NoProfile","-Command",`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ${w}`]:["-c",w]}m$1.args=J;function fe(f){return f?p(f):(0, m$1.defaultPreferred)()}m$1.preferred=fe;function ie(f){return f?p(f,{acceptable:true}):(0, m$1.defaultAcceptable)()}m$1.acceptable=ie;function pe(){m$1.defaultPreferred.reset(),m$1.defaultAcceptable.reset();}m$1.reset=pe;async function Te(){return (process.platform==="win32"?i():await l()).filter(u=>a(u)).map(V)}m$1.list=Te;function ve(f){return wn[C(f)]}m$1.metaInfo=ve;function Ht(f){return /[|&;<>()$`!#]/.test(f)}m$1.needsShell=Ht;function F(){return process.platform==="win32"?i():["/bin/bash","/bin/zsh","/bin/sh"]}m$1.platformShells=F;function I(f){return f?!!a(f):false}m$1.isValid=I;async function B(f){let u=a(f);if(!u)return;let y=C(u);if(!/^cmd(\.exe)?$/i.test(y))try{let x;Y(y)?x=["-NoProfile","-Command","$PSVersionTable.PSVersion.ToString()"]:x=["--version"],e.debug(`\u83B7\u53D6 Shell \u7248\u672C: ${u}`,{shell:u,args:x});let h=await _.run([u,...x]);if(h.code===0){let w=h.stdout.trim().split(`
27
- `)[0];return e.debug(`Shell \u7248\u672C\u83B7\u53D6\u6210\u529F: ${w}`),w}e.debug(`Shell \u7248\u672C\u83B7\u53D6\u5931\u8D25\uFF0C\u9000\u51FA\u7801: ${h.code}`,{stderr:h.stderr});}catch(x){e.debug(`Shell \u7248\u672C\u83B7\u53D6\u5F02\u5E38: ${x}`);}}m$1.version=B;class U extends Error{constructor(y,x,h,w){super(y);c$1(this,"message",y);c$1(this,"pkg",x);c$1(this,"version",h);c$1(this,"originalError",w);this.name="InstallFailedError";}}m$1.InstallFailedError=U;async function G(f,u="latest",y){let{Lock:x}=await import('./chunks/lock-EGXJVIO5.mjs'),{Filesystem:h}=await import('./chunks/filesystem-KGIAOOG5.mjs'),{PackageRegistry:w}=await import('./chunks/registry-36YLLEJU.mjs');y=y??process.env.EASBOT_CACHE_PATH??be.join(".easbot","cache");let R=await x.write("pkg-install");try{let v=be.posix.join(y,"node_modules",f),T=be.posix.join(y,"package.json"),D=(await h.readJson(T).catch(async()=>{let Z={dependencies:{}};return await h.writeJson(T,Z),Z})).dependencies??{},$=await h.exists(v),z=D[f],A=!1;if(!$||!z)A=!0;else {if(u!=="latest"&&z===u)return v;if(u==="latest"){if(!await w.isOutdated(f,z,y))return v;e.info("Cached version is outdated, proceeding with install",{pkg:f,cachedVersion:z}),A=!0;}}if(!A)return v;let L=m$1.acceptable(process.platform==="win32"?"cmd":void 0)??k(),te=`${f}@${u}`;e.info("installing package",{pkg:f,version:u,cache:y,shell:L});let K=await _.packageManager();if(!K)throw new U("No package manager found (npm, pnpm, bun)",f,u,"No package manager available");let X=K.name,et=X==="pnpm"?"add":"install",tt=`${K.name} ${et} --save-exact ${te}`;e.info(`Using ${X} to install package`,{pkg:f,version:u,shell:L,pmPath:K.path});try{let Z=await m$1.run(L,tt,{cwd:y,timeout:6e5,windowsHide:!0});if(Z.code!==0)throw new Error(`Package manager exited with code ${Z.code}: ${Z.stderr}`);e.info(`Successfully installed ${f}@${u} with ${X}`);}catch(Z){let Wt=Z instanceof Error?Z:new Error(String(Z));if(!await h.exists(v))throw new U(`Failed to install ${f}@${u}`,f,u,Wt.message);e.warn("Package install failed but module exists, continuing",{error:Wt.message});}let nt=u;u==="latest"&&(nt=(await h.readJson(be.join(v,"package.json")).catch(()=>({})))?.version??"unknown");let Be=await h.readJson(T);return Be.dependencies=Be.dependencies??{},Be.dependencies[f]=nt,await h.writeJson(T,Be),e.info("Package installation completed",{pkg:f,version:nt,path:v}),v}finally{R[Symbol.dispose]();}}m$1.install=G;async function Re(f,u,y){let x=f?m$1.acceptable(f)??k():m$1.acceptable()??k(),h=y?.cwd??process.cwd(),w=m$1.args(x,u,h);e.debug(`run shell process: ${x} ${w.join(" ")}`,{command:u,cwd:h});let{windowsHide:R,env:v,...T}=y??{},O={...process.env,LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8",LC_CTYPE:"en_US.UTF-8",...v};process.platform==="win32"&&(O.CHCP="65001");let{stdin:D,stdout:$,stderr:z,timeout:A,signal:L,...te}=T??{},K={...te,cwd:h,env:O,windowsHide:process.platform==="win32"?R??true:void 0,shell:te.shell,timeout:A},X=C(x),et=/^cmd(\.exe)?$/i.test(X),tt=process.platform==="win32"&&et?"cmd":x;return _.run([tt,...w],K)}m$1.run=Re;function j(f,u,y){let x=f?m$1.acceptable(f)??k():m$1.acceptable()??k(),h=y?.cwd??process.cwd(),w=m$1.args(x,u,h);e.debug(`Spawn shell process: ${x} ${w.join(" ")}`,{command:u,cwd:h});let{stdin:R,stdout:v,stderr:T,timeout:O,signal:D,windowsHide:$,env:z,...A}=y??{},L={...process.env,LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8",LC_CTYPE:"en_US.UTF-8",...z};process.platform==="win32"&&(L.CHCP="65001");let te=C(x),K=/^cmd(\.exe)?$/i.test(te),X={...A,cwd:h,env:L,windowsHide:process.platform==="win32"?$??true:void 0,shell:A.shell,timeout:O};return _.spawn([K?"cmd":x,...w],X)}m$1.spawn=j;function S(f,...u){let y=f.reduce((h,w,R)=>h+w+(u[R]??""),""),x=(h={})=>({quiet:()=>x({...h,quiet:true}),nothrow:()=>x({...h,nothrow:true}),cwd:w=>x({...h,cwd:w}),env:w=>x({...h,env:w}),stdin:w=>x({...h,stdin:w}),stdout:w=>x({...h,stdout:w}),stderr:w=>x({...h,stderr:w}),text:async()=>{let w=oe(y.trim());if(w.length===0)throw new Error("Empty command");let R=w[0]??"",v=C(R),T=/^cmd(\.exe)?$/i.test(v),O=process.platform==="win32"&&T?"cmd":ve(R)?R:void 0,D=ge(R,w.slice(1)),$=await m$1.run(O,D,{cwd:h.cwd,env:h.env,stdin:h.stdin,stdout:h.stdout,stderr:h.stderr,timeout:h.timeout,windowsHide:process.platform==="win32"?h.windowsHide??true:void 0,shell:h.shell});if($.code!==0&&!h.nothrow)throw new Error(`Command failed with exit code ${$.code}: ${y}
28
- ${$.stderr}`);return $.stdout},lines:async()=>(await x(h).text()).split(`
29
- `).filter(R=>R.trim()),then:(w,R)=>{let v=oe(y.trim()),T=v[0]??"",O=C(T),D=/^cmd(\.exe)?$/i.test(O),$=process.platform==="win32"&&D?"cmd":ve(T)?T:void 0,z=ge(T,v.slice(1));return m$1.run($,z,{cwd:h.cwd,env:h.env,stdin:h.stdin,stdout:h.stdout,stderr:h.stderr,timeout:h.timeout,windowsHide:process.platform==="win32"?h.windowsHide??true:void 0,shell:h.shell}).then(A=>{if(A.code!==0&&!h.nothrow){let L=new Error(`Command failed with exit code ${A.code}: ${y}
30
- ${A.stderr}`);if(R){R(L);return}throw L}return w({exitCode:A.code,stdout:new TextEncoder().encode(A.stdout),stderr:new TextEncoder().encode(A.stderr),text:()=>A.stdout,lines:()=>A.stdout.split(`
31
- `).filter(L=>L.trim())})},R)}});return x()}m$1.$=S;})(ne||(ne={}));var $r=ne.$;k();var Ee=class Ee extends Error{static create(t,r){var s;let n=De.object({name:De.literal(t),data:r}).meta({ref:t}),o=(s=class extends Ee{constructor(i,l){super(t,l);c$1(this,"data",i);c$1(this,"name",t);this.name=t;}static isInstance(i){return typeof i=="object"&&"name"in i&&i.name===t}schema(){return n}toObject(){return {name:t,data:this.data}}},c$1(s,"Schema",n),s);return Object.defineProperty(o,"name",{value:t}),o}};c$1(Ee,"Unknown",Ee.create("UnknownError",De.object({message:De.string()})));var gt=Ee;k();var ht;(t=>{function e(r){return new bt(r)}t.create=e;})(ht||(ht={}));var bt=class{constructor(t){c$1(this,"rules",[]);c$1(this,"ignorecase");c$1(this,"debug");this.ignorecase=t?.ignorecase??false,this.debug=t?.debug??false;}add(t){let r=typeof t=="string"?t.split(`
32
- `):t;for(let n=0;n<r.length;n++){let o=r[n];this.parseRule(o,n+1);}return this}parseRule(t,r){let n=t;if(n.length===0||n.startsWith("#"))return;let s=n.startsWith("!");if(s&&(n=n.slice(1)),n=n.trimEnd(),n.length===0)return;if(n.startsWith("\\#")){n=n.slice(1);return}if(n.startsWith("#"))return;let i=n.endsWith("/");if(i&&(n=n.slice(0,-1)),n.length===0)return;let l=this.patternToRegex(n);l&&this.rules.push({pattern:n,regex:l,negative:s,isDirectory:i,original:t,lineNumber:r});}ignores(t,r){let n=this.normalizePath(t),o=r??t.endsWith("/"),s=this.checkIgnore(n,o);return this.debug&&console.log(`Ignore.ignores("${t}", isDirectory=${o}) => ${s}`),s}checkIgnore(t,r){let n=false;for(let o of this.rules)o.isDirectory&&!r||o.regex.test(t)&&(o.negative?n=false:n=true);return n}filter(t){return t.filter(r=>!this.ignores(r))}createFilter(){return t=>!this.ignores(t)}patternToRegex(t){let r=[],n=0,o=t.length;for(;n<o;){let p=t[n];if(p==="\\")if(n+1<o){let c=t[n+1];r.push(this.escapeRegexChar(c)),n+=2;continue}else {r.push("\\\\"),n++;continue}if(p==="*")if(n+1<o&&t[n+1]==="*")if(n+2<o&&t[n+2]==="/")if(n===0||t[n-1]==="/")if(n+3>=o){r.push(".*"),n+=3;continue}else {r.push(".*"),n+=3;continue}else {r.push(".*"),n+=3;continue}else if(n===0||t[n-1]==="/")if(n+2>=o){r.push(".*"),n+=2;continue}else {r.push("(?:/.*)*"),n+=2;continue}else {r.push(".*"),n+=2;continue}else {r.push("[^/]*"),n++;continue}if(p==="?"){r.push("[^/]"),n++;continue}if(p==="["){let c=this.findMatchingBracket(t,n);if(c!==-1){let d=t.slice(n,c+1);(d.startsWith("[!")||d.startsWith("[^"))&&(d="[^"+d.slice(2)),this.ignorecase&&(d=d.toLowerCase()),r.push(d),n=c+1;continue}}if(p==="/"){r.push("/"),n++;continue}if(".+$^{}|()".includes(p)){r.push("\\"+p),n++;continue}if(this.ignorecase&&p>="A"&&p<="Z"){r.push("["+p.toLowerCase()+p+"]"),n++;continue}r.push(p),n++;}let s=r.join(""),a=s.startsWith("/"),i=s.endsWith("/")&&!s.endsWith("\\/");a||(s="(?:.*/)?"+s),i&&(s=s.slice(0,-1)),!i&&!s.endsWith("(?:/.*)*")&&(s="(?:"+s+")(?:/.*)?");let l=this.ignorecase?"i":"";try{return new RegExp("^"+s+"$",l)}catch(p){return this.debug&&console.error(`Failed to create regex for pattern "${t}":`,p),null}}escapeRegexChar(t){return "\\[]{}().+^$|".includes(t)?"\\"+t:t}findMatchingBracket(t,r){let n=r+1,o=t.length;for((n>=o||t[n]==="!"||t[n]==="^")&&n++;n<o;){let s=t[n];if(s==="\\"&&n+1<o){n+=2;continue}if(s==="]")return n;if(n+2<o&&t[n+1]==="-"&&t[n+2]!=="]"){n+=3;continue}n++;}return -1}normalizePath(t){let r=t.replace(/\\/g,"/");if(r==="/")return "";for(;r.startsWith("./");)r=r.slice(2);return r}};k();function Sn(e,t){let r=n=>{let o;try{o=e.parse(n);}catch(s){throw console.trace("schema validation failure stack trace:"),s instanceof z.ZodError&&console.error("schema validation issues:",JSON.stringify(s.issues,null,2)),s}return t(o)};return r.force=n=>t(n),r.schema=e,r}var jr=Sn,yt;(t=>t.fn=Sn)(yt||(yt={}));k();function Hr(){let r=be.join(process.cwd(),".env");existsSync(r)&&config({path:r,override:true,debug:false,encoding:"utf-8",quiet:true});}k();async function Wr(e,t){if(process.env.EASBOT_CLIENT==="acp")try{let s=process.platform==="win32"?"cmd":void 0,a=ne.spawn(s,`git ${e.join(" ")}`,{stdin:void 0,stdout:"pipe",stderr:"pipe",cwd:t.cwd,env:t.env?{...process.env,...t.env}:process.env}),[i,l,p]=await Promise.all([a.exited,new Response(a.stdout).arrayBuffer(),new Response(a.stderr).arrayBuffer()]),c=Buffer.from(l),d=Buffer.from(p);return {exitCode:i,text:()=>c.toString(),stdout:c,stderr:d}}catch(s){let a=Buffer.from(s instanceof Error?s.message:String(s));return {exitCode:1,text:()=>"",stdout:Buffer.alloc(0),stderr:a}}let r=t.env?{...process.env,...t.env}:void 0,n=ne.$`git ${e.join(" ")}`.quiet().nothrow().cwd(t.cwd);r&&(n=n.env(r));let o=await n;return {exitCode:o.exitCode,text:()=>o.text(),stdout:o.stdout,stderr:o.stderr}}k();function Tn(e){return e?dirname(fileURLToPath(e)):typeof i<"u"?i:process.cwd()}function kn(e,t,r=3){function n(o,s){if(s>r||!existsSync(o))return null;try{let a=readdirSync(o);for(let i of a){let l=join(o,i);try{let p=statSync(l);if(p.isFile()&&l.endsWith(t))return l;if(p.isDirectory()&&s<r){let c=n(l,s+1);if(c)return c}}catch{}}}catch{}return null}return n(e,0)}function vn(e,t){let r=join(e,t);if(existsSync(r))return r;let n=t.split("/").pop()||t,o=e;for(let s=0;s<5;s++){let a=join(o,"assets","txt");if(existsSync(a)){let p=kn(a,n,5);if(p)return p}let i=join(o,"dist","assets","txt");if(existsSync(i)){let p=kn(i,n,5);if(p)return p}let l=join(o,"..");if(l===o)break;o=l;}return r}function Gr(e,t){return me.lazy(()=>{try{let r=Tn(t),n=vn(r,e);return _.file(n).textSync()}catch(r){throw console.error(`Failed to load text file: ${e}`,r),r}})}function Jr(e,t){return me.lazy(async()=>{try{let r=Tn(t),n=vn(r,e);return await _.file(n).text()}catch(r){throw console.error(`Failed to load text file: ${e}`,r),r}})}k();function Kr(e){return e()}k();function Zr(e){if(!e||typeof e!="string")return {provider:"",model:""};let t=e.indexOf("/");return t===-1?{provider:"",model:e}:{provider:e.substring(0,t),model:e.substring(t+1)}}k();k();k();function xt(e,t,r,n=()=>true){let o=-1,s=-1,a=0;for(let i=t;i<r;i++){if(!n(i))continue;let l=e[i];if(l){if(l==="("){a+=1;continue}if(l===")"&&a>0){a-=1;continue}a===0&&(l===`
33
- `?o=i:/\s/.test(l)&&(s=i));}}return {lastNewline:o,lastWhitespace:s}}function Xr(e,t){if(!e)return [];if(t<=0)return [e];if(e.length<=t)return [e]}function ye(e,t,r){try{let n=z.string().parse(e),o=z.number().int().parse(t),s=Xr(n,o);if(s)return s;let a=wt(n,o,i=>{let{lastNewline:l,lastWhitespace:p}=xt(i,0,i.length);return l>0?l:p});return r?.minLength&&r.minLength>0&&(a=Pn(a,r.minLength)),a}catch(n){return console.warn("Invalid input for chunkText:",n),typeof e=="string"&&e.length>0?[e]:[]}}function Pn(e,t){if(e.length<=1||t<=0)return e;let r=[],n=e[0]??"";for(let o=1;o<e.length;o++){let s=e[o]??"";n.length<t?n=n+`
12
+ ${W}`,truncated:true,outputPath:L,originalLength:c.length,removedLength:ae,label:g}}p.truncate=a;function s(c){return c.truncated?i(c.outputPath,c.label):""}p.formatHint=s;async function l(){let c=j.timestamp(j.create("context",false,Date.now()-o)),f=(await pe.readdir(p.DIR).catch(()=>[])).filter(m=>m.startsWith("context_"));for(let m of f)j.timestamp(m)>=c||await pe.unlink(d.join(p.DIR,m)).catch(()=>{});}p.cleanup=l;})(Oe||(Oe={}));k();var Le;(s=>{let t="New session - ",e="Child session - ";s.parentTitlePrefix=t,s.childTitlePrefix=e;function o(l=false){return (l?e:t)+b(new Date)}s.createDefault=o;function i(l){return new RegExp(`^(${t}|${e})\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}[+-]\\d{2}:\\d{2}$`).test(l)}s.isDefault=i;function a(l){let p=l.match(/^(.+) \(fork #(\d+)\)$/);if(p){let c=p[1]??"",u=parseInt(p[2]??"0",10);return `${c} (fork #${u+1})`}return `${l} (fork #1)`}s.getForked=a;})(Le||(Le={}));k();var ee=class ee extends Error{static create(e,n){var i;let r=fe.object({name:fe.literal(e),data:n}).meta({ref:e}),o=(i=class extends ee{constructor(s,l){super(e,l);c(this,"data",s);c(this,"name",e);this.name=e;}static isInstance(s){return s!==null&&typeof s=="object"&&"name"in s&&s.name===e}schema(){return r}toObject(){return {name:e,data:this.data}}},c(i,"Schema",r),i);return Object.defineProperty(o,"name",{value:e}),o}};c(ee,"Unknown",ee.create("UnknownError",fe.object({message:fe.string()})));var Ee=ee;k();var Ae;(e=>{function t(n){return new $e(n)}e.create=t;})(Ae||(Ae={}));var $e=class{constructor(e){c(this,"rules",[]);c(this,"ignorecase");c(this,"debug");this.ignorecase=e?.ignorecase??false,this.debug=e?.debug??false;}add(e){let n=typeof e=="string"?e.split(`
13
+ `):e;for(let r=0;r<n.length;r++){let o=n[r];this.parseRule(o,r+1);}return this}parseRule(e,n){let r=e,o=e;if(r.length===0||r.startsWith("#"))return;let i=r.startsWith("!");if(i&&(r=r.slice(1)),r=r.trim(),r.length===0||(r.startsWith("\\#")&&(r=r.slice(1)),r.startsWith("#")))return;let a=r.startsWith("/");a&&(r=r.slice(1));let s=r.endsWith("/");s&&(r=r.slice(0,-1)),r.length!==0&&this.rules.push({pattern:r,negative:i,isDirectory:s,anchored:a,original:o,lineNumber:n});}ignores(e,n){let r=this.normalizePath(e),o=n??e.endsWith("/"),i=this.checkIgnore(r,o);return this.debug&&console.log(`Ignore.ignores("${e}", isDirectory=${o}) => ${i}`),i}checkIgnore(e,n){let r=false;for(let o of this.rules)o.isDirectory&&!n||this.matchPath(o,e)&&(o.negative?r=false:r=true);return r}matchPath(e,n){let r=this.ignorecase?n.toLowerCase():n,i=this.ignorecase?e.pattern.toLowerCase():e.pattern;if(e.anchored)return a.match(r,i);if(i.includes("/"))return a.match(r,i);let a$1=r.split("/");for(let s of a$1)if(a.match(s,i))return true;return false}filter(e){return e.filter(n=>!this.ignores(n))}createFilter(){return e=>!this.ignores(e)}normalizePath(e){let n=e.replace(/\\/g,"/");if(n==="/")return "";for(;n.startsWith("./");)n=n.slice(2);return n.endsWith("/")&&n.length>1&&(n=n.slice(0,-1)),n}};k();function it(t,e){let n=r=>{let o;try{o=t.parse(r);}catch(i){throw console.trace("schema validation failure stack trace:"),i instanceof z.ZodError&&console.error("schema validation issues:",JSON.stringify(i.issues,null,2)),i}return e(o)};return n.force=r=>e(r),n.schema=t,n}var sn=it,De;(e=>e.fn=it)(De||(De={}));k();function cn(t={}){let e=t.isDevelopment??false,n=e?".env.dev":".env",r=t.globalConfigPath??(xdgConfig?ze.join(xdgConfig,"easbot"):void 0),o=t.projectRoot??process.cwd(),i=o?ze.join(o,".easbot"):void 0,a=[{root:r,label:"global"},{root:o,label:"project"},{root:i,label:"workspace"}];for(let{root:s}of a){if(!s)continue;let l=ze.join(s,n);if(!existsSync(l))continue;let p=config({path:l,override:true,debug:e,encoding:"utf-8",quiet:!e});if(e&&p.parsed){let u=["XDG_CONFIG_HOME","XDG_DATA_HOME","XDG_CACHE_HOME","XDG_STATE_HOME","XDG_RUNTIME_DIR","EASBOT_CONFIG_PATH","EASBOT_DATA_PATH","EASBOT_CACHE_PATH","EASBOT_STATE_PATH","EASBOT_LOG_PATH","EASBOT_BIN_PATH"].filter(f=>f in p.parsed);u.length>0&&console.warn(`[loadEnv] ${l} contains keys that have no effect: ${u.join(", ")}.
14
+ Reason: xdg-basedir caches XDG_* on import, so this .env file loads too late.
15
+ How to override: export them in the shell before loadEnv() runs, or set process.env directly.`);}}}k();async function un(t,e){if(process.env.EASBOT_CLIENT==="acp")try{let i=process.platform==="win32"?"cmd":void 0,a=G$1.spawn(i,`git ${t.join(" ")}`,{stdin:void 0,stdout:"pipe",stderr:"pipe",cwd:e.cwd,env:e.env?{...process.env,...e.env}:process.env}),[s,l,p]=await Promise.all([a.exited,new Response(a.stdout).arrayBuffer(),new Response(a.stderr).arrayBuffer()]),c=Buffer.from(l),u=Buffer.from(p);return {exitCode:s,text:()=>c.toString(),stdout:c,stderr:u}}catch(i){let a=Buffer.from(i instanceof Error?i.message:String(i));return {exitCode:1,text:()=>"",stdout:Buffer.alloc(0),stderr:a}}let n=e.env?{...process.env,...e.env}:void 0,r=G$1.$`git ${t.join(" ")}`.quiet().nothrow().cwd(e.cwd);n&&(r=r.env(n));let o=await r;return {exitCode:o.exitCode,text:()=>o.text(),stdout:o.stdout,stderr:o.stderr}}k();function ct(t){return t?dirname(fileURLToPath(t)):typeof i<"u"?i:process.cwd()}function lt(t,e,n=3){function r(o,i){if(i>n||!existsSync(o))return null;try{let a=readdirSync(o);for(let s of a){let l=join(o,s);try{let p=statSync(l);if(p.isFile()&&l.endsWith(e))return l;if(p.isDirectory()&&i<n){let c=r(l,i+1);if(c)return c}}catch{}}}catch{}return null}return r(t,0)}function ut(t,e){let n=join(t,e);if(existsSync(n))return n;let r=e.split("/").pop()||e,o=t;for(let i=0;i<5;i++){let a=join(o,"assets","txt");if(existsSync(a)){let p=lt(a,r,5);if(p)return p}let s=join(o,"dist","assets","txt");if(existsSync(s)){let p=lt(s,r,5);if(p)return p}let l=join(o,"..");if(l===o)break;o=l;}return n}function hn(t,e){return c$1.lazy(()=>{try{let n=ct(e),r=ut(n,t);return D.file(r).textSync()}catch(n){throw console.error(`Failed to load text file: ${t}`,n),n}})}function gn(t,e){return c$1.lazy(async()=>{try{let n=ct(e),r=ut(n,t);return await D.file(r).text()}catch(n){throw console.error(`Failed to load text file: ${t}`,n),n}})}k();function yn(t){return t()}k();function bn(t){if(!t||typeof t!="string")return {provider:"",model:""};let e=t.indexOf("/");return e===-1?{provider:"",model:t}:{provider:t.substring(0,e),model:t.substring(e+1)}}k();k();k();function Be(t,e,n,r=()=>true){let o=-1,i=-1,a=0;for(let s=e;s<n;s++){if(!r(s))continue;let l=t[s];if(l){if(l==="("){a+=1;continue}if(l===")"&&a>0){a-=1;continue}a===0&&(l===`
16
+ `?o=s:/\s/.test(l)&&(i=s));}}return {lastNewline:o,lastWhitespace:i}}function xn(t,e){if(!t)return [];if(e<=0)return [t];if(t.length<=e)return [t]}function G(t,e,n){try{let r=z.string().parse(t),o=z.number().int().parse(e),i=xn(r,o);if(i)return i;let a=Ne(r,o,s=>{let{lastNewline:l,lastWhitespace:p}=Be(s,0,s.length);return l>0?l:p});return n?.minLength&&n.minLength>0&&(a=ft(a,n.minLength)),a}catch(r){return console.warn("Invalid input for chunkText:",r),typeof t=="string"&&t.length>0?[t]:[]}}function ft(t,e){if(t.length<=1||e<=0)return t;let n=[],r=t[0]??"";for(let o=1;o<t.length;o++){let i=t[o]??"";r.length<e?r=r+`
34
17
 
35
- `+s:(r.push(n),n=s);}if(n.length>0)if(n.length<t&&r.length>0){let o=r.pop();r.push(o+`
18
+ `+i:(n.push(r),r=i);}if(r.length>0)if(r.length<e&&n.length>0){let o=n.pop();n.push(o+`
36
19
 
37
- `+n);}else r.push(n);return r}function wt(e,t,r){if(!e)return [];if(t<=0||e.length<=t)return [e];let n=[],o=e;for(;o.length>t;){let s=o.slice(0,t),a=r(s),i=Number.isFinite(a)&&a>0&&a<=t?a:t,p=o.slice(0,i).trimEnd();p.length>0&&n.push(p);let c=i<o.length&&o[i]!==void 0&&/\s/.test(o[i]),d=Math.min(o.length,i+(c?1:0));o=o.slice(d).trimStart();}return o.length>0&&n.push(o),n}k();var St=z.enum(["bold","italic","strikethrough","code","code_block","spoiler","blockquote"]),Mn=z.object({start:z.number().int().min(0),end:z.number().int().min(0),style:St}).strict().refine(e=>e.end>=e.start,{message:"end must be greater than or equal to start"}),En=z.object({start:z.number().int().min(0),end:z.number().int().min(0),href:z.string().min(1)}).strict().refine(e=>e.end>=e.start,{message:"end must be greater than or equal to start"}),Ie=z.object({text:z.string(),styles:z.array(Mn),links:z.array(En)}).strict(),Oe=z.enum(["off","bullets","code"]),We=z.object({linkify:z.boolean().default(true),enableSpoilers:z.boolean().default(false),headingStyle:z.enum(["none","bold"]).default("none"),blockquotePrefix:z.string().default(""),autolink:z.boolean().default(true),tableMode:Oe.default("off")}).partial().default({}),Cn=z.object({open:z.string(),close:z.string()}).strict(),kt=z.object({styleMarkers:z.record(St,Cn).optional(),escapeText:z.any().optional(),buildLink:z.any().optional()}).strict();z.object({start:z.number().int().min(0),end:z.number().int().min(0),open:z.string(),close:z.string()}).strict();var Tt=z.object({indentSize:z.number().int().min(1).default(2),listMarker:z.enum(["\u2022","-","*"]).default("\u2022"),codeBlockMarker:z.enum(["```","~~~"]).default("```"),preserveFrontmatter:z.boolean().default(true)}).strict(),vt=z.record(z.string(),z.string()),Ue=z.object({open:z.boolean(),ticks:z.number().int().min(0)}).strict();z.object({inlineState:Ue,isInside:z.any()}).strict();z.object({start:z.number().int().min(0),end:z.number().int().min(0),openLine:z.string(),marker:z.string(),indent:z.string()}).strict();z.object({tables:Oe.optional()}).strict();function oo(e){let t=new ro({html:false,linkify:e.linkify??true,breaks:false,typographer:false});return t.enable("strikethrough"),e.tableMode&&e.tableMode!=="off"?t.enable("table"):t.disable("table"),e.autolink===false&&t.disable("autolink"),t}function In(e,t){if(e.attrGet)return e.attrGet(t);if(e.attrs){for(let[r,n]of e.attrs)if(r===t)return n}return null}function Rt(e,t){return {...e,type:"text",content:t,children:void 0}}function so(e){for(let t of e)t.children&&t.children.length>0&&(t.children=io(t.children));}function io(e){let t=0;for(let a of e){if(a.type!=="text")continue;let i=a.content??"",l=0;for(;l<i.length;){let p=i.indexOf("||",l);if(p===-1)break;t+=1,l=p+2;}}if(t<2)return e;let r=t-t%2,n=[],o={spoilerOpen:false},s=0;for(let a of e){if(a.type!=="text"){n.push(a);continue}let i=a.content??"";if(!i.includes("||")){n.push(a);continue}let l=0;for(;l<i.length;){let p=i.indexOf("||",l);if(p===-1){l<i.length&&n.push(Rt(a,i.slice(l)));break}if(s>=r){n.push(Rt(a,i.slice(l)));break}p>l&&n.push(Rt(a,i.slice(l,p))),s+=1,o.spoilerOpen=!o.spoilerOpen,n.push({type:o.spoilerOpen?"spoiler_open":"spoiler_close"}),l=p+2;}}return n}function ao(){return {text:"",styles:[],openStyles:[],links:[],linkStack:[]}}function de(e){return e.table?.currentCell??e}function qe(e,t){if(!t)return;let r=de(e);r.text+=t;}function xe(e,t){let r=de(e);r.openStyles.push({style:t,start:r.text.length});}function we(e,t){let r=de(e);for(let n=r.openStyles.length-1;n>=0;n-=1){let o=r.openStyles[n];if(o?.style===t){let s=o.start;r.openStyles.splice(n,1);let a=r.text.length;a>s&&r.styles.push({start:s,end:a,style:t});return}}}function On(e){e.env.listStack.length>0||e.table||(e.text+=`
20
+ `+r);}else n.push(r);return n}function Ne(t,e,n){if(!t)return [];if(e<=0||t.length<=e)return [t];let r=[],o=t;for(;o.length>e;){let i=o.slice(0,e),a=n(i),s=Number.isFinite(a)&&a>0&&a<=e?a:e,p=o.slice(0,s).trimEnd();p.length>0&&r.push(p);let c=s<o.length&&o[s]!==void 0&&/\s/.test(o[s]),u=Math.min(o.length,s+(c?1:0));o=o.slice(u).trimStart();}return o.length>0&&r.push(o),r}k();var je=z.enum(["bold","italic","strikethrough","code","code_block","spoiler","blockquote"]),dt=z.object({start:z.number().int().min(0),end:z.number().int().min(0),style:je}).strict().refine(t=>t.end>=t.start,{message:"end must be greater than or equal to start"}),mt=z.object({start:z.number().int().min(0),end:z.number().int().min(0),href:z.string().min(1)}).strict().refine(t=>t.end>=t.start,{message:"end must be greater than or equal to start"}),ne=z.object({text:z.string(),styles:z.array(dt),links:z.array(mt)}).strict(),re=z.enum(["off","bullets","code"]),me=z.object({linkify:z.boolean().default(true),enableSpoilers:z.boolean().default(false),headingStyle:z.enum(["none","bold"]).default("none"),blockquotePrefix:z.string().default(""),autolink:z.boolean().default(true),tableMode:re.default("off")}).partial().default({}),ht=z.object({open:z.string(),close:z.string()}).strict(),He=z.object({styleMarkers:z.record(je,ht).optional(),escapeText:z.any().optional(),buildLink:z.any().optional()}).strict();z.object({start:z.number().int().min(0),end:z.number().int().min(0),open:z.string(),close:z.string()}).strict();var Ue=z.object({indentSize:z.number().int().min(1).default(2),listMarker:z.enum(["\u2022","-","*"]).default("\u2022"),codeBlockMarker:z.enum(["```","~~~"]).default("```"),preserveFrontmatter:z.boolean().default(true)}).strict(),We=z.record(z.string(),z.string()),he=z.object({open:z.boolean(),ticks:z.number().int().min(0)}).strict();z.object({inlineState:he,isInside:z.any()}).strict();z.object({start:z.number().int().min(0),end:z.number().int().min(0),openLine:z.string(),marker:z.string(),indent:z.string()}).strict();z.object({tables:re.optional()}).strict();function Rn(t){let e=new Mn({html:false,linkify:t.linkify??true,breaks:false,typographer:false});return e.enable("strikethrough"),t.tableMode&&t.tableMode!=="off"?e.enable("table"):e.disable("table"),t.autolink===false&&e.disable("autolink"),e}function gt(t,e){if(t.attrGet)return t.attrGet(e);if(t.attrs){for(let[n,r]of t.attrs)if(n===e)return r}return null}function qe(t,e){return {...t,type:"text",content:e,children:void 0}}function vn(t){for(let e of t)e.children&&e.children.length>0&&(e.children=In(e.children));}function In(t){let e=0;for(let a of t){if(a.type!=="text")continue;let s=a.content??"",l=0;for(;l<s.length;){let p=s.indexOf("||",l);if(p===-1)break;e+=1,l=p+2;}}if(e<2)return t;let n=e-e%2,r=[],o={spoilerOpen:false},i=0;for(let a of t){if(a.type!=="text"){r.push(a);continue}let s=a.content??"";if(!s.includes("||")){r.push(a);continue}let l=0;for(;l<s.length;){let p=s.indexOf("||",l);if(p===-1){l<s.length&&r.push(qe(a,s.slice(l)));break}if(i>=n){r.push(qe(a,s.slice(l)));break}p>l&&r.push(qe(a,s.slice(l,p))),i+=1,o.spoilerOpen=!o.spoilerOpen,r.push({type:o.spoilerOpen?"spoiler_open":"spoiler_close"}),l=p+2;}}return r}function Pn(){return {text:"",styles:[],openStyles:[],links:[],linkStack:[]}}function U(t){return t.table?.currentCell??t}function ge(t,e){if(!e)return;let n=U(t);n.text+=e;}function Y(t,e){let n=U(t);n.openStyles.push({style:e,start:n.text.length});}function X(t,e){let n=U(t);for(let r=n.openStyles.length-1;r>=0;r-=1){let o=n.openStyles[r];if(o?.style===e){let i=o.start;n.openStyles.splice(r,1);let a=n.text.length;a>i&&n.styles.push({start:i,end:a,style:e});return}}}function yt(t){t.env.listStack.length>0||t.table||(t.text+=`
38
21
 
39
- `);}function lo(e){let t=e.env.listStack,r=t[t.length-1];if(!r)return;r.index+=1;let n=" ".repeat(Math.max(0,t.length-1)),o=r.type==="ordered"?`${r.index}. `:"\u2022 ";e.text+=`${n}${o}`;}function co(e,t){if(!t)return;let r=de(e),n=r.text.length;r.text+=t,r.styles.push({start:n,end:n+t.length,style:"code"});}function uo(e,t){let r=t??"",n=de(e),o=n.text.length;n.text+=r,n.styles.push({start:o,end:o+r.length,style:"code_block"});}function fo(e){let t=de(e),r=t.linkStack.pop();if(!r?.href)return;let n=r.href.trim();if(!n)return;let o=r.labelStart,s=t.text.length;if(s<=o){t.links.push({start:o,end:s,href:n});return}t.links.push({start:o,end:s,href:n});}function po(){return {headers:[],rows:[],currentRow:[],currentCell:null,inHeader:false}}function mo(e){return An(e),{text:e.text,styles:e.styles,links:e.links}}function Ye(e){let t=e.text,r=0,n=t.length;for(;r<n&&/\s/.test(t[r]??"");)r+=1;for(;n>r&&/\s/.test(t[n-1]??"");)n-=1;if(r===0&&n===t.length)return e;let o=t.slice(r,n),s=o.length,a=[];for(let l of e.styles){let p=Math.max(0,l.start-r),c=Math.min(s,l.end-r);c>p&&a.push({start:p,end:c,style:l.style});}let i=[];for(let l of e.links){let p=Math.max(0,l.start-r),c=Math.min(s,l.end-r);c>p&&i.push({start:p,end:c,href:l.href});}return {text:o,styles:a,links:i}}function Pt(e,t){if(!t.text)return;let r=e.text.length;e.text+=t.text;for(let n of t.styles)e.styles.push({start:r+n.start,end:r+n.end,style:n.style});for(let n of t.links)e.links.push({start:r+n.start,end:r+n.end,href:n.href});}function go(e,t){t.text&&(e.text+=t.text);}function Fn(e,t){let{header:r,value:n,columnIndex:o,includeColumnFallback:s}=t;n?.text&&(e.text+="\u2022 ",r?.text?(Pt(e,r),e.text+=": "):s&&(e.text+=`Column ${o}: `),Pt(e,n),e.text+=`
40
- `);}function ho(e){if(!e.table)return;let t=e.table.headers.map(Ye),r=e.table.rows.map(o=>o.map(Ye));if(t.length===0&&r.length===0)return;if(t.length>1&&r.length>0)for(let o of r){if(o.length===0)continue;let s=o[0];if(s?.text){let a=e.text.length;Pt(e,s);let i=e.text.length;i>a&&e.styles.push({start:a,end:i,style:"bold"}),e.text+=`
41
- `;}for(let a=1;a<o.length;a++)Fn(e,{header:t[a],value:o[a],columnIndex:a,includeColumnFallback:true});e.text+=`
42
- `;}else for(let o of r){for(let s=0;s<o.length;s++)Fn(e,{header:t[s],value:o[s],columnIndex:s,includeColumnFallback:false});e.text+=`
43
- `;}}function bo(e){if(!e.table)return;let t=e.table.headers.map(Ye),r=e.table.rows.map(c=>c.map(Ye)),n=Math.max(t.length,...r.map(c=>c.length));if(n===0)return;let o=Array.from({length:n},()=>0),s=c=>{for(let d=0;d<n;d+=1){let k=c[d]?.text.length??0;(o[d]??0)<k&&(o[d]=k);}};s(t);for(let c of r)s(c);let a=e.text.length,i=c=>{e.text+="|";for(let d=0;d<n;d+=1){e.text+=" ";let g=c[d];g&&go(e,g);let k=g?.text.length??0,W=(o[d]??0)-k;W>0&&(e.text+=" ".repeat(W)),e.text+=" |";}e.text+=`
44
- `;},l=()=>{e.text+="|";for(let c=0;c<n;c+=1){let d=o[c]??0,g=Math.max(3,d);e.text+=` ${"-".repeat(g)} |`;}e.text+=`
45
- `;};i(t),l();for(let c of r)i(c);let p=e.text.length;p>a&&e.styles.push({start:a,end:p,style:"code_block"});}function Mt(e,t){for(let r of e)switch(r.type){case "inline":r.children&&Mt(r.children,t);break;case "text":qe(t,r.content??"");break;case "em_open":xe(t,"italic");break;case "em_close":we(t,"italic");break;case "strong_open":xe(t,"bold");break;case "strong_close":we(t,"bold");break;case "s_open":xe(t,"strikethrough");break;case "s_close":we(t,"strikethrough");break;case "code_inline":co(t,r.content??"");break;case "spoiler_open":t.enableSpoilers&&xe(t,"spoiler");break;case "spoiler_close":t.enableSpoilers&&we(t,"spoiler");break;case "link_open":{let n=In(r,"href")??"",o=de(t);o.linkStack.push({href:n,labelStart:o.text.length});break}case "link_close":fo(t);break;case "image":qe(t,r.content??"");break;case "softbreak":case "hardbreak":qe(t,`
46
- `);break;case "paragraph_close":On(t);break;case "heading_open":t.headingStyle==="bold"&&xe(t,"bold");break;case "heading_close":t.headingStyle==="bold"&&we(t,"bold"),On(t);break;case "blockquote_open":t.blockquotePrefix&&(t.text+=t.blockquotePrefix),xe(t,"blockquote");break;case "blockquote_close":we(t,"blockquote");break;case "bullet_list_open":t.env.listStack.length>0&&(t.text+=`
47
- `),t.env.listStack.push({type:"bullet",index:0});break;case "bullet_list_close":t.env.listStack.pop(),t.env.listStack.length===0&&(t.text+=`
48
- `);break;case "ordered_list_open":{t.env.listStack.length>0&&(t.text+=`
49
- `);let n=Number(In(r,"start")??"1");t.env.listStack.push({type:"ordered",index:n-1});break}case "ordered_list_close":t.env.listStack.pop(),t.env.listStack.length===0&&(t.text+=`
50
- `);break;case "list_item_open":lo(t);break;case "list_item_close":t.text.endsWith(`
51
- `)||(t.text+=`
52
- `);break;case "code_block":case "fence":uo(t,r.content??"");break;case "html_block":case "html_inline":qe(t,r.content??"");break;case "table_open":t.tableMode!=="off"&&(t.table=po(),t.hasTables=true);break;case "table_close":t.table&&(t.tableMode==="bullets"?ho(t):t.tableMode==="code"&&bo(t)),t.table=null;break;case "thead_open":t.table&&(t.table.inHeader=true);break;case "thead_close":t.table&&(t.table.inHeader=false);break;case "tbody_open":case "tbody_close":break;case "tr_open":t.table&&(t.table.currentRow=[]);break;case "tr_close":t.table&&(t.table.inHeader?t.table.headers=t.table.currentRow:t.table.rows.push(t.table.currentRow),t.table.currentRow=[]);break;case "th_open":case "td_open":t.table&&(t.table.currentCell=ao());break;case "th_close":case "td_close":t.table?.currentCell&&(t.table.currentRow.push(mo(t.table.currentCell)),t.table.currentCell=null);break;case "hr":t.text+=`\u2500\u2500\u2500
22
+ `);}function Fn(t){let e=t.env.listStack,n=e[e.length-1];if(!n)return;n.index+=1;let r=" ".repeat(Math.max(0,e.length-1)),o=n.type==="ordered"?`${n.index}. `:"\u2022 ";t.text+=`${r}${o}`;}function Cn(t,e){if(!e)return;let n=U(t),r=n.text.length;n.text+=e,n.styles.push({start:r,end:r+e.length,style:"code"});}function _n(t,e){let n=e??"",r=U(t),o=r.text.length;r.text+=n,r.styles.push({start:o,end:o+n.length,style:"code_block"});}function On(t){let e=U(t),n=e.linkStack.pop();if(!n?.href)return;let r=n.href.trim();if(!r)return;let o=n.labelStart,i=e.text.length;if(i<=o){e.links.push({start:o,end:i,href:r});return}e.links.push({start:o,end:i,href:r});}function Ln(){return {headers:[],rows:[],currentRow:[],currentCell:null,inHeader:false}}function En(t){return xt(t),{text:t.text,styles:t.styles,links:t.links}}function ye(t){let e=t.text,n=0,r=e.length;for(;n<r&&/\s/.test(e[n]??"");)n+=1;for(;r>n&&/\s/.test(e[r-1]??"");)r-=1;if(n===0&&r===e.length)return t;let o=e.slice(n,r),i=o.length,a=[];for(let l of t.styles){let p=Math.max(0,l.start-n),c=Math.min(i,l.end-n);c>p&&a.push({start:p,end:c,style:l.style});}let s=[];for(let l of t.links){let p=Math.max(0,l.start-n),c=Math.min(i,l.end-n);c>p&&s.push({start:p,end:c,href:l.href});}return {text:o,styles:a,links:s}}function Ge(t,e){if(!e.text)return;let n=t.text.length;t.text+=e.text;for(let r of e.styles)t.styles.push({start:n+r.start,end:n+r.end,style:r.style});for(let r of e.links)t.links.push({start:n+r.start,end:n+r.end,href:r.href});}function An(t,e){e.text&&(t.text+=e.text);}function bt(t,e){let{header:n,value:r,columnIndex:o,includeColumnFallback:i}=e;r?.text&&(t.text+="\u2022 ",n?.text?(Ge(t,n),t.text+=": "):i&&(t.text+=`Column ${o}: `),Ge(t,r),t.text+=`
23
+ `);}function $n(t){if(!t.table)return;let e=t.table.headers.map(ye),n=t.table.rows.map(o=>o.map(ye));if(e.length===0&&n.length===0)return;if(e.length>1&&n.length>0)for(let o of n){if(o.length===0)continue;let i=o[0];if(i?.text){let a=t.text.length;Ge(t,i);let s=t.text.length;s>a&&t.styles.push({start:a,end:s,style:"bold"}),t.text+=`
24
+ `;}for(let a=1;a<o.length;a++)bt(t,{header:e[a],value:o[a],columnIndex:a,includeColumnFallback:true});t.text+=`
25
+ `;}else for(let o of n){for(let i=0;i<o.length;i++)bt(t,{header:e[i],value:o[i],columnIndex:i,includeColumnFallback:false});t.text+=`
26
+ `;}}function Dn(t){if(!t.table)return;let e=t.table.headers.map(ye),n=t.table.rows.map(c=>c.map(ye)),r=Math.max(e.length,...n.map(c=>c.length));if(r===0)return;let o=Array.from({length:r},()=>0),i=c=>{for(let u=0;u<r;u+=1){let m=c[u]?.text.length??0;(o[u]??0)<m&&(o[u]=m);}};i(e);for(let c of n)i(c);let a=t.text.length,s=c=>{t.text+="|";for(let u=0;u<r;u+=1){t.text+=" ";let f=c[u];f&&An(t,f);let m=f?.text.length??0,S=(o[u]??0)-m;S>0&&(t.text+=" ".repeat(S)),t.text+=" |";}t.text+=`
27
+ `;},l=()=>{t.text+="|";for(let c=0;c<r;c+=1){let u=o[c]??0,f=Math.max(3,u);t.text+=` ${"-".repeat(f)} |`;}t.text+=`
28
+ `;};s(e),l();for(let c of n)s(c);let p=t.text.length;p>a&&t.styles.push({start:a,end:p,style:"code_block"});}function Ye(t,e){for(let n of t)switch(n.type){case "inline":n.children&&Ye(n.children,e);break;case "text":ge(e,n.content??"");break;case "em_open":Y(e,"italic");break;case "em_close":X(e,"italic");break;case "strong_open":Y(e,"bold");break;case "strong_close":X(e,"bold");break;case "s_open":Y(e,"strikethrough");break;case "s_close":X(e,"strikethrough");break;case "code_inline":Cn(e,n.content??"");break;case "spoiler_open":e.enableSpoilers&&Y(e,"spoiler");break;case "spoiler_close":e.enableSpoilers&&X(e,"spoiler");break;case "link_open":{let r=gt(n,"href")??"",o=U(e);o.linkStack.push({href:r,labelStart:o.text.length});break}case "link_close":On(e);break;case "image":ge(e,n.content??"");break;case "softbreak":case "hardbreak":ge(e,`
29
+ `);break;case "paragraph_close":yt(e);break;case "heading_open":e.headingStyle==="bold"&&Y(e,"bold");break;case "heading_close":e.headingStyle==="bold"&&X(e,"bold"),yt(e);break;case "blockquote_open":e.blockquotePrefix&&(e.text+=e.blockquotePrefix),Y(e,"blockquote");break;case "blockquote_close":X(e,"blockquote");break;case "bullet_list_open":e.env.listStack.length>0&&(e.text+=`
30
+ `),e.env.listStack.push({type:"bullet",index:0});break;case "bullet_list_close":e.env.listStack.pop(),e.env.listStack.length===0&&(e.text+=`
31
+ `);break;case "ordered_list_open":{e.env.listStack.length>0&&(e.text+=`
32
+ `);let r=Number(gt(n,"start")??"1");e.env.listStack.push({type:"ordered",index:r-1});break}case "ordered_list_close":e.env.listStack.pop(),e.env.listStack.length===0&&(e.text+=`
33
+ `);break;case "list_item_open":Fn(e);break;case "list_item_close":e.text.endsWith(`
34
+ `)||(e.text+=`
35
+ `);break;case "code_block":case "fence":_n(e,n.content??"");break;case "html_block":case "html_inline":ge(e,n.content??"");break;case "table_open":e.tableMode!=="off"&&(e.table=Ln(),e.hasTables=true);break;case "table_close":e.table&&(e.tableMode==="bullets"?$n(e):e.tableMode==="code"&&Dn(e)),e.table=null;break;case "thead_open":e.table&&(e.table.inHeader=true);break;case "thead_close":e.table&&(e.table.inHeader=false);break;case "tbody_open":case "tbody_close":break;case "tr_open":e.table&&(e.table.currentRow=[]);break;case "tr_close":e.table&&(e.table.inHeader?e.table.headers=e.table.currentRow:e.table.rows.push(e.table.currentRow),e.table.currentRow=[]);break;case "th_open":case "td_open":e.table&&(e.table.currentCell=Pn());break;case "th_close":case "td_close":e.table?.currentCell&&(e.table.currentRow.push(En(e.table.currentCell)),e.table.currentCell=null);break;case "hr":e.text+=`\u2500\u2500\u2500
53
36
 
54
- `;break;default:r.children&&Mt(r.children,t);break}}function An(e){for(let t=e.openStyles.length-1;t>=0;t-=1){let r=e.openStyles[t];if(!r)continue;let n=e.text.length;n>r.start&&e.styles.push({start:r.start,end:n,style:r.style});}e.openStyles=[];}function yo(e,t){let r=[];for(let n of e){let o=Math.max(0,Math.min(n.start,t)),s=Math.max(o,Math.min(n.end,t));s>o&&r.push({start:o,end:s,style:n.style});}return r}function xo(e,t){let r=[];for(let n of e){let o=Math.max(0,Math.min(n.start,t)),s=Math.max(o,Math.min(n.end,t));s>o&&r.push({start:o,end:s,href:n.href});}return r}function Ln(e){let t=[...e].toSorted((n,o)=>n.start!==o.start?n.start-o.start:n.end!==o.end?n.end-o.end:n.style.localeCompare(o.style)),r=[];for(let n of t){let o=r[r.length-1];if(o&&o.style===n.style&&(n.start<o.end||n.start===o.end&&n.style!=="blockquote")){o.end=Math.max(o.end,n.end);continue}r.push({...n});}return r}function Bn(e,t,r){let n=Math.max(e.start,t),o=Math.min(e.end,r);return o<=n?null:{start:n,end:o}}function wo(e,t,r){if(e.length===0)return [];let n=[];for(let o of e){let s=Bn(o,t,r);s&&n.push({start:s.start-t,end:s.end-t,style:o.style});}return Ln(n)}function So(e,t,r){if(e.length===0)return [];let n=[];for(let o of e){let s=Bn(o,t,r);s&&n.push({start:s.start-t,end:s.end-t,href:o.href});}return n}function Se(e,t){try{let r=typeof e=="string"?e:"",n=We.parse(t??{});return Fe(r,n).ir}catch(r){return console.error("Markdown parse error:",r),{text:"",styles:[],links:[]}}}function Fe(e,t){try{let r=typeof e=="string"?e:"",n=We.parse(t),o={listStack:[]},a=oo(n).parse(r||"",o);n.enableSpoilers&&so(a);let i=n.tableMode??"off",l={text:"",styles:[],openStyles:[],links:[],linkStack:[],env:o,headingStyle:n.headingStyle??"none",blockquotePrefix:n.blockquotePrefix??"",enableSpoilers:n.enableSpoilers??!1,tableMode:i,table:null,hasTables:!1};Mt(a,l),An(l);let c=l.text.trimEnd().length,d=0;for(let C of l.styles)C.style==="code_block"&&C.end>d&&(d=C.end);let g=Math.max(c,d);return {ir:{text:g===l.text.length?l.text:l.text.slice(0,g),styles:Ln(yo(l.styles,g)),links:xo(l.links,g)},hasTables:l.hasTables}}catch(r){return console.error("Markdown parse error:",r),{ir:{text:"",styles:[],links:[]},hasTables:false}}}function $n(e,t){try{let r=Ie.parse(e),n=typeof t=="number"&&t>0?t:0;if(!r.text)return [];if(n<=0||r.text.length<=n)return [r];let o=ye(r.text,n),s=[],a=0;return o.forEach((i,l)=>{if(!i)return;if(l>0)for(;a<r.text.length&&/\s/.test(r.text[a]??"");)a+=1;let p=a,c=Math.min(r.text.length,p+i.length);s.push({text:i,styles:wo(r.styles,p,c),links:So(r.links,p,c)}),a=c;}),s}catch(r){return console.error("Chunk IR error:",r),[]}}k();var ko={bold:{open:"**",close:"**"},italic:{open:"*",close:"*"},strikethrough:{open:"~~",close:"~~"},code:{open:"`",close:"`"},code_block:{open:"```\n",close:"```"},spoiler:{open:"||",close:"||"},blockquote:{open:"> ",close:""}};function Ae(e,t){try{let r=Ie.parse(e),n=kt.parse(t??{});if(!r.text)return "";let o=n.styleMarkers??ko,s=n.escapeText??(d=>d),a=n.buildLink,i=[];for(let d=0;d<r.styles.length;d++){let g=r.styles[d];g&&(i.push({position:g.start,type:"open",style:g.style,spanIndex:d}),i.push({position:g.end,type:"close",style:g.style,spanIndex:d}));}for(let d=0;d<r.links.length;d++){let g=r.links[d];g&&(i.push({position:g.start,type:"link_open",spanIndex:d,href:g.href}),i.push({position:g.end,type:"link_close",spanIndex:d,href:g.href}));}i.sort((d,g)=>{if(d.position!==g.position)return d.position-g.position;let k=(V,J)=>V==="link_open"?0:V==="open"?1:V==="close"?2:V==="link_close"?3:4,C=d.type==="close"||d.type==="link_close",W=g.type==="close"||g.type==="link_close",q=k(d.type,C),Y=k(g.type,W);return q!==Y?q-Y:d.type==="open"&&g.type==="open"?d.spanIndex-g.spanIndex:d.type==="close"&&g.type==="close"?g.spanIndex-d.spanIndex:d.spanIndex-g.spanIndex});let l="",p=0,c=[];for(let d of i){if(d.position>p){let g=r.text.slice(p,d.position);l+=s?s(g):g;}if(d.type==="open"||d.type==="close"){let g=o[d.style];if(g)if(d.type==="open")l+=g.open,c.push(d);else {l+=g.close,d.style==="code_block"&&d.position<r.text.length&&(l+=`
55
- `);let k=c.findIndex(C=>C.spanIndex===d.spanIndex&&C.type==="open");k!==-1&&c.splice(k,1);}}else if(d.type==="link_open")l+="[",c.push(d);else if(d.type==="link_close"){l+="]("+d.href+")";let g=c.findIndex(k=>k.spanIndex===d.spanIndex&&k.type==="link_open");g!==-1&&c.splice(g,1);}p=d.position;}if(p<r.text.length){let d=r.text.slice(p);l+=s?s(d):d;}return l}catch(r){return console.error("Markdown render error:",r),""}}function ke(e,t){return Ae(e,t)}k();function To(e){let t=e.replace(/\r\n/g,`
37
+ `;break;default:n.children&&Ye(n.children,e);break}}function xt(t){for(let e=t.openStyles.length-1;e>=0;e-=1){let n=t.openStyles[e];if(!n)continue;let r=t.text.length;r>n.start&&t.styles.push({start:n.start,end:r,style:n.style});}t.openStyles=[];}function zn(t,e){let n=[];for(let r of t){let o=Math.max(0,Math.min(r.start,e)),i=Math.max(o,Math.min(r.end,e));i>o&&n.push({start:o,end:i,style:r.style});}return n}function Bn(t,e){let n=[];for(let r of t){let o=Math.max(0,Math.min(r.start,e)),i=Math.max(o,Math.min(r.end,e));i>o&&n.push({start:o,end:i,href:r.href});}return n}function kt(t){let e=[...t].toSorted((r,o)=>r.start!==o.start?r.start-o.start:r.end!==o.end?r.end-o.end:r.style.localeCompare(o.style)),n=[];for(let r of e){let o=n[n.length-1];if(o&&o.style===r.style&&(r.start<o.end||r.start===o.end&&r.style!=="blockquote")){o.end=Math.max(o.end,r.end);continue}n.push({...r});}return n}function St(t,e,n){let r=Math.max(t.start,e),o=Math.min(t.end,n);return o<=r?null:{start:r,end:o}}function Nn(t,e,n){if(t.length===0)return [];let r=[];for(let o of t){let i=St(o,e,n);i&&r.push({start:i.start-e,end:i.end-e,style:o.style});}return kt(r)}function jn(t,e,n){if(t.length===0)return [];let r=[];for(let o of t){let i=St(o,e,n);i&&r.push({start:i.start-e,end:i.end-e,href:o.href});}return r}function V(t,e){try{let n=typeof t=="string"?t:"",r=me.parse(e??{});return oe(n,r).ir}catch(n){return console.error("Markdown parse error:",n),{text:"",styles:[],links:[]}}}function oe(t,e){try{let n=typeof t=="string"?t:"",r=me.parse(e),o={listStack:[]},a=Rn(r).parse(n||"",o);r.enableSpoilers&&vn(a);let s=r.tableMode??"off",l={text:"",styles:[],openStyles:[],links:[],linkStack:[],env:o,headingStyle:r.headingStyle??"none",blockquotePrefix:r.blockquotePrefix??"",enableSpoilers:r.enableSpoilers??!1,tableMode:s,table:null,hasTables:!1};Ye(a,l),xt(l);let c=l.text.trimEnd().length,u=0;for(let g of l.styles)g.style==="code_block"&&g.end>u&&(u=g.end);let f=Math.max(c,u);return {ir:{text:f===l.text.length?l.text:l.text.slice(0,f),styles:kt(zn(l.styles,f)),links:Bn(l.links,f)},hasTables:l.hasTables}}catch(n){return console.error("Markdown parse error:",n),{ir:{text:"",styles:[],links:[]},hasTables:false}}}function wt(t,e){try{let n=ne.parse(t),r=typeof e=="number"&&e>0?e:0;if(!n.text)return [];if(r<=0||n.text.length<=r)return [n];let o=G(n.text,r),i=[],a=0;return o.forEach((s,l)=>{if(!s)return;if(l>0)for(;a<n.text.length&&/\s/.test(n.text[a]??"");)a+=1;let p=a,c=Math.min(n.text.length,p+s.length);i.push({text:s,styles:Nn(n.styles,p,c),links:jn(n.links,p,c)}),a=c;}),i}catch(n){return console.error("Chunk IR error:",n),[]}}k();var Hn={bold:{open:"**",close:"**"},italic:{open:"*",close:"*"},strikethrough:{open:"~~",close:"~~"},code:{open:"`",close:"`"},code_block:{open:"```\n",close:"```"},spoiler:{open:"||",close:"||"},blockquote:{open:"> ",close:""}};function se(t,e){try{let n=ne.parse(t),r=He.parse(e??{});if(!n.text)return "";let o=r.styleMarkers??Hn,i=r.escapeText??(u=>u),a=r.buildLink,s=[];for(let u=0;u<n.styles.length;u++){let f=n.styles[u];f&&(s.push({position:f.start,type:"open",style:f.style,spanIndex:u}),s.push({position:f.end,type:"close",style:f.style,spanIndex:u}));}for(let u=0;u<n.links.length;u++){let f=n.links[u];f&&(s.push({position:f.start,type:"link_open",spanIndex:u,href:f.href}),s.push({position:f.end,type:"link_close",spanIndex:u,href:f.href}));}s.sort((u,f)=>{if(u.position!==f.position)return u.position-f.position;let m=(F,L)=>F==="link_open"?0:F==="open"?1:F==="close"?2:F==="link_close"?3:4,g=u.type==="close"||u.type==="link_close",S=f.type==="close"||f.type==="link_close",w=m(u.type,g),v=m(f.type,S);return w!==v?w-v:u.type==="open"&&f.type==="open"?u.spanIndex-f.spanIndex:u.type==="close"&&f.type==="close"?f.spanIndex-u.spanIndex:u.spanIndex-f.spanIndex});let l="",p=0,c=[];for(let u of s){if(u.position>p){let f=n.text.slice(p,u.position);l+=i?i(f):f;}if(u.type==="open"||u.type==="close"){let f=o[u.style];if(f)if(u.type==="open")l+=f.open,c.push(u);else {l+=f.close,u.style==="code_block"&&u.position<n.text.length&&(l+=`
38
+ `);let m=c.findIndex(g=>g.spanIndex===u.spanIndex&&g.type==="open");m!==-1&&c.splice(m,1);}}else if(u.type==="link_open")l+="[",c.push(u);else if(u.type==="link_close"){l+="]("+u.href+")";let f=c.findIndex(m=>m.spanIndex===u.spanIndex&&m.type==="link_open");f!==-1&&c.splice(f,1);}p=u.position;}if(p<n.text.length){let u=n.text.slice(p);l+=i?i(u):u;}return l}catch(n){return console.error("Markdown render error:",n),""}}function K(t,e){return se(t,e)}k();function Un(t){let e=t.replace(/\r\n/g,`
56
39
  `).replace(/\r/g,`
57
- `);if(!t.startsWith("---"))return {frontmatter:"",content:e};let r=t.indexOf(`
58
- ---`,3);if(r===-1)return {frontmatter:"",content:e};let n=t.slice(0,r+4),o=t.slice(r+4).trimStart();return {frontmatter:n,content:o}}function Ve(e,t){try{let r=typeof e=="string"?e:"",n=Tt.parse(t??{});if(!r)return "";let{frontmatter:o,content:s}=To(r),a=Se(s,{linkify:!0,enableSpoilers:!1,autolink:!0,headingStyle:"none",blockquotePrefix:"",tableMode:"off"}),i=ke(a);return i=i.replace(/\n{3,}/g,`
40
+ `);if(!e.startsWith("---"))return {frontmatter:"",content:t};let n=e.indexOf(`
41
+ ---`,3);if(n===-1)return {frontmatter:"",content:t};let r=e.slice(0,n+4),o=e.slice(n+4).trimStart();return {frontmatter:r,content:o}}function be(t,e){try{let n=typeof t=="string"?t:"",r=Ue.parse(e??{});if(!n)return "";let{frontmatter:o,content:i}=Un(n),a=V(i,{linkify:!0,enableSpoilers:!1,autolink:!0,headingStyle:"none",blockquotePrefix:"",tableMode:"off"}),s=K(a);return s=s.replace(/\n{3,}/g,`
59
42
 
60
- `),i=i.trimEnd()+`
61
- `,n.preserveFrontmatter&&o&&(i=o+`
62
- `+i),i}catch(r){return console.error("Markdown format error:",r),e}}k();function vo(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function Ro(e){if(e!=null){if(typeof e=="string")return {value:e.trim(),kind:"scalar"};if(typeof e=="number"||typeof e=="boolean")return {value:String(e),kind:"scalar"};if(typeof e=="object")try{return {value:JSON.stringify(e),kind:"structured"}}catch{return}}}function Po(e){try{let t=_n.parse(e,{schema:"core"});if(!t||typeof t!="object"||Array.isArray(t))return null;let r={};for(let[n,o]of Object.entries(t)){let s=n.trim();if(!s)continue;let a=Ro(o);a&&(r[s]=a);}return r}catch{return null}}function Mo(e,t){let r=[],n=t+1;for(;n<e.length;){let s=e[n];if(!s){n+=1;continue}if(s.length>0&&!s.startsWith(" ")&&!s.startsWith(" "))break;r.push(s),n+=1;}return {value:r.join(`
63
- `).trim(),linesConsumed:n-t}}function Eo(e){let t={},r=e.split(`
64
- `),n=0;for(;n<r.length;){let o=r[n];if(!o){n+=1;continue}let s=o.match(/^([\w-]+):\s*(.*)$/);if(!s?.[1]||!s[2]){n+=1;continue}let a=s[1],i=s[2].trim();if(!a){n+=1;continue}if(!i&&n+1<r.length){let p=r[n+1];if(p&&(p.startsWith(" ")||p.startsWith(" "))){let{value:c,linesConsumed:d}=Mo(r,n);c&&(t[a]={value:c,kind:"multiline",rawInline:i}),n+=d;continue}}let l=vo(i);l&&(t[a]={value:l,kind:"inline",rawInline:i}),n+=1;}return t}function Co(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.value;return t}function Io(e){return /^[|>][+-]?(\d+)?[+-]?$/.test(e)}function Oo(e){let{lineEntry:t,yamlValue:r}=e;return r.kind!=="structured"||t.kind!=="inline"||Io(t.rawInline)?false:t.value.includes(":")}function Fo(e){let t=e.replace(/\r\n/g,`
43
+ `),s=s.trimEnd()+`
44
+ `,r.preserveFrontmatter&&o&&(s=o+`
45
+ `+s),s}catch(n){return console.error("Markdown format error:",n),t}}k();function Wn(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function qn(t){if(t!=null){if(typeof t=="string")return {value:t.trim(),kind:"scalar"};if(typeof t=="number"||typeof t=="boolean")return {value:String(t),kind:"scalar"};if(typeof t=="object")try{return {value:JSON.stringify(t),kind:"structured"}}catch{return}}}function Gn(t){try{let e=Tt.parse(t,{schema:"core"});if(!e||typeof e!="object"||Array.isArray(e))return null;let n={};for(let[r,o]of Object.entries(e)){let i=r.trim();if(!i)continue;let a=qn(o);a&&(n[i]=a);}return n}catch{return null}}function Yn(t,e){let n=[],r=e+1;for(;r<t.length;){let i=t[r];if(!i){r+=1;continue}if(i.length>0&&!i.startsWith(" ")&&!i.startsWith(" "))break;n.push(i),r+=1;}return {value:n.join(`
46
+ `).trim(),linesConsumed:r-e}}function Xn(t){let e={},n=t.split(`
47
+ `),r=0;for(;r<n.length;){let o=n[r];if(!o){r+=1;continue}let i=o.match(/^([\w-]+):\s*(.*)$/);if(!i?.[1]||!i[2]){r+=1;continue}let a=i[1],s=i[2].trim();if(!a){r+=1;continue}if(!s&&r+1<n.length){let p=n[r+1];if(p&&(p.startsWith(" ")||p.startsWith(" "))){let{value:c,linesConsumed:u}=Yn(n,r);c&&(e[a]={value:c,kind:"multiline",rawInline:s}),r+=u;continue}}let l=Wn(s);l&&(e[a]={value:l,kind:"inline",rawInline:s}),r+=1;}return e}function Vn(t){let e={};for(let[n,r]of Object.entries(t))e[n]=r.value;return e}function Kn(t){return /^[|>][+-]?(\d+)?[+-]?$/.test(t)}function Zn(t){let{lineEntry:e,yamlValue:n}=t;return n.kind!=="structured"||e.kind!=="inline"||Kn(e.rawInline)?false:e.value.includes(":")}function Jn(t){let e=t.replace(/\r\n/g,`
65
48
  `).replace(/\r/g,`
66
- `);if(!t.startsWith("---"))return;let r=t.indexOf(`
67
- ---`,3);if(r!==-1)return t.slice(4,r)}function Le(e){try{if(typeof e!="string")return {};let t=Fo(e);if(!t)return {};let r=Eo(t),n=Po(t);if(n===null)return Co(r);let o={};for(let[s,a]of Object.entries(n)){o[s]=a.value;let i=r[s];i&&Oo({lineEntry:i,yamlValue:a})&&(o[s]=i.value);}for(let[s,a]of Object.entries(r))s in o||(o[s]=a.value);return o}catch(t){return console.warn("Failed to parse frontmatter:",t),{}}}function Ge(e){try{let t=vt.parse(e);if(Object.keys(t).length===0)return "";let r={};for(let[o,s]of Object.entries(t))try{let a=JSON.parse(s);r[o]=a;}catch{r[o]=s;}return `---
68
- ${_n.stringify(r,{lineWidth:0,defaultStringType:"QUOTE_DOUBLE"}).trim()}
69
- ---`}catch(t){return console.warn("Failed to serialize frontmatter:",t),""}}function Je(e){try{if(typeof e!="string")return {frontmatter:{},content:""};let t=e.replace(/\r\n/g,`
49
+ `);if(!e.startsWith("---"))return;let n=e.indexOf(`
50
+ ---`,3);if(n!==-1)return e.slice(4,n)}function ie(t){try{if(typeof t!="string")return {};let e=Jn(t);if(!e)return {};let n=Xn(e),r=Gn(e);if(r===null)return Vn(n);let o={};for(let[i,a]of Object.entries(r)){o[i]=a.value;let s=n[i];s&&Zn({lineEntry:s,yamlValue:a})&&(o[i]=s.value);}for(let[i,a]of Object.entries(n))i in o||(o[i]=a.value);return o}catch(e){return console.warn("Failed to parse frontmatter:",e),{}}}function xe(t){try{let e=We.parse(t);if(Object.keys(e).length===0)return "";let n={};for(let[o,i]of Object.entries(e))try{let a=JSON.parse(i);n[o]=a;}catch{n[o]=i;}return `---
51
+ ${Tt.stringify(n,{lineWidth:0,defaultStringType:"QUOTE_DOUBLE"}).trim()}
52
+ ---`}catch(e){return console.warn("Failed to serialize frontmatter:",e),""}}function ke(t){try{if(typeof t!="string")return {frontmatter:{},content:""};let e=t.replace(/\r\n/g,`
70
53
  `).replace(/\r/g,`
71
- `);if(!t.startsWith("---"))return {frontmatter:{},content:e};let r=t.indexOf(`
72
- ---`,3);if(r===-1)return {frontmatter:{},content:e};let n=t.slice(4,r),o=t.slice(r+4).trimStart();return {frontmatter:Le(e),content:o}}catch(t){return console.warn("Failed to extract frontmatter:",t),{frontmatter:{},content:e}}}k();k();function Ke(e){try{let t=z.string().parse(e),r=[],n,o=0;for(;o<=t.length;){let s=t.indexOf(`
73
- `,o),a=s===-1?t.length:s,i=t.slice(o,a),l=i.match(/^( {0,3})(`{3,}|~{3,})(.*)$/);if(l){let p=l[1],c=l[2];if(!p||!c){o=a+1;continue}let d=c[0];if(!d){o=a+1;continue}let g=c.length;if(!n)n={start:o,markerChar:d,markerLen:g,openLine:i,marker:c,indent:p};else if(n.markerChar===d&&g>=n.markerLen){let k=a;r.push({start:n.start,end:k,openLine:n.openLine,marker:n.marker,indent:n.indent}),n=void 0;}}if(s===-1)break;o=s+1;}return n&&r.push({start:n.start,end:t.length,openLine:n.openLine,marker:n.marker,indent:n.indent}),r}catch(t){return console.warn("Invalid input for parseFenceSpans:",t),[]}}function Et(e,t){let r=0,n=e.length-1;for(;r<=n;){let o=Math.floor((r+n)/2),s=e[o];if(!s)break;if(t<=s.start){n=o-1;continue}if(t>=s.end){r=o+1;continue}return s}}function jn(e,t){return !Et(e,t)}function Ze(){return {open:false,ticks:0}}function Xe(e,t){try{let r=z.string().parse(e),n=t?Ue.parse(t):Ze(),o=Ke(r),s={open:n.open,ticks:n.ticks},{spans:a,state:i}=Bo(r,o,s);return {inlineState:i,isInside:l=>_o(l,o)||jo(l,a)}}catch(r){return console.warn("Invalid input for buildCodeSpanIndex:",r),{inlineState:Ze(),isInside:()=>false}}}function Bo(e,t,r){let n=[],o=r.open,s=r.ticks,a=o?0:-1,i=0;for(;i<e.length;){let l=$o(t,i);if(l){i=l.end;continue}if(e[i]!=="`"){i+=1;continue}let p=i,c=0;for(;i<e.length&&e[i]==="`";)c+=1,i+=1;if(!o){o=true,s=c,a=p;continue}c===s&&(n.push([a,i]),o=false,s=0,a=-1);}return o&&n.push([a,e.length]),{spans:n,state:{open:o,ticks:s}}}function $o(e,t){return e.find(r=>t>=r.start&&t<r.end)}function _o(e,t){return t.some(r=>e>=r.start&&e<r.end)}function jo(e,t){return t.some(([r,n])=>e>=r&&e<n)}k();var zo={bold:{open:"**",close:"**"},italic:{open:"_",close:"_"},strikethrough:{open:"~~",close:"~~"},code:{open:"`",close:"`"},code_block:{open:"```\n",close:"```"},spoiler:{open:"||",close:"||"},blockquote:{open:"> ",close:""}};function Qe(e,t){try{let r=z.string().parse(e),n=Oe.parse(t);if(!r||n==="off")return r;let{ir:o,hasTables:s}=Fe(r,{linkify:!1,enableSpoilers:!1,autolink:!1,headingStyle:"none",blockquotePrefix:"",tableMode:n});return s?Ae(o,{styleMarkers:zo,escapeText:a=>a,buildLink:(a,i)=>{let l=a.href.trim();return !l||!i.slice(a.start,a.end)?null:{start:a.start,end:a.end,open:"[",close:`](${l})`}}}):r}catch(r){return console.warn("Invalid input for convertMarkdownTables:",r),typeof e=="string"?e:""}}var Ct;(p=>{function e(c,d){try{return Se(c,d)}catch(g){return console.warn("Markdown.parse error:",g),{text:"",styles:[],links:[]}}}p.parse=e;function t(c,d){try{return ke(c,d)}catch(g){return console.warn("Markdown.render error:",g),""}}p.render=t;function r(c,d){try{return Ve(c,d)}catch(g){return console.warn("Markdown.format error:",g),typeof c=="string"?c:""}}p.format=r;function n(c){try{return Le(c)}catch(d){return console.warn("Markdown.parseFrontmatter error:",d),{}}}p.parseFrontmatter=n;function o(c){try{return Ge(c)}catch(d){return console.warn("Markdown.serializeFrontmatter error:",d),""}}p.serializeFrontmatter=o;function s(c){try{return Je(c)}catch(d){return console.warn("Markdown.extractFrontmatter error:",d),{frontmatter:{},content:typeof c=="string"?c:""}}}p.extractFrontmatter=s;function a(c,d,g){try{return ye(c,d,g)}catch(k){return console.warn("Markdown.chunk error:",k),typeof c=="string"&&c.length>0?[c]:[]}}p.chunk=a;function i(c,d){try{return Xe(c,d)}catch(g){return console.warn("Markdown.buildCodeIndex error:",g),{inlineState:{open:false,ticks:0},isInside:()=>false}}}p.buildCodeIndex=i;function l(c,d){try{return Qe(c,d)}catch(g){return console.warn("Markdown.convertTables error:",g),typeof c=="string"?c:""}}p.convertTables=l;})(Ct||(Ct={}));k();function Nn(e){if(!e)return "";let r=e.replace(/[/\\]+$/,"").split(/[/\\]/);return r[r.length-1]??""}function Do(e){if(!e)return "";let r=e.replace(/[/\\]+$/,"").split(/[/\\]/);return r.slice(0,r.length-1).join("/")+"/"}function Ho(e){if(!e)return "";let t=e.split(".");return t[t.length-1]}function Wo(e,t=20){let r=Nn(e);if(r.length<=t)return r;let n=r.lastIndexOf("."),o=n<=0?"":r.slice(n),s=t-o.length-1;return s<=0?r.slice(0,t-1)+"\u2026":r.slice(0,s)+"\u2026"+o}function Uo(e,t=20){if(e.length<=t)return e;let r=t-1,n=Math.ceil(r/2),o=Math.floor(r/2);return e.slice(0,n)+"\u2026"+e.slice(-o)}k();var qo=["load failed","network connection was lost","network request failed","failed to fetch","econnreset","econnrefused","etimedout","socket hang up"];function Yo(e){if(!e)return false;let t=String(e instanceof Error?e.message:e).toLowerCase();return qo.some(r=>t.includes(r))}async function It(e,t={}){let{attempts:r=3,delay:n=500,factor:o=2,maxDelay:s=1e4,retryIf:a=Yo}=t,i;for(let l=0;l<r;l++)try{return await e()}catch(p){if(i=p,l===r-1||!a(p))throw p;let c=Math.min(n*o**l,s);await new Promise(d=>setTimeout(d,c));}throw i}k();var Ot;(Ht=>{let e=m.create({service:"fetch"}),t=["HTTP_PROXY","HTTPS_PROXY","http_proxy","https_proxy"],r=false,n=null;function o(){return t.some(F=>{let I=process.env[F];return typeof I=="string"&&I.trim().length>0})}Ht.hasProxyConfigured=o;function s(){let F=process.env.http_proxy||process.env.HTTP_PROXY;return process.env.https_proxy||process.env.HTTPS_PROXY||F}Ht.getProxyUrl=s;function a(F={}){let I=F.httpProxy||F.httpsProxy||s();if(!I){e.warn("[Fetch] No proxy configured, HTTP_PROXY/HTTPS_PROXY environment variables not set");return}let B=new ProxyAgent({uri:I,connectTimeout:F.connectTimeout||1e4,keepAliveTimeout:F.keepAliveTimeout||3e4});n=getGlobalDispatcher(),setGlobalDispatcher(B),r=true,e.info(`[Fetch] Global proxy enabled: ${I}`);}Ht.enableProxy=a;function i(){!r||!n||(setGlobalDispatcher(n),r=false,n=null,e.info("[Fetch] \u5168\u5C40\u4EE3\u7406\u5DF2\u7981\u7528"));}Ht.disableProxy=i;function l(){return r}Ht.isProxyEnabled=l;async function p(F,I){let B=I?.timeout||3e4,U=I?.responseType||"json",{timeout:G,responseType:Re,...j}=I||{},S=null,m=null;try{j.signal||(S=new AbortController,m=setTimeout(()=>S.abort(),B));let f=await fetch(F,{...j,signal:j.signal||S.signal});m&&clearTimeout(m);let u;switch(U){case "arrayBuffer":u=await f.arrayBuffer();break;case "blob":u=await f.blob();break;case "buffer":{let y=await f.arrayBuffer();u=Buffer.from(y);break}case "text":u=await f.text();break;default:{let y=await f.text();try{u=JSON.parse(y);}catch{u=y;}break}}return {ok:f.ok,status:f.status,statusText:f.statusText,headers:f.headers,data:u,url:f.url}}catch(f){throw m&&clearTimeout(m),f}}async function c$1(F,I){let B=I?.retries??0,U=I?.retryDelay??1e3,{retries:G,retryDelay:Re,responseType:j,...S}=I||{};return It(()=>p(F,{...S,responseType:I?.responseType}),{attempts:B+1,delay:U,maxDelay:U*2**(B+1)})}async function d(F,I){return c$1(F,{method:"GET",...I})}Ht.get=d;async function g(F,I,B){return c$1(F,{method:"POST",headers:{"Content-Type":"application/json",...B?.headers},body:I?JSON.stringify(I):void 0,...B})}Ht.post=g;async function k(F,I,B){return c$1(F,{method:"PUT",headers:{"Content-Type":"application/json",...B?.headers},body:I?JSON.stringify(I):void 0,...B})}Ht.put=k;async function C(F,I,B){return c$1(F,{method:"DELETE",headers:{"Content-Type":"application/json",...B?.headers},body:I?JSON.stringify(I):void 0,...B})}Ht.del=C;async function W(F,I,B){return c$1(F,{method:"PATCH",headers:{"Content-Type":"application/json",...B?.headers},body:I?JSON.stringify(I):void 0,...B})}Ht.patch=W;async function q(F,I){return c$1(F,I)}Ht.request=q;function Y(F={}){return o()?(a(F),true):false}Ht.autoProxy=Y;let V=5*1024*1024;function J(F){return new TextEncoder().encode(F)}function fe(F){return c.mimeType(F)}function ie(F){return F.startsWith("file://")}async function pe(F){let I=fileURLToPath(F);return await _.file(I).bytes()}async function Te(F,I,B){let U=`----FetchFormBoundary${Date.now()}`,G=[],j=I.some(h=>h.filename||h.value instanceof Uint8Array||Buffer.isBuffer(h.value))&&!B?.timeout?3e5:B?.timeout;for(let h of I){let w=h.maxSize??V,R=h.filename,v=`Content-Disposition: form-data; name="${h.name}"${R?`; filename="${R}"`:""}`;R&&(v+=`\r
74
- Content-Type: ${fe(R)}`),v+=`\r
54
+ `);if(!e.startsWith("---"))return {frontmatter:{},content:t};let n=e.indexOf(`
55
+ ---`,3);if(n===-1)return {frontmatter:{},content:t};let r=e.slice(4,n),o=e.slice(n+4).trimStart();return {frontmatter:ie(t),content:o}}catch(e){return console.warn("Failed to extract frontmatter:",e),{frontmatter:{},content:t}}}k();k();function Se(t){try{let e=z.string().parse(t),n=[],r,o=0;for(;o<=e.length;){let i=e.indexOf(`
56
+ `,o),a=i===-1?e.length:i,s=e.slice(o,a),l=s.match(/^( {0,3})(`{3,}|~{3,})(.*)$/);if(l){let p=l[1],c=l[2];if(!p||!c){o=a+1;continue}let u=c[0];if(!u){o=a+1;continue}let f=c.length;if(!r)r={start:o,markerChar:u,markerLen:f,openLine:s,marker:c,indent:p};else if(r.markerChar===u&&f>=r.markerLen){let m=a;n.push({start:r.start,end:m,openLine:r.openLine,marker:r.marker,indent:r.indent}),r=void 0;}}if(i===-1)break;o=i+1;}return r&&n.push({start:r.start,end:e.length,openLine:r.openLine,marker:r.marker,indent:r.indent}),n}catch(e){return console.warn("Invalid input for parseFenceSpans:",e),[]}}function Xe(t,e){let n=0,r=t.length-1;for(;n<=r;){let o=Math.floor((n+r)/2),i=t[o];if(!i)break;if(e<=i.start){r=o-1;continue}if(e>=i.end){n=o+1;continue}return i}}function Mt(t,e){return !Xe(t,e)}function we(){return {open:false,ticks:0}}function Te(t,e){try{let n=z.string().parse(t),r=e?he.parse(e):we(),o=Se(n),i={open:r.open,ticks:r.ticks},{spans:a,state:s}=tr(n,o,i);return {inlineState:s,isInside:l=>rr(l,o)||or(l,a)}}catch(n){return console.warn("Invalid input for buildCodeSpanIndex:",n),{inlineState:we(),isInside:()=>false}}}function tr(t,e,n){let r=[],o=n.open,i=n.ticks,a=o?0:-1,s=0;for(;s<t.length;){let l=nr(e,s);if(l){s=l.end;continue}if(t[s]!=="`"){s+=1;continue}let p=s,c=0;for(;s<t.length&&t[s]==="`";)c+=1,s+=1;if(!o){o=true,i=c,a=p;continue}c===i&&(r.push([a,s]),o=false,i=0,a=-1);}return o&&r.push([a,t.length]),{spans:r,state:{open:o,ticks:i}}}function nr(t,e){return t.find(n=>e>=n.start&&e<n.end)}function rr(t,e){return e.some(n=>t>=n.start&&t<n.end)}function or(t,e){return e.some(([n,r])=>t>=n&&t<r)}k();var ir={bold:{open:"**",close:"**"},italic:{open:"_",close:"_"},strikethrough:{open:"~~",close:"~~"},code:{open:"`",close:"`"},code_block:{open:"```\n",close:"```"},spoiler:{open:"||",close:"||"},blockquote:{open:"> ",close:""}};function Me(t,e){try{let n=z.string().parse(t),r=re.parse(e);if(!n||r==="off")return n;let{ir:o,hasTables:i}=oe(n,{linkify:!1,enableSpoilers:!1,autolink:!1,headingStyle:"none",blockquotePrefix:"",tableMode:r});return i?se(o,{styleMarkers:ir,escapeText:a=>a,buildLink:(a,s)=>{let l=a.href.trim();return !l||!s.slice(a.start,a.end)?null:{start:a.start,end:a.end,open:"[",close:`](${l})`}}}):n}catch(n){return console.warn("Invalid input for convertMarkdownTables:",n),typeof t=="string"?t:""}}var Ve;(p=>{function t(c,u){try{return V(c,u)}catch(f){return console.warn("Markdown.parse error:",f),{text:"",styles:[],links:[]}}}p.parse=t;function e(c,u){try{return K(c,u)}catch(f){return console.warn("Markdown.render error:",f),""}}p.render=e;function n(c,u){try{return be(c,u)}catch(f){return console.warn("Markdown.format error:",f),typeof c=="string"?c:""}}p.format=n;function r(c){try{return ie(c)}catch(u){return console.warn("Markdown.parseFrontmatter error:",u),{}}}p.parseFrontmatter=r;function o(c){try{return xe(c)}catch(u){return console.warn("Markdown.serializeFrontmatter error:",u),""}}p.serializeFrontmatter=o;function i(c){try{return ke(c)}catch(u){return console.warn("Markdown.extractFrontmatter error:",u),{frontmatter:{},content:typeof c=="string"?c:""}}}p.extractFrontmatter=i;function a(c,u,f){try{return G(c,u,f)}catch(m){return console.warn("Markdown.chunk error:",m),typeof c=="string"&&c.length>0?[c]:[]}}p.chunk=a;function s(c,u){try{return Te(c,u)}catch(f){return console.warn("Markdown.buildCodeIndex error:",f),{inlineState:{open:false,ticks:0},isInside:()=>false}}}p.buildCodeIndex=s;function l(c,u){try{return Me(c,u)}catch(f){return console.warn("Markdown.convertTables error:",f),typeof c=="string"?c:""}}p.convertTables=l;})(Ve||(Ve={}));k();function Rt(t){if(!t)return "";let n=t.replace(/[/\\]+$/,"").split(/[/\\]/);return n[n.length-1]??""}function ar(t){if(!t)return "";let n=t.replace(/[/\\]+$/,"").split(/[/\\]/);return n.slice(0,n.length-1).join("/")+"/"}function lr(t){if(!t)return "";let e=t.split(".");return e[e.length-1]}function cr(t,e=20){let n=Rt(t);if(n.length<=e)return n;let r=n.lastIndexOf("."),o=r<=0?"":n.slice(r),i=e-o.length-1;return i<=0?n.slice(0,e-1)+"\u2026":n.slice(0,i)+"\u2026"+o}function ur(t,e=20){if(t.length<=e)return t;let n=e-1,r=Math.ceil(n/2),o=Math.floor(n/2);return t.slice(0,r)+"\u2026"+t.slice(-o)}k();var pr=["load failed","network connection was lost","network request failed","failed to fetch","econnreset","econnrefused","etimedout","socket hang up"];function fr(t){if(!t)return false;let e=String(t instanceof Error?t.message:t).toLowerCase();return pr.some(n=>e.includes(n))}async function Ke(t,e={}){let{attempts:n=3,delay:r=500,factor:o=2,maxDelay:i=1e4,retryIf:a=fr}=e,s;for(let l=0;l<n;l++)try{return await t()}catch(p){if(s=p,l===n-1||!a(p))throw p;let c=Math.min(r*o**l,i);await new Promise(u=>setTimeout(u,c));}throw s}k();var Ze;(Or=>{let t=m.create({service:"fetch"}),e=["HTTP_PROXY","HTTPS_PROXY","http_proxy","https_proxy"],n=false,r=null;function o(){return e.some(k=>{let x=process.env[k];return typeof x=="string"&&x.trim().length>0})}Or.hasProxyConfigured=o;function i(){let k=process.env.http_proxy||process.env.HTTP_PROXY;return process.env.https_proxy||process.env.HTTPS_PROXY||k}Or.getProxyUrl=i;function a(k={}){let x=k.httpProxy||k.httpsProxy||i();if(!x){t.warn("[Fetch] No proxy configured, HTTP_PROXY/HTTPS_PROXY environment variables not set");return}let T=new ProxyAgent({uri:x,connectTimeout:k.connectTimeout||1e4,keepAliveTimeout:k.keepAliveTimeout||3e4});r=getGlobalDispatcher(),setGlobalDispatcher(T),n=true,t.info(`[Fetch] Global proxy enabled: ${x}`);}Or.enableProxy=a;function s(){!n||!r||(setGlobalDispatcher(r),n=false,r=null,t.info("[Fetch] \u5168\u5C40\u4EE3\u7406\u5DF2\u7981\u7528"));}Or.disableProxy=s;function l(){return n}Or.isProxyEnabled=l;async function p(k,x){let T=x?.timeout||3e4,C=x?.responseType||"json",{timeout:_,responseType:ve,...E}=x||{},A=null,D=null;try{E.signal||(A=new AbortController,D=setTimeout(()=>A.abort(),T));let R=await fetch(k,{...E,signal:E.signal||A.signal});D&&clearTimeout(D);let O;switch(C){case "arrayBuffer":O=await R.arrayBuffer();break;case "blob":O=await R.blob();break;case "buffer":{let B=await R.arrayBuffer();O=Buffer.from(B);break}case "text":O=await R.text();break;default:{let B=await R.text();try{O=JSON.parse(B);}catch{O=B;}break}}return {ok:R.ok,status:R.status,statusText:R.statusText,headers:R.headers,data:O,url:R.url}}catch(R){throw D&&clearTimeout(D),R}}async function c(k,x){let T=x?.retries??0,C=x?.retryDelay??1e3,{retries:_,retryDelay:ve,responseType:E,...A}=x||{};return Ke(()=>p(k,{...A,responseType:x?.responseType}),{attempts:T+1,delay:C,maxDelay:C*2**(T+1)})}async function u(k,x){return c(k,{method:"GET",...x})}Or.get=u;async function f(k,x,T){return c(k,{method:"POST",headers:{"Content-Type":"application/json",...T?.headers},body:x?JSON.stringify(x):void 0,...T})}Or.post=f;async function m$1(k,x,T){return c(k,{method:"PUT",headers:{"Content-Type":"application/json",...T?.headers},body:x?JSON.stringify(x):void 0,...T})}Or.put=m$1;async function g(k,x,T){return c(k,{method:"DELETE",headers:{"Content-Type":"application/json",...T?.headers},body:x?JSON.stringify(x):void 0,...T})}Or.del=g;async function S(k,x,T){return c(k,{method:"PATCH",headers:{"Content-Type":"application/json",...T?.headers},body:x?JSON.stringify(x):void 0,...T})}Or.patch=S;async function w(k,x){return c(k,x)}Or.request=w;function v(k={}){return o()?(a(k),true):false}Or.autoProxy=v;let F=5*1024*1024;function L(k){return new TextEncoder().encode(k)}function ae(k){return d.mimeType(k)}function W(k){return k.startsWith("file://")}async function le(k){let x=fileURLToPath(k);return await D.file(x).bytes()}async function Re(k,x,T){let C=`----FetchFormBoundary${Date.now()}`,_=[],E=x.some(M=>M.filename||M.value instanceof Uint8Array||Buffer.isBuffer(M.value))&&!T?.timeout?3e5:T?.timeout;for(let M of x){let $=M.maxSize??F,z=M.filename,q=`Content-Disposition: form-data; name="${M.name}"${z?`; filename="${z}"`:""}`;z&&(q+=`\r
57
+ Content-Type: ${ae(z)}`),q+=`\r
75
58
  \r
76
- `,G.push(J(v));let T=h.value;if(typeof T=="string")if(ie(T)){let O=await pe(T);if(R||(R=T.split("/").pop()||"file"),O.byteLength>w)throw new Error(`File size ${O.byteLength} exceeds limit ${w} bytes: ${R}`);G.push(O);}else G.push(J(T));else if(Buffer.isBuffer(T)){if(T.byteLength>w)throw new Error(`Buffer size ${T.byteLength} exceeds limit ${w} bytes: ${h.name}`);G.push(new Uint8Array(T.buffer,T.byteOffset,T.byteLength));}else if(T instanceof Uint8Array){if(T.byteLength>w)throw new Error(`File size ${T.byteLength} exceeds limit ${w} bytes: ${h.name}`);G.push(T);}}let S=J(`\r
77
- --${U}--`),m=J(`\r
78
- --${U}\r
79
- `),f=[];f.push(J(`--${U}\r
80
- `));for(let h=0;h<G.length;h++)f.push(G[h]),h%2===1&&h<G.length-1&&(f.push(m),f.push(J(`--${U}\r
81
- `)));f.push(S);let u=f.reduce((h,w)=>h+w.length,0),y=new Uint8Array(u),x=0;for(let h of f)y.set(h,x),x+=h.length;return c$1(F,{method:"POST",headers:{"Content-Type":`multipart/form-data; boundary=${U}`,...B?.headers},body:y,timeout:j,...B})}Ht.postForm=Te;function ve(F,I,B){let U=new AbortController,G=U.signal;return (async()=>{try{let j={Accept:"text/event-stream",...B?.headers||{}},S=await fetch(F,{...B,headers:j,signal:G});if(!S.ok)throw new Error(`SSE connection failed: ${S.status}`);let m=S.body?.getReader();if(!m)throw new Error("SSE stream not available");let f=new TextDecoder("utf-8"),u="";for(;!G.aborted;){let{done:y,value:x}=await m.read();if(y)break;let h=f.decode(x,{stream:!0});u+=h;let w=u.split(`
82
- `);u=w.pop()??"";for(let R of w)if(R.startsWith("data: ")){let v=R.slice(6);if(v==="[DONE]"){I.onComplete?.();return}I.onMessage?.(v);}}I.onComplete?.();}catch(j){j.name!=="AbortError"&&I.onError?.(j);}})(),()=>{U.abort();}}Ht.sse=ve;})(Ot||(Ot={}));k();var Ft;(n=>{let e=["brave","calm","clever","cosmic","crisp","curious","eager","gentle","glowing","happy","hidden","jolly","kind","lucky","mighty","misty","neon","nimble","playful","proud","quick","quiet","shiny","silent","stellar","sunny","swift","tidy","witty"],t=["cabin","cactus","canyon","circuit","comet","eagle","engine","falcon","forest","garden","harbor","island","knight","lagoon","meadow","moon","mountain","nebula","orchid","otter","panda","pixel","planet","river","rocket","sailor","squid","star","tiger","wizard","wolf"];function r(){return [e[Math.floor(Math.random()*e.length)],t[Math.floor(Math.random()*t.length)]].join("-")}n.create=r;})(Ft||(Ft={}));k();function Dn(e){let t=new AbortController,r=setTimeout(t.abort.bind(t),e);return {controller:t,signal:t.signal,clearTimeout:()=>globalThis.clearTimeout(r)}}function Ko(e,...t){let r=Dn(e);return {signal:AbortSignal.any([r.signal,...t]),clearTimeout:r.clearTimeout}}k();var At;(t=>{async function e(r,n){if(process.platform==="win32"){let o=be.resolve(r),s=be.resolve(n),a=`Expand-Archive -Path '${o}' -DestinationPath '${s}' -Force`,i=await ne.run("powershell",`-NoProfile -NonInteractive -Command "$global:ProgressPreference = 'SilentlyContinue'; ${a}"`);if(i.code!==0)throw new Error(`PowerShell exited with code ${i.code}: ${i.stderr}`)}else {let o=`unzip -o -q ${r} -d ${n}`,s=await ne.run(void 0,o);if(s.code!==0)throw new Error(`unzip exited with code ${s.code}: ${s.stderr}`)}}t.extractZip=e;})(At||(At={}));k();var Lt;(n=>{function e(o){return o?/^#[0-9a-fA-F]{6}$/.test(o):false}n.isValidHex=e;function t(o){let s=parseInt(o.slice(1,3),16),a=parseInt(o.slice(3,5),16),i=parseInt(o.slice(5,7),16);return {r:s,g:a,b:i}}n.hexToRgb=t;function r(o){if(!e(o))return;let{r:s,g:a,b:i}=t(o);return `\x1B[38;2;${s};${a};${i}m\x1B[1m`}n.hexToAnsiBold=r;})(Lt||(Lt={}));k();var Bt;(r=>{class e extends Error{constructor(s){super(`No context found for ${s}`);c$1(this,"name",s);}}r.NotFound=e;function t(n){let o=new AsyncLocalStorage;return {use(){let s=o.getStore();if(!s)throw new e(n);return s},provide(s,a){return o.run(s,a)}}}r.create=t;})(Bt||(Bt={}));k();function Xo(e){return {[Symbol.dispose](){e();},[Symbol.asyncDispose](){return Promise.resolve(e())}}}k();var $t;(t=>{async function e(){return new Promise(r=>{let n=()=>{process._getActiveHandles().length===0&&process._getActiveRequests().length===0?r():setImmediate(n);};n();})}t.wait=e;})($t||($t={}));k();function Qo(e){if(e<=0)return "";if(e<60)return `${e}s`;if(e<3600){let r=Math.floor(e/60),n=e%60;return n>0?`${r}m ${n}s`:`${r}m`}if(e<86400){let r=Math.floor(e/3600),n=Math.floor(e%3600/60);return n>0?`${r}h ${n}m`:`${r}h`}if(e<604800){let r=Math.floor(e/86400);return r===1?"~1 day":`~${r} days`}let t=Math.floor(e/604800);return t===1?"~1 week":`~${t} weeks`}k();var _t;(a=>{function e(i,l){if(i===l)return true;if(typeof i!="object"||typeof l!="object"||i===null||l===null)return false;let p=Object.keys(i),c=Object.keys(l);if(p.length!==c.length)return false;for(let d of p)if(!c.includes(d)||!e(i[d],l[d]))return false;return true}function t(i){return {...i,super:i.super??false}}function r(i,l){return i?e(t(i),t(l)):false}a.match=r;function n(i,l=false){return {name:i.name,ctrl:i.ctrl,meta:i.meta,shift:i.shift,super:i.super??false,leader:l}}a.fromParsedKey=n;function o(i){if(!i)return "";let l=[];i.ctrl&&l.push("ctrl"),i.meta&&l.push("alt"),i.super&&l.push("super"),i.shift&&l.push("shift"),i.name&&(i.name==="delete"?l.push("del"):l.push(i.name));let p=l.join("+");return i.leader&&(p=p?`<leader> ${p}`:"<leader>"),p}a.keyToString=o;function s(i){return i==="none"?[]:i.split(",").map(l=>{let c=l.replace(/<leader>/g,"leader+").toLowerCase().split("+"),d={ctrl:false,meta:false,shift:false,super:false,leader:false,name:""};for(let g of c)switch(g){case "ctrl":d.ctrl=true;break;case "alt":case "meta":case "option":d.meta=true;break;case "super":d.super=true;break;case "shift":d.shift=true;break;case "leader":d.leader=true;break;case "esc":d.name="escape";break;default:d.name=g;break}return d})}a.parse=s;})(_t||(_t={}));k();var jt;(p=>{function e(c){return c.replace(/\b\w/g,d=>d.toUpperCase())}p.titlecase=e;function t(c){return new Date(c).toLocaleTimeString(void 0,{timeStyle:"short"})}p.time=t;function r(c){let d=new Date(c),g=t(c),k=d.toLocaleDateString();return `${g} \xB7 ${k}`}p.datetime=r;function n(c){let d=new Date(c),g=new Date;return d.getFullYear()===g.getFullYear()&&d.getMonth()===g.getMonth()&&d.getDate()===g.getDate()?t(c):r(c)}p.todayTimeOrDateTime=n;function o(c){return c>=1e6?(c/1e6).toFixed(1)+"M":c>=1e3?(c/1e3).toFixed(1)+"K":c.toString()}p.number=o;function s(c){if(c<1e3)return `${c}ms`;if(c<6e4)return `${(c/1e3).toFixed(1)}s`;if(c<36e5){let k=Math.floor(c/6e4),C=Math.floor(c%6e4/1e3);return `${k}m ${C}s`}if(c<864e5){let k=Math.floor(c/36e5),C=Math.floor(c%36e5/6e4);return `${k}h ${C}m`}let d=Math.floor(c/36e5);return `${Math.floor(c%36e5/864e5)}d ${d}h`}p.duration=s;function a(c,d){return c.length<=d?c:c.slice(0,d-1)+"\u2026"}p.truncate=a;function i(c,d=35){if(c.length<=d)return c;let g="\u2026",k=Math.ceil((d-g.length)/2),C=Math.floor((d-g.length)/2);return c.slice(0,k)+g+c.slice(-C)}p.truncateMiddle=i;function l(c,d,g){return (c===1?d:g).replace("{}",c.toString())}p.pluralize=l;})(jt||(jt={}));k();var es=["HTTP_PROXY","HTTPS_PROXY","http_proxy","https_proxy"];function ts(){return es.some(e=>process.env[e])}function ns(){return process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy}function rs(){let e=process.env.HTTP_PROXY||process.env.http_proxy,t=process.env.HTTPS_PROXY||process.env.https_proxy;return {http:e,https:t,enabled:!!(e||t)}}k();var Nt=class{constructor(){c$1(this,"queue",[]);c$1(this,"resolvers",[]);}push(t){let r=this.resolvers.shift();r?r(t):this.queue.push(t);}async next(){return this.queue.length>0?this.queue.shift():new Promise(t=>this.resolvers.push(t))}async*[Symbol.asyncIterator](){for(;;)yield await this.next();}};async function os(e,t,r){let n=[...t];await Promise.all(Array.from({length:e},async()=>{for(;;){let o=n.pop();if(o===void 0)return;await r(o);}}));}k();function ss(){let e,t=new Promise(r=>e=r);return {trigger(){return e()},wait(){return t}}}k();function is(e,t){let r;return Promise.race([e.then(n=>(clearTimeout(r),n)),new Promise((n,o)=>{r=setTimeout(()=>{o(new Error(`Operation timed out after ${t}ms`));},t);})])}k();var zt;(a=>{let r=/[\u4e00-\u9fff\u3400-\u4dbf]/g;function n(i){if(!i)return 0;let l=String(i),p=(l.match(r)||[]).length,c=l.length-p,d=Math.round(p/1.5),g=Math.round(c/4);return Math.max(0,d+g)}a.estimate=n;function o(i){if(i==null)return 0;try{let l=typeof i=="string"?i:JSON.stringify(i);return n(l)}catch{return 0}}a.estimateObject=o;function s(i){if(i.total!==void 0&&i.total>0)return i.total;let l=i.input??0,p=i.output??0,c=i.cache?.read??0,d=i.cache?.write??0;return l+p+c+d}a.total=s;})(zt||(zt={}));k();function ls(e){let t={};for(let[r,n]of Object.entries(e.required().shape))t[r]=n.nullable();return De.object(t)}k();var Dt;(s=>{function e(a,i){let l=i.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return l.endsWith(" .*")&&(l=l.slice(0,-3)+"( .*)?"),new RegExp("^"+l+"$","s").test(a)}s.match=e;function t(a){return a.sort((i,l)=>{let p=i[0].length-l[0].length;return p!==0?p:i[0].localeCompare(l[0])})}function r(a,i){let l=Object.entries(i),p=t(l),c;for(let[d,g]of p)e(a,d)&&(c=g);return c}s.all=r;function n(a,i){let l=Object.entries(i),p=t(l),c;for(let[d,g]of p){let k=d.split(/\s+/);e(a.head,k[0])&&(k.length===1||o(a.tail,k.slice(1)))&&(c=g);}return c}s.allStructured=n;function o(a,i){if(i.length===0)return true;if(a.length<i.length)return false;for(let l=0;l<i.length;l++)if(!e(a[l],i[l]))return false;return true}})(Dt||(Dt={}));export{$r as $,At as Archive,Nt as AsyncQueue,ot as Binary,Lt as Color,Bt as Context,st as Encode,$t as EventLoop,Ot as Fetch,yt as Fn,ae as Identifier,ht as Ignore,_t as Keybind,me as Lazy,jt as Locale,Ct as Markdown,gt as NamedError,_ as PKG,Pe as PkgShell,at as SessionTitle,ne as Shell,Ft as Slug,zt as Token,it as TruncateContent,Dt as Wildcard,Dn as abortAfter,Ko as abortAfterAny,Xe as buildCodeSpanIndex,$n as chunkMarkdownIR,ye as chunkText,wt as chunkTextByBreakResolver,Qe as convertMarkdownTables,Ze as createInlineCodeState,ue as createPkgShell,ct as createRESTServer,lt as createRPCServer,le as createServer,dt as createStreamingServer,ut as createWebSocketServer,Xo as defer,pn as detectPlatform,mt as escapeCommandArg,fn as escapeCommandArgSafe,Je as extractFrontmatter,Et as findFenceSpanAt,sr as findLast,jr as fn,Qo as formatDuration,Ve as formatMarkdown,Do as getDirectory,Ho as getFileExtension,Nn as getFilename,Wo as getFilenameTruncated,rs as getProxyConfig,ns as getProxyUrl,Wr as git,Kr as iife,jn as isSafeFenceBreak,ge as joinCommandArgs,_e as lazy,lr as lazyAsync,Hr as loadEnv,Gr as loadTextFile,Jr as loadTextFileAsync,Se as markdownToIR,Fe as markdownToIRWithMeta,un as needsShellExecution,oe as parseCommand,dn as parseCommandWithOptions,Ke as parseFenceSpans,Le as parseFrontmatterBlock,Zr as parseModelId,ts as proxied,Ar as readableStreamToText,ke as renderMarkdown,Ae as renderMarkdownWithMarkers,It as retry,xt as scanParenAwareBreakpoints,Ge as serializeFrontmatter,gn as shell,ss as signal,fr as startServer,Uo as truncateMiddle,ls as updateSchema,Lr as whichSync,is as withTimeout,os as work};
59
+ `,_.push(L(q));let I=M.value;if(typeof I=="string")if(W(I)){let Ie=await le(I);if(z||(z=I.split("/").pop()||"file"),Ie.byteLength>$)throw new Error(`File size ${Ie.byteLength} exceeds limit ${$} bytes: ${z}`);_.push(Ie);}else _.push(L(I));else if(Buffer.isBuffer(I)){if(I.byteLength>$)throw new Error(`Buffer size ${I.byteLength} exceeds limit ${$} bytes: ${M.name}`);_.push(new Uint8Array(I.buffer,I.byteOffset,I.byteLength));}else if(I instanceof Uint8Array){if(I.byteLength>$)throw new Error(`File size ${I.byteLength} exceeds limit ${$} bytes: ${M.name}`);_.push(I);}}let A=L(`\r
60
+ --${C}--`),D=L(`\r
61
+ --${C}\r
62
+ `),R=[];R.push(L(`--${C}\r
63
+ `));for(let M=0;M<_.length;M++)R.push(_[M]),M%2===1&&M<_.length-1&&(R.push(D),R.push(L(`--${C}\r
64
+ `)));R.push(A);let O=R.reduce((M,$)=>M+$.length,0),B=new Uint8Array(O),ce=0;for(let M of R)B.set(M,ce),ce+=M.length;return c(k,{method:"POST",headers:{"Content-Type":`multipart/form-data; boundary=${C}`,...T?.headers},body:B,timeout:E,...T})}Or.postForm=Re;function Ft(k,x,T){let C=new AbortController,_=C.signal;return (async()=>{try{let E={Accept:"text/event-stream",...T?.headers||{}},A=await fetch(k,{...T,headers:E,signal:_});if(!A.ok)throw new Error(`SSE connection failed: ${A.status}`);let D=A.body?.getReader();if(!D)throw new Error("SSE stream not available");let R=new TextDecoder("utf-8"),O="";for(;!_.aborted;){let{done:B,value:ce}=await D.read();if(B)break;let M=R.decode(ce,{stream:!0});O+=M;let $=O.split(`
65
+ `);O=$.pop()??"";for(let z of $)if(z.startsWith("data: ")){let q=z.slice(6);if(q==="[DONE]"){x.onComplete?.();return}x.onMessage?.(q);}}x.onComplete?.();}catch(E){E.name!=="AbortError"&&x.onError?.(E);}})(),()=>{C.abort();}}Or.sse=Ft;})(Ze||(Ze={}));k();var Je;(r=>{let t=["brave","calm","clever","cosmic","crisp","curious","eager","gentle","glowing","happy","hidden","jolly","kind","lucky","mighty","misty","neon","nimble","playful","proud","quick","quiet","shiny","silent","stellar","sunny","swift","tidy","witty"],e=["cabin","cactus","canyon","circuit","comet","eagle","engine","falcon","forest","garden","harbor","island","knight","lagoon","meadow","moon","mountain","nebula","orchid","otter","panda","pixel","planet","river","rocket","sailor","squid","star","tiger","wizard","wolf"];function n(){return [t[Math.floor(Math.random()*t.length)],e[Math.floor(Math.random()*e.length)]].join("-")}r.create=n;})(Je||(Je={}));k();function It(t){let e=new AbortController,n=setTimeout(e.abort.bind(e),t);return {controller:e,signal:e.signal,clearTimeout:()=>globalThis.clearTimeout(n)}}function gr(t,...e){let n=It(t);return {signal:AbortSignal.any([n.signal,...e]),clearTimeout:n.clearTimeout}}k();var Qe;(e=>{async function t(n,r){if(process.platform==="win32"){let o=ze.resolve(n),i=ze.resolve(r),a=`Expand-Archive -Path '${o}' -DestinationPath '${i}' -Force`,s=await G$1.run("powershell",`-NoProfile -NonInteractive -Command "$global:ProgressPreference = 'SilentlyContinue'; ${a}"`);if(s.code!==0)throw new Error(`PowerShell exited with code ${s.code}: ${s.stderr}`)}else {let o=`unzip -o -q ${n} -d ${r}`,i=await G$1.run(void 0,o);if(i.code!==0)throw new Error(`unzip exited with code ${i.code}: ${i.stderr}`)}}e.extractZip=t;})(Qe||(Qe={}));k();var et;(r=>{function t(o){return o?/^#[0-9a-fA-F]{6}$/.test(o):false}r.isValidHex=t;function e(o){let i=parseInt(o.slice(1,3),16),a=parseInt(o.slice(3,5),16),s=parseInt(o.slice(5,7),16);return {r:i,g:a,b:s}}r.hexToRgb=e;function n(o){if(!t(o))return;let{r:i,g:a,b:s}=e(o);return `\x1B[38;2;${i};${a};${s}m\x1B[1m`}r.hexToAnsiBold=n;})(et||(et={}));k();var tt;(n=>{class t extends Error{constructor(i){super(`No context found for ${i}`);c(this,"name",i);}}n.NotFound=t;function e(r){let o=new AsyncLocalStorage;return {use(){let i=o.getStore();if(!i)throw new t(r);return i},provide(i,a){return o.run(i,a)}}}n.create=e;})(tt||(tt={}));k();function br(t){return {[Symbol.dispose](){t();},[Symbol.asyncDispose](){return Promise.resolve(t())}}}k();var nt;(e=>{async function t(){return new Promise(n=>{let r=()=>{process._getActiveHandles().length===0&&process._getActiveRequests().length===0?n():setImmediate(r);};r();})}e.wait=t;})(nt||(nt={}));k();function xr(t){if(t<=0)return "";if(t<60)return `${t}s`;if(t<3600){let n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}if(t<86400){let n=Math.floor(t/3600),r=Math.floor(t%3600/60);return r>0?`${n}h ${r}m`:`${n}h`}if(t<604800){let n=Math.floor(t/86400);return n===1?"~1 day":`~${n} days`}let e=Math.floor(t/604800);return e===1?"~1 week":`~${e} weeks`}k();var rt;(a=>{function t(s,l){if(s===l)return true;if(typeof s!="object"||typeof l!="object"||s===null||l===null)return false;let p=Object.keys(s),c=Object.keys(l);if(p.length!==c.length)return false;for(let u of p)if(!c.includes(u)||!t(s[u],l[u]))return false;return true}function e(s){return {...s,super:s.super??false}}function n(s,l){return s?t(e(s),e(l)):false}a.match=n;function r(s,l=false){return {name:s.name,ctrl:s.ctrl,meta:s.meta,shift:s.shift,super:s.super??false,leader:l}}a.fromParsedKey=r;function o(s){if(!s)return "";let l=[];s.ctrl&&l.push("ctrl"),s.meta&&l.push("alt"),s.super&&l.push("super"),s.shift&&l.push("shift"),s.name&&(s.name==="delete"?l.push("del"):l.push(s.name));let p=l.join("+");return s.leader&&(p=p?`<leader> ${p}`:"<leader>"),p}a.keyToString=o;function i(s){return s==="none"?[]:s.split(",").map(l=>{let c=l.replace(/<leader>/g,"leader+").toLowerCase().split("+"),u={ctrl:false,meta:false,shift:false,super:false,leader:false,name:""};for(let f of c)switch(f){case "ctrl":u.ctrl=true;break;case "alt":case "meta":case "option":u.meta=true;break;case "super":u.super=true;break;case "shift":u.shift=true;break;case "leader":u.leader=true;break;case "esc":u.name="escape";break;default:u.name=f;break}return u})}a.parse=i;})(rt||(rt={}));k();var Z;(f=>{f.SUPPORTED_LANGS=["zh-CN","en-US"],f.DEFAULT_LANG="zh-CN";function n(m,g="EASBOT_LANG"){let S=[m,process.env[g]?.trim()];for(let w of S)if(w&&f.SUPPORTED_LANGS.includes(w))return w;return f.DEFAULT_LANG}f.resolveLocaleLang=n;function r(m){return m.replace(/\b\w/g,g=>g.toUpperCase())}f.titlecase=r;function o(m){return new Date(m).toLocaleTimeString(void 0,{timeStyle:"short"})}f.time=o;function i(m){let g=new Date(m),S=o(m),w=g.toLocaleDateString();return `${S} \xB7 ${w}`}f.datetime=i;function a(m){let g=new Date(m),S=new Date;return g.getFullYear()===S.getFullYear()&&g.getMonth()===S.getMonth()&&g.getDate()===S.getDate()?o(m):i(m)}f.todayTimeOrDateTime=a;function s(m){return m>=1e6?(m/1e6).toFixed(1)+"M":m>=1e3?(m/1e3).toFixed(1)+"K":m.toString()}f.number=s;function l(m){if(m<1e3)return `${m}ms`;if(m<6e4)return `${(m/1e3).toFixed(1)}s`;if(m<36e5){let w=Math.floor(m/6e4),v=Math.floor(m%6e4/1e3);return `${w}m ${v}s`}if(m<864e5){let w=Math.floor(m/36e5),v=Math.floor(m%36e5/6e4);return `${w}h ${v}m`}let g=Math.floor(m/36e5);return `${Math.floor(m%36e5/864e5)}d ${g}h`}f.duration=l;function p(m,g){return m.length<=g?m:m.slice(0,g-1)+"\u2026"}f.truncate=p;function c(m,g=35){if(m.length<=g)return m;let S="\u2026",w=Math.ceil((g-S.length)/2),v=Math.floor((g-S.length)/2);return m.slice(0,w)+S+m.slice(-v)}f.truncateMiddle=c;function u(m,g,S){return (m===1?g:S).replace("{}",m.toString())}f.pluralize=u;})(Z||(Z={}));var kr=Z.resolveLocaleLang,Sr=Z.SUPPORTED_LANGS,wr=Z.DEFAULT_LANG;k();var Tr=["HTTP_PROXY","HTTPS_PROXY","http_proxy","https_proxy"];function Mr(){return Tr.some(t=>process.env[t])}function Rr(){return process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy}function vr(){let t=process.env.HTTP_PROXY||process.env.http_proxy,e=process.env.HTTPS_PROXY||process.env.https_proxy;return {http:t,https:e,enabled:!!(t||e)}}k();var ot=class{constructor(){c(this,"queue",[]);c(this,"resolvers",[]);}push(e){let n=this.resolvers.shift();n?n(e):this.queue.push(e);}async next(){return this.queue.length>0?this.queue.shift():new Promise(e=>this.resolvers.push(e))}async*[Symbol.asyncIterator](){for(;;)yield await this.next();}};async function Ir(t,e,n){let r=[...e];await Promise.all(Array.from({length:t},async()=>{for(;;){let o=r.pop();if(o===void 0)return;await n(o);}}));}k();function Pr(){let t,e=new Promise(n=>t=n);return {trigger(){return t()},wait(){return e}}}k();function Fr(t,e){let n;return Promise.race([t.then(r=>(clearTimeout(n),r)),new Promise((r,o)=>{n=setTimeout(()=>{o(new Error(`Operation timed out after ${e}ms`));},e);})])}k();var st;(a=>{let n=/[\u4e00-\u9fff\u3400-\u4dbf]/g;function r(s){if(!s)return 0;let l=String(s),p=(l.match(n)||[]).length,c=l.length-p,u=Math.round(p/1.5),f=Math.round(c/4);return Math.max(0,u+f)}a.estimate=r;function o(s){if(s==null)return 0;try{let l=typeof s=="string"?s:JSON.stringify(s);return r(l)}catch{return 0}}a.estimateObject=o;function i(s){if(s.total!==void 0&&s.total>0)return s.total;let l=s.input??0,p=s.output??0,c=s.cache?.read??0,u=s.cache?.write??0;return l+p+c+u}a.total=i;})(st||(st={}));k();function _r(t){let e={},n=t.shape??t.required().shape;for(let[r,o]of Object.entries(n))e[r]=o.nullable().optional();return fe.object(e)}export{Qe as Archive,ot as AsyncQueue,Ce as Binary,et as Color,tt as Context,wr as DEFAULT_LANG,_e as Encode,nt as EventLoop,Ze as Fetch,De as Fn,j as Identifier,Ae as Ignore,rt as Keybind,Z as Locale,Ve as Markdown,Ee as NamedError,Sr as SUPPORTED_LANGS,Le as SessionTitle,Je as Slug,st as Token,Oe as TruncateContent,It as abortAfter,gr as abortAfterAny,Te as buildCodeSpanIndex,wt as chunkMarkdownIR,G as chunkText,Ne as chunkTextByBreakResolver,Me as convertMarkdownTables,we as createInlineCodeState,br as defer,ke as extractFrontmatter,Xe as findFenceSpanAt,tn as findLast,sn as fn,xr as formatDuration,be as formatMarkdown,ar as getDirectory,lr as getFileExtension,Rt as getFilename,cr as getFilenameTruncated,vr as getProxyConfig,Rr as getProxyUrl,un as git,yn as iife,Mt as isSafeFenceBreak,cn as loadEnv,hn as loadTextFile,gn as loadTextFileAsync,V as markdownToIR,oe as markdownToIRWithMeta,Se as parseFenceSpans,ie as parseFrontmatterBlock,bn as parseModelId,Mr as proxied,K as renderMarkdown,se as renderMarkdownWithMarkers,kr as resolveLocaleLang,Ke as retry,Be as scanParenAwareBreakpoints,xe as serializeFrontmatter,Pr as signal,ur as truncateMiddle,_r as updateSchema,Fr as withTimeout,Ir as work};