dsh-edge 0.19.0-alpha.2 → 0.19.0

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.
@@ -152,7 +152,7 @@ Known schemas:
152
152
  - `)}`,new Error(Ve)}let gt=`${c}/$ref`,nt=Ns(e,Le,n,r,i,s,o,gt,l);if(nt.valid||Se.push({instanceLocation:o,keyword:"$ref",keywordLocation:gt,error:"A subschema had errors."},...nt.errors),n==="4"||n==="7")return{valid:Se.length===0,errors:Se}}if(Array.isArray(g)){let ze=g.length,Le=!1;for(let gt=0;gt<ze;gt++)if(d===g[gt]||g[gt]==="integer"&&d==="number"&&e%1===0&&e===e){Le=!0;break}Le||Se.push({instanceLocation:o,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${d}" is invalid. Expected "${g.join('", "')}".`})}else g==="integer"?(d!=="number"||e%1||e!==e)&&Se.push({instanceLocation:o,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${d}" is invalid. Expected "${g}".`}):g!==void 0&&d!==g&&Se.push({instanceLocation:o,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${d}" is invalid. Expected "${g}".`});if(y!==void 0&&(d==="object"||d==="array"?$b(e,y)||Se.push({instanceLocation:o,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(y)}.`}):e!==y&&Se.push({instanceLocation:o,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})),v!==void 0&&(d==="object"||d==="array"?v.some(ze=>$b(e,ze))||Se.push({instanceLocation:o,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`}):v.some(ze=>e===ze)||Se.push({instanceLocation:o,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})),w!==void 0){let ze=`${c}/not`;Ns(e,w,n,r,i,s,o,ze).valid&&Se.push({instanceLocation:o,keyword:"not",keywordLocation:ze,error:'Instance matched "not" schema.'})}let at=[];if(S!==void 0){let ze=`${c}/anyOf`,Le=Se.length,gt=!1;for(let nt=0;nt<S.length;nt++){let Ve=S[nt],ht=Object.create(l),Re=Ns(e,Ve,n,r,i,h===!0?s:null,o,`${ze}/${nt}`,ht);Se.push(...Re.errors),gt=gt||Re.valid,Re.valid&&at.push(ht)}gt?Se.length=Le:Se.splice(Le,0,{instanceLocation:o,keyword:"anyOf",keywordLocation:ze,error:"Instance does not match any subschemas."})}if(k!==void 0){let ze=`${c}/allOf`,Le=Se.length,gt=!0;for(let nt=0;nt<k.length;nt++){let Ve=k[nt],ht=Object.create(l),Re=Ns(e,Ve,n,r,i,h===!0?s:null,o,`${ze}/${nt}`,ht);Se.push(...Re.errors),gt=gt&&Re.valid,Re.valid&&at.push(ht)}gt?Se.length=Le:Se.splice(Le,0,{instanceLocation:o,keyword:"allOf",keywordLocation:ze,error:"Instance does not match every subschema."})}if(E!==void 0){let ze=`${c}/oneOf`,Le=Se.length,gt=E.filter((nt,Ve)=>{let ht=Object.create(l),Re=Ns(e,nt,n,r,i,h===!0?s:null,o,`${ze}/${Ve}`,ht);return Se.push(...Re.errors),Re.valid&&at.push(ht),Re.valid}).length;gt===1?Se.length=Le:Se.splice(Le,0,{instanceLocation:o,keyword:"oneOf",keywordLocation:ze,error:`Instance does not match exactly one subschema (${gt} matches).`})}if((d==="object"||d==="array")&&Object.assign(l,...at),_!==void 0){let ze=`${c}/if`;if(Ns(e,_,n,r,i,s,o,ze,l).valid){if(I!==void 0){let gt=Ns(e,I,n,r,i,s,o,`${c}/then`,l);gt.valid||Se.push({instanceLocation:o,keyword:"if",keywordLocation:ze,error:'Instance does not match "then" schema.'},...gt.errors)}}else if(j!==void 0){let gt=Ns(e,j,n,r,i,s,o,`${c}/else`,l);gt.valid||Se.push({instanceLocation:o,keyword:"if",keywordLocation:ze,error:'Instance does not match "else" schema.'},...gt.errors)}}if(d==="object"){if(x!==void 0)for(let nt of x)nt in e||Se.push({instanceLocation:o,keyword:"required",keywordLocation:`${c}/required`,error:`Instance does not have required property "${nt}".`});let ze=Object.keys(e);if(A!==void 0&&ze.length<A&&Se.push({instanceLocation:o,keyword:"minProperties",keywordLocation:`${c}/minProperties`,error:`Instance does not have at least ${A} properties.`}),U!==void 0&&ze.length>U&&Se.push({instanceLocation:o,keyword:"maxProperties",keywordLocation:`${c}/maxProperties`,error:`Instance does not have at least ${U} properties.`}),C!==void 0){let nt=`${c}/propertyNames`;for(let Ve in e){let ht=`${o}/${ru(Ve)}`,Re=Ns(Ve,C,n,r,i,s,ht,nt);Re.valid||Se.push({instanceLocation:o,keyword:"propertyNames",keywordLocation:nt,error:`Property name "${Ve}" does not match schema.`},...Re.errors)}}if(R!==void 0){let nt=`${c}/dependantRequired`;for(let Ve in R)if(Ve in e){let ht=R[Ve];for(let Re of ht)Re in e||Se.push({instanceLocation:o,keyword:"dependentRequired",keywordLocation:nt,error:`Instance has "${Ve}" but does not have "${Re}".`})}}if($!==void 0)for(let nt in $){let Ve=`${c}/dependentSchemas`;if(nt in e){let ht=Ns(e,$[nt],n,r,i,s,o,`${Ve}/${ru(nt)}`,l);ht.valid||Se.push({instanceLocation:o,keyword:"dependentSchemas",keywordLocation:Ve,error:`Instance has "${nt}" but does not match dependant schema.`},...ht.errors)}}if(N!==void 0){let nt=`${c}/dependencies`;for(let Ve in N)if(Ve in e){let ht=N[Ve];if(Array.isArray(ht))for(let Re of ht)Re in e||Se.push({instanceLocation:o,keyword:"dependencies",keywordLocation:nt,error:`Instance has "${Ve}" but does not have "${Re}".`});else{let Re=Ns(e,ht,n,r,i,s,o,`${nt}/${ru(Ve)}`);Re.valid||Se.push({instanceLocation:o,keyword:"dependencies",keywordLocation:nt,error:`Instance has "${Ve}" but does not match dependant schema.`},...Re.errors)}}}let Le=Object.create(null),gt=!1;if(L!==void 0){let nt=`${c}/properties`;for(let Ve in L){if(!(Ve in e))continue;let ht=`${o}/${ru(Ve)}`,Re=Ns(e[Ve],L[Ve],n,r,i,s,ht,`${nt}/${ru(Ve)}`);if(Re.valid)l[Ve]=Le[Ve]=!0;else if(gt=i,Se.push({instanceLocation:o,keyword:"properties",keywordLocation:nt,error:`Property "${Ve}" does not match schema.`},...Re.errors),gt)break}}if(!gt&&O!==void 0){let nt=`${c}/patternProperties`;for(let Ve in O){let ht=new RegExp(Ve,"u"),Re=O[Ve];for(let St in e){if(!ht.test(St))continue;let Bt=`${o}/${ru(St)}`,dt=Ns(e[St],Re,n,r,i,s,Bt,`${nt}/${ru(Ve)}`);dt.valid?l[St]=Le[St]=!0:(gt=i,Se.push({instanceLocation:o,keyword:"patternProperties",keywordLocation:nt,error:`Property "${St}" matches pattern "${Ve}" but does not match associated schema.`},...dt.errors))}}}if(!gt&&V!==void 0){let nt=`${c}/additionalProperties`;for(let Ve in e){if(Le[Ve])continue;let ht=`${o}/${ru(Ve)}`,Re=Ns(e[Ve],V,n,r,i,s,ht,nt);Re.valid?l[Ve]=!0:(gt=i,Se.push({instanceLocation:o,keyword:"additionalProperties",keywordLocation:nt,error:`Property "${Ve}" does not match additional properties schema.`},...Re.errors))}}else if(!gt&&Q!==void 0){let nt=`${c}/unevaluatedProperties`;for(let Ve in e)if(!l[Ve]){let ht=`${o}/${ru(Ve)}`,Re=Ns(e[Ve],Q,n,r,i,s,ht,nt);Re.valid?l[Ve]=!0:Se.push({instanceLocation:o,keyword:"unevaluatedProperties",keywordLocation:nt,error:`Property "${Ve}" does not match unevaluated properties schema.`},...Re.errors)}}}else if(d==="array"){le!==void 0&&e.length>le&&Se.push({instanceLocation:o,keyword:"maxItems",keywordLocation:`${c}/maxItems`,error:`Array has too many items (${e.length} > ${le}).`}),ve!==void 0&&e.length<ve&&Se.push({instanceLocation:o,keyword:"minItems",keywordLocation:`${c}/minItems`,error:`Array has too few items (${e.length} < ${ve}).`});let ze=e.length,Le=0,gt=!1;if(P!==void 0){let nt=`${c}/prefixItems`,Ve=Math.min(P.length,ze);for(;Le<Ve;Le++){let ht=Ns(e[Le],P[Le],n,r,i,s,`${o}/${Le}`,`${nt}/${Le}`);if(l[Le]=!0,!ht.valid&&(gt=i,Se.push({instanceLocation:o,keyword:"prefixItems",keywordLocation:nt,error:"Items did not match schema."},...ht.errors),gt))break}}if(G!==void 0){let nt=`${c}/items`;if(Array.isArray(G)){let Ve=Math.min(G.length,ze);for(;Le<Ve;Le++){let ht=Ns(e[Le],G[Le],n,r,i,s,`${o}/${Le}`,`${nt}/${Le}`);if(l[Le]=!0,!ht.valid&&(gt=i,Se.push({instanceLocation:o,keyword:"items",keywordLocation:nt,error:"Items did not match schema."},...ht.errors),gt))break}}else for(;Le<ze;Le++){let Ve=Ns(e[Le],G,n,r,i,s,`${o}/${Le}`,nt);if(l[Le]=!0,!Ve.valid&&(gt=i,Se.push({instanceLocation:o,keyword:"items",keywordLocation:nt,error:"Items did not match schema."},...Ve.errors),gt))break}if(!gt&&Y!==void 0){let Ve=`${c}/additionalItems`;for(;Le<ze;Le++){let ht=Ns(e[Le],Y,n,r,i,s,`${o}/${Le}`,Ve);l[Le]=!0,ht.valid||(gt=i,Se.push({instanceLocation:o,keyword:"additionalItems",keywordLocation:Ve,error:"Items did not match additional items schema."},...ht.errors))}}}if(z!==void 0)if(ze===0&&ne===void 0)Se.push({instanceLocation:o,keyword:"contains",keywordLocation:`${c}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(ne!==void 0&&ze<ne)Se.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array has less items (${ze}) than minContains (${ne}).`});else{let nt=`${c}/contains`,Ve=Se.length,ht=0;for(let Re=0;Re<ze;Re++){let St=Ns(e[Re],z,n,r,i,s,`${o}/${Re}`,nt);St.valid?(l[Re]=!0,ht++):Se.push(...St.errors)}ht>=(ne||0)&&(Se.length=Ve),ne===void 0&&ye===void 0&&ht===0?Se.splice(Ve,0,{instanceLocation:o,keyword:"contains",keywordLocation:nt,error:"Array does not contain item matching schema."}):ne!==void 0&&ht<ne?Se.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array must contain at least ${ne} items matching schema. Only ${ht} items were found.`}):ye!==void 0&&ht>ye&&Se.push({instanceLocation:o,keyword:"maxContains",keywordLocation:`${c}/maxContains`,error:`Array may contain at most ${ye} items matching schema. ${ht} items were found.`})}if(!gt&&X!==void 0){let nt=`${c}/unevaluatedItems`;for(Le;Le<ze;Le++){if(l[Le])continue;let Ve=Ns(e[Le],X,n,r,i,s,`${o}/${Le}`,nt);l[Le]=!0,Ve.valid||Se.push({instanceLocation:o,keyword:"unevaluatedItems",keywordLocation:nt,error:"Items did not match unevaluated items schema."},...Ve.errors)}}if(ke)for(let nt=0;nt<ze;nt++){let Ve=e[nt],ht=typeof Ve=="object"&&Ve!==null;for(let Re=0;Re<ze;Re++){if(nt===Re)continue;let St=e[Re];(Ve===St||ht&&(typeof St=="object"&&St!==null)&&$b(Ve,St))&&(Se.push({instanceLocation:o,keyword:"uniqueItems",keywordLocation:`${c}/uniqueItems`,error:`Duplicate items at indexes ${nt} and ${Re}.`}),nt=Number.MAX_SAFE_INTEGER,Re=Number.MAX_SAFE_INTEGER)}}}else if(d==="number"){if(n==="4"?(Ee!==void 0&&(de===!0&&e<=Ee||e<Ee)&&Se.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${de?"or equal to ":""} ${Ee}.`}),ue!==void 0&&(rt===!0&&e>=ue||e>ue)&&Se.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${rt?"or equal to ":""} ${ue}.`})):(Ee!==void 0&&e<Ee&&Se.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${Ee}.`}),ue!==void 0&&e>ue&&Se.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${ue}.`}),de!==void 0&&e<=de&&Se.push({instanceLocation:o,keyword:"exclusiveMinimum",keywordLocation:`${c}/exclusiveMinimum`,error:`${e} is less than ${de}.`}),rt!==void 0&&e>=rt&&Se.push({instanceLocation:o,keyword:"exclusiveMaximum",keywordLocation:`${c}/exclusiveMaximum`,error:`${e} is greater than or equal to ${rt}.`})),We!==void 0){let ze=e%We;Math.abs(0-ze)>=11920929e-14&&Math.abs(We-ze)>=11920929e-14&&Se.push({instanceLocation:o,keyword:"multipleOf",keywordLocation:`${c}/multipleOf`,error:`${e} is not a multiple of ${We}.`})}}else if(d==="string"){let ze=tt===void 0&&Ae===void 0?0:Rxe(e);tt!==void 0&&ze<tt&&Se.push({instanceLocation:o,keyword:"minLength",keywordLocation:`${c}/minLength`,error:`String is too short (${ze} < ${tt}).`}),Ae!==void 0&&ze>Ae&&Se.push({instanceLocation:o,keyword:"maxLength",keywordLocation:`${c}/maxLength`,error:`String is too long (${ze} > ${Ae}).`}),xe!==void 0&&!new RegExp(xe,"u").test(e)&&Se.push({instanceLocation:o,keyword:"pattern",keywordLocation:`${c}/pattern`,error:"String does not match pattern."}),D!==void 0&&HG[D]&&!HG[D](e)&&Se.push({instanceLocation:o,keyword:"format",keywordLocation:`${c}/format`,error:`String does not match format "${D}".`})}return{valid:Se.length===0,errors:Se}}var ZG=ce(()=>{WG();lN();VG();cN();GG();a(Ns,"validate")});var uN,$xe=ce(()=>{lN();ZG();uN=class{static{a(this,"Validator")}schema;draft;shortCircuit;lookup;constructor(t,n="2019-09",r=!0){this.schema=t,this.draft=n,this.shortCircuit=r,this.lookup=qh(t)}validate(t){return Ns(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,n){n&&(t={...t,$id:n}),qh(t,this.lookup)}}});var Oxe=ce(()=>{WG();lN();VG();cN();Cxe();GG();ZG();$xe()});var dN,Nxe=ce(()=>{Oxe();dN=class{static{a(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let n=new uN(t,this.draft,this.shortcircuit);return r=>{let i=n.validate(r);return i.valid?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:i.errors.map(s=>`${s.instanceLocation}: ${s.error}`).join("; ")}}}}});var xo,pN=ce(()=>{"use strict";xo={probeTimeoutMs:3e4,callTimeoutMs:6e4,maxToolsPerServer:128,maxCatalogPages:10,maxCatalogBytes:131072,maxDescriptionLength:512,maxErrorMessageChars:300,maxPublicNameLength:64,maxInstructionsLength:1024,metaToolThreshold:20}});import{createHash as wgt}from"node:crypto";function xgt(e){let t=e.replace(/[.*+?^${}()|[\]\\]/gu,n=>n==="*"?"\0":`\\${n}`);return new RegExp(`^${t.replaceAll("\0",".*")}$`)}function Pxe(e,t,n){let r=t??"read_only";return r==="allow_all"?"allow":r==="approve_all"?"ask":n===!0?"allow":n===!1?"ask":bgt.some(i=>xgt(i).test(e))?"allow":"ask"}function gf(e){return e.replace(/Bearer\s+[^\s"']+/giu,"Bearer ***").replace(/(https?:\/\/[^\s"'?]+)\?[^\s"']*/giu,"$1?***").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/gu,"").slice(0,xo.maxErrorMessageChars)}function Dxe(e,t){let n=`mcp__${e}__${t}`,r=n.replace(/[^A-Za-z0-9_-]/gu,"_");if(r===n&&r.length<=xo.maxPublicNameLength)return r;let i=Sgt(e,t),s=xo.maxPublicNameLength-i.length-1;return`${r.slice(0,s)}_${i}`}function Sgt(e,t){return wgt("sha256").update(`${e}\0${t}`).digest("hex").slice(0,12)}function Mxe(e){if(!(e==null||typeof e!="object"))try{let t=JSON.parse(JSON.stringify(e));return w0(t),t}catch{return}}function _gt(e){return kgt.has(e)}function Lxe(e){return e.type!=="image"||e.data===void 0||e.mimeType===void 0||!_gt(e.mimeType)||!Egt.test(e.data)?void 0:{data:Uint8Array.from(atob(e.data),n=>n.charCodeAt(0)),mediaType:e.mimeType}}function jxe(e){return e.some(t=>t.type==="image"&&t.data!==void 0)}function j2(e){if(e.isError)return[{type:"text",text:e.content.filter(i=>i.type==="text"&&typeof i.text=="string").map(i=>i.text).join(`
153
153
  `)||"MCP tool returned an error."}];let t=[],n=[];for(let r of e.content)if(r.type==="text"&&typeof r.text=="string")n.push(r.text);else if(r.type==="resource_link"&&r.uri!==void 0)n.push(`Resource: ${r.name??"unnamed"} (${r.uri})`);else if(r.type==="image"&&r.data!==void 0)n.push(`![image](data:${r.mimeType??"image/png"};base64,${r.data})`);else if(r.type==="image")n.push(`[image: ${r.mimeType??"unknown type"}]`);else if(r.type==="audio")n.push("[audio result unsupported on Cloudflare Workers]");else if(r.type==="resource"&&r.resource?.text!==void 0){let i=r.resource.uri??"embedded resource";n.push(`--- ${i} ---
154
154
  ${r.resource.text}`)}else r.type==="resource"?n.push("[embedded resource: binary content not displayed]"):n.push(`[unsupported MCP content type: ${r.type}]`);return n.length>0&&t.push({type:"text",text:n.join(`
155
- `)}),t.length>0?t:[{type:"text",text:"(empty MCP result)"}]}var bgt,kgt,Egt,fN=ce(()=>{"use strict";ia();pN();bgt=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a(xgt,"globToRegExp");a(Pxe,"evaluateMcpToolPolicy");a(gf,"scrubMcpErrorMessage");a(Dxe,"publicToolName");a(Sgt,"hashSuffix");a(Mxe,"supportedOutputSchema");kgt=new Set(["image/png","image/jpeg"]),Egt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(_gt,"isImageMediaType");a(Lxe,"decodeImageBlock");a(jxe,"containsImage");a(j2,"mapMcpResultToContentBlocks")});var KG,Fxe=ce(()=>{KG={name:"dsh-edge",version:"0.19.0-alpha.2",description:"Your DeepSeek Harness, anywhere \u2014 deploy a persistent personal coding agent to Cloudflare Workers in one command",author:"pawaca",license:"MIT",type:"module",bin:{"dsh-edge":"scripts/cli.mjs"},files:["dist","worker","scripts/*.d.mts","scripts/*.mjs","wrangler.jsonc","README.md","README.zh.md","LICENSE","THIRD_PARTY_NOTICES.md"],repository:{type:"git",url:"git+https://github.com/pawaca/dsh-edge.git",directory:"apps/dsh-edge"},homepage:"https://github.com/pawaca/dsh-edge#readme",bugs:{url:"https://github.com/pawaca/dsh-edge/issues"},keywords:["deepseek","deepseek-harness","ai-agents","byok","cloudflare-workers","durable-objects","self-hosted"],engines:{node:">=22.14.0"},publishConfig:{access:"public"},dshEdge:{upstreamVersion:"0.2.0-rc.1"},scripts:{"bundle:direct":"pnpm run web:build && pnpm --dir standalone run build:worker:direct && node standalone/scripts/promote.mjs direct","bundle:isolated":"pnpm run web:build && pnpm --dir standalone run build:worker:isolated && node standalone/scripts/promote.mjs isolated","bundle:workers":"pnpm --dir standalone run build && pnpm --dir standalone run verify && node standalone/scripts/promote.mjs all",dev:"pnpm run bundle:direct && node scripts/dev.mjs direct","dev:isolated":"pnpm run bundle:isolated && node scripts/dev.mjs isolated","dev:container":"pnpm run bundle:isolated && node scripts/dev.mjs container","dsh-edge":"node scripts/cli.mjs","example:install":"node examples/install-keyless.mjs","install:cloudflare":"pnpm run bundle:workers && node scripts/cli.mjs install","legal:write":"node scripts/legal-files.mjs write","pack:verify":"node scripts/verify-packed.mjs",prepack:"node scripts/legal-files.mjs verify && pnpm run bundle:workers","web:build":"pnpm --dir standalone run build:web && node standalone/scripts/promote.mjs web",test:"vitest run --root ../.. --project edge-runtime","test:integration":"pnpm run bundle:workers && node tests/run-session-integration.mjs","test:container":"pnpm run bundle:isolated && node tests/container.integration.mjs","test:snapshot":"vitest run --root ../.. --config apps/dsh-edge/vitest.snapshot.config.ts",typecheck:"tsc --noEmit"},dependencies:{"@clack/prompts":"1.7.0","compare-versions":"6.1.1",execa:"^10.0.1","jsonc-parser":"^3.3.1",wrangler:"4.129.0"},devDependencies:{"@cfworker/json-schema":"^4.1.1","@cloudflare/computer":"0.3.1","@cloudflare/workers-types":"5.20260904.1","@deepseek-ai/cordis":"4.0.4","@deepseek-ai/cosmokit":"1.8.5","@deepseek-ai/dsh-agent":"0.2.0-rc.1","@deepseek-ai/dsh-agent-loop":"0.2.0-rc.1","@deepseek-ai/dsh-anonymous-user-id":"0.2.0-rc.1","@deepseek-ai/dsh-api-gateway":"0.2.0-rc.1","@deepseek-ai/dsh-api-job-controller":"0.2.0-rc.1","@deepseek-ai/dsh-api-remotes":"0.2.0-rc.1","@deepseek-ai/dsh-api-session-controller":"0.2.0-rc.1","@deepseek-ai/dsh-api-settings-controller":"0.2.0-rc.1","@deepseek-ai/dsh-api-workspace-controller":"0.2.0-rc.1","@deepseek-ai/dsh-api-workspace-files":"0.2.0-rc.1","@deepseek-ai/dsh-attachment":"0.2.0-rc.1","@deepseek-ai/dsh-brand":"0.2.0-rc.1","@deepseek-ai/dsh-client-locale":"0.2.0-rc.1","@deepseek-ai/dsh-client-store":"0.2.0-rc.1","@deepseek-ai/dsh-client-ui-chat":"0.2.0-rc.1","@deepseek-ai/dsh-client-ui-conversation":"0.2.0-rc.1","@deepseek-ai/dsh-client-ui-settings":"0.2.0-rc.1","@deepseek-ai/dsh-client-ui-settings-general":"0.2.0-rc.1","@deepseek-ai/dsh-client-ui-theme":"0.2.0-rc.1","@deepseek-ai/dsh-commands":"0.2.0-rc.1","@deepseek-ai/dsh-compaction":"0.2.0-rc.1","@deepseek-ai/dsh-compaction-basic":"0.2.0-rc.1","@deepseek-ai/dsh-compaction-tool-result-pruner":"0.2.0-rc.1","@deepseek-ai/dsh-credentials":"0.2.0-rc.1","@deepseek-ai/dsh-file-reference":"0.2.0-rc.1","@deepseek-ai/dsh-fs":"0.2.0-rc.1","@deepseek-ai/dsh-goal":"0.2.0-rc.1","@deepseek-ai/dsh-goal-round-driver":"0.2.0-rc.1","@deepseek-ai/dsh-host-directory-picker":"0.2.0-rc.1","@deepseek-ai/dsh-host-plugin-inventory":"0.2.0-rc.1","@deepseek-ai/dsh-invariants":"0.2.0-rc.1","@deepseek-ai/dsh-jobs":"0.2.0-rc.1","@deepseek-ai/dsh-jobs-local":"0.2.0-rc.1","@deepseek-ai/dsh-launch-environment":"0.2.0-rc.1","@deepseek-ai/dsh-llm":"0.2.0-rc.1","@deepseek-ai/dsh-llm-deepseek":"0.2.0-rc.1","@deepseek-ai/dsh-llm-deepseek-api-key":"0.2.0-rc.1","@deepseek-ai/dsh-message-feedback":"0.2.0-rc.1","@deepseek-ai/dsh-output-retention":"0.2.0-rc.1","@deepseek-ai/dsh-plan-mode":"0.2.0-rc.1","@deepseek-ai/dsh-ptc-runtime":"0.2.0-rc.1","@deepseek-ai/dsh-sandbox":"0.2.0-rc.1","@deepseek-ai/dsh-schedule":"0.2.0-rc.1","@deepseek-ai/dsh-scope":"0.2.0-rc.1","@deepseek-ai/dsh-session":"0.2.0-rc.1","@deepseek-ai/dsh-session-format":"0.2.0-rc.1","@deepseek-ai/dsh-session-format-catalog":"0.2.0-rc.1","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.0-rc.1","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.0-rc.1","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.0-rc.1","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.0-rc.1","@deepseek-ai/dsh-session-persistence":"0.2.0-rc.1","@deepseek-ai/dsh-session-projection":"0.2.0-rc.1","@deepseek-ai/dsh-session-projection-cache":"0.2.0-rc.1","@deepseek-ai/dsh-session-query":"0.2.0-rc.1","@deepseek-ai/dsh-session-reference":"0.2.0-rc.1","@deepseek-ai/dsh-session-title":"0.2.0-rc.1","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.0-rc.1","@deepseek-ai/dsh-session-title-llm":"0.2.0-rc.1","@deepseek-ai/dsh-settings":"0.2.0-rc.1","@deepseek-ai/dsh-skill":"0.2.0-rc.1","@deepseek-ai/dsh-spill":"0.2.0-rc.1","@deepseek-ai/dsh-spill-policy":"0.2.0-rc.1","@deepseek-ai/dsh-storage":"0.2.0-rc.1","@deepseek-ai/dsh-storage-domain":"0.2.0-rc.1","@deepseek-ai/dsh-subagent":"0.2.0-rc.1","@deepseek-ai/dsh-subagent-in-process-driver":"0.2.0-rc.1","@deepseek-ai/dsh-subagent-spawn-in-process":"0.2.0-rc.1","@deepseek-ai/dsh-system-prompt":"0.2.0-rc.1","@deepseek-ai/dsh-timeout":"0.2.0-rc.1","@deepseek-ai/dsh-token-meter":"0.2.0-rc.1","@deepseek-ai/dsh-tool-ask-user":"0.2.0-rc.1","@deepseek-ai/dsh-tool-call-timeout-policy":"0.2.0-rc.1","@deepseek-ai/dsh-tool-fs":"0.2.0-rc.1","@deepseek-ai/dsh-tool-goal":"0.2.0-rc.1","@deepseek-ai/dsh-tool-jobs":"0.2.0-rc.1","@deepseek-ai/dsh-tool-skill":"0.2.0-rc.1","@deepseek-ai/dsh-tool-subagent":"0.2.0-rc.1","@deepseek-ai/dsh-tool-web":"0.2.0-rc.1","@deepseek-ai/dsh-tool-workflow":"0.2.0-rc.1","@deepseek-ai/dsh-tools":"0.2.0-rc.1","@deepseek-ai/dsh-typert-protocol":"0.2.0-rc.1","@deepseek-ai/dsh-typert-registry":"0.2.0-rc.1","@deepseek-ai/dsh-user-approval":"0.2.0-rc.1","@deepseek-ai/dsh-user-questions":"0.2.0-rc.1","@deepseek-ai/dsh-util-values":"0.2.0-rc.1","@deepseek-ai/dsh-web":"0.2.0-rc.1","@deepseek-ai/dsh-web-fetch-http":"0.2.0-rc.1","@deepseek-ai/dsh-web-search-deepseek":"0.2.0-rc.1","@deepseek-ai/dsh-workflow":"0.2.0-rc.1","@deepseek-ai/dsh-workspace":"0.2.0-rc.1","@deepseek-ai/schemastery":"3.18.4","@mixmark-io/domino":"2.2.0","@modelcontextprotocol/sdk":"1.30.0",acorn:"8.18.0","fast-png":"8.0.0","jpeg-js":"0.4.4","just-bash":"3.4.2",playwright:"^1.49.0",sucrase:"3.35.1",typescript:"^6.0.3",vitest:"^4.1.8",ws:"^8.21.0"}}});var i1,qxe,Uxe,F2=ce(()=>{"use strict";Fxe();i1=KG.version,qxe=KG.dshEdge.upstreamVersion,Uxe=`npx dsh-edge@${i1.includes("-")?"next":"latest"} upgrade`});function Rgt(e){let t=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/iu.exec(e);if(t!==null)return t[1];let n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/iu.exec(e);if(n!==null){let r=parseInt(n[1],16),i=parseInt(n[2],16);return`${String(r>>8)}.${String(r&255)}.${String(i>>8)}.${String(i&255)}`}}function $gt(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function Uh(e){let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("MCP server URL must use http: or https: protocol.");let n=t.hostname.toLowerCase(),r=n.endsWith(".")?n.slice(0,-1):n,i=r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r;if(!(i==="localhost"||i==="127.0.0.1"||i==="::1")){for(let s of Igt)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if($gt(i)){let s=Rgt(i),o=s??i;for(let c of Agt)if(c.test(o))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`);if(s===void 0){for(let c of Cgt)if(c.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function Ogt(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function zxe(e,t,n){Uh(e);let r=new aN(new URL(e),{requestInit:{headers:Ogt(t),signal:n},fetch:s1}),i=new sN({name:"dsh-edge",version:i1},{capabilities:{},jsonSchemaValidator:Ngt});return await i.connect(r),{client:i,close:a(async()=>{await i.close().catch(()=>{})},"close")}}async function Bxe(e,t,n){let r=AbortSignal.timeout(xo.probeTimeoutMs),i;try{i=await zxe(t,n,r)}catch(c){throw new Error(gf(c instanceof Error?c.message:String(c)))}let{client:s,close:o}=i;try{let c=[],l=new Set,u=new Set,d;for(let h=0;h<xo.maxCatalogPages;h++){let g=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let y of g.tools){if(c.length>=xo.maxToolsPerServer)break;let v=Dxe(e,y.name);if(l.has(v))throw new Error(`Server listed tool "${y.name}" more than once`);l.add(v);let x=y.annotations?.readOnlyHint,w=Mxe(y.outputSchema);c.push({name:y.name,publicName:v,description:y.description??"",inputSchema:y.inputSchema??{type:"object"},...w!==void 0?{outputSchema:w}:{},...x!==void 0?{annotations:{readOnlyHint:x}}:{}})}if(c.length>=xo.maxToolsPerServer||(d=g.nextCursor??void 0,d===void 0))break;if(u.has(d))throw new Error("Server repeated a tools/list continuation cursor");u.add(d)}let p=s.getServerVersion?.(),f=s.getInstructions?.();return{tools:c,serverInfo:p?{name:p.name,version:p.version}:void 0,instructions:typeof f=="string"&&f.length>0?f.slice(0,xo.maxInstructionsLength):void 0}}finally{await o()}}async function hN(e,t,n,r,i,s){let o=s??xo.callTimeoutMs,c=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),l;try{l=await zxe(e,r,c)}catch(u){throw new Error(gf(u instanceof Error?u.message:String(u)))}try{let u=await l.client.callTool({name:t,arguments:n},void 0,{signal:c});return{content:u.content??[],structuredContent:u.structuredContent,isError:u.isError===!0}}catch(u){throw new Error(gf(u instanceof Error?u.message:String(u)))}finally{await l.close()}}var Igt,Agt,Cgt,Ngt,s1,q2=ce(()=>{"use strict";Vbe();_xe();Nxe();fN();pN();F2();Igt=[".internal",".local",".localhost"],Agt=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],Cgt=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(Rgt,"extractMappedIPv4");a($gt,"isIpAddress");a(Uh,"assertSafeUrl");a(Ogt,"buildHeaders");Ngt=new dN,s1=a(async(e,t)=>{let n=await globalThis.fetch(e,{...t,redirect:"manual"});if(n.status>=300&&n.status<400)throw new Error(`MCP server returned HTTP ${String(n.status)} redirect; redirects are blocked for security.`);return n},"noRedirectFetch");a(zxe,"connectClient");a(Bxe,"probe");a(hN,"callTool")});import{Buffer as Pgt}from"node:buffer";function jgt(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Lgt.has(e.code)}function Hxe(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Mgt.has(e.code)}function Vxe(e,t,n){let r=Pgt.from(e,"base64");if(e.length===0&&t==="reject"||r.toString("base64")!==e)throw new rr(n==="INVALID_IMAGE_BASE64"?"Image upload is not canonical base64.":"File upload is not canonical base64.",n);return new Uint8Array(r)}function Fgt(e){return Vxe(e,"reject","INVALID_IMAGE_BASE64")}function qgt(e){return{data:Fgt(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function U2(e,t){return e.saveImages(t.map(qgt))}async function Ugt(e,t){return e.saveFile({data:Vxe(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function Gxe(e,t,n){let r=Math.min(1,Math.sqrt(n/(e*t)));if(r===1)return{width:e,height:t};if(e>=t){let o=Math.max(1,Math.floor(e*r)),c=Math.max(1,Math.round(o*t/e));for(;o*c>n&&o>1;)o-=1,c=Math.max(1,Math.round(o*t/e));return{width:o,height:c}}let i=Math.max(1,Math.floor(t*r)),s=Math.max(1,Math.round(i*e/t));for(;s*i>n&&i>1;)i-=1,s=Math.max(1,Math.round(i*e/t));return{width:s,height:i}}function JG(e,t,n){return n>=Math.max(e,t)?{width:e,height:t}:e>=t?{width:n,height:Math.max(1,Math.round(n*t/e))}:{width:Math.max(1,Math.round(n*e/t)),height:n}}var Wxe,Dgt,Mgt,Lgt,rr,YG,zh=ce(()=>{Bn();Wxe=["TOO_MANY_IMAGES","IMAGES_TOO_LARGE","UNSUPPORTED_IMAGE_TYPE","INVALID_IMAGE_BASE64","INVALID_IMAGE","IMAGE_TYPE_MISMATCH","IMAGE_TOO_LARGE","IMAGE_TOO_MANY_PIXELS","IMAGE_DIMENSION_TOO_LARGE"],Dgt=[...Wxe,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],Mgt=new Set(Wxe),Lgt=new Set(Dgt),rr=class extends Error{static{a(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};a(jgt,"isAttachmentError");a(Hxe,"isImageAdmissionError");a(Vxe,"decodeCanonicalBase64");a(Fgt,"decodeBase64");a(qgt,"saveInput");a(U2,"admitEncodedImages");a(Ugt,"admitEncodedFile");a(Gxe,"requestImageDimensions");a(JG,"longEdgeDimensions");YG=class extends xt{static{a(this,"AttachmentStore")}constructor(e){super(e,"attachments")}validateImageBatch(e){let{maxImagesPerMessage:t,maxMessageImageBytes:n,mediaTypes:r}=this.imageLimits;if(e.length>t)throw new rr("Image batch exceeds the configured image-count limit.","TOO_MANY_IMAGES");if(e.reduce((i,s)=>i+s.data.byteLength,0)>n)throw new rr("Image batch exceeds the configured aggregate image-byte limit.","IMAGES_TOO_LARGE");for(let i of e)if(!r.includes(i.mediaType))throw new rr(`Image type ${i.mediaType} is not accepted by this deployment.`,"UNSUPPORTED_IMAGE_TYPE")}async saveImages(e){this.validateImageBatch(e);for(let n of e)await this.validateImage(n);let t=[];for(let n of e)t.push(await this.saveImage(n));return t}async admitPromptContent(e){if(e.every(r=>r.type!=="image"))return e.map(r=>r.type==="text"?{type:"text",text:r.text}:{type:"file",attachment:r.attachment});let t=await U2(this,e.filter(r=>r.type==="image")),n=0;return e.map(r=>r.type==="text"?{type:"text",text:r.text}:r.type==="file"?{type:"file",attachment:r.attachment}:{type:"image",attachment:t[n++]})}admitEncodedFile(e){return Ugt(this,e)}isAttachmentError(e){return jgt(e)}imageHostPath(e){}saveFile(e){return Promise.reject(new rr("The mounted attachment provider cannot store verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}saveFileStream(e){return Promise.reject(new rr("The mounted attachment provider cannot stream verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}async*readFileStream(e,t){t?.throwIfAborted(),await Promise.reject(new rr("The mounted attachment provider cannot read verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}fileHostPath(e){}readImageRequest(e,t,n){return n?.throwIfAborted(),Promise.reject(new rr("The mounted attachment provider cannot derive model-request images.","ATTACHMENT_PROJECTION_UNSUPPORTED"))}}});var gN={};Ln(gN,{buildAuthorizationUrl:()=>Jgt,discoverEndpoints:()=>Zgt,exchangeCode:()=>Ygt,isTokenExpired:()=>Qgt,refreshToken:()=>Xgt,registerClient:()=>Kgt});function Yxe(e){let t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,n=>n.toString(16).padStart(2,"0")).join("").slice(0,e)}async function Ggt(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return btoa(String.fromCharCode(...new Uint8Array(n))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=/gu,"")}async function Zgt(e){let t=AbortSignal.timeout(mN),n=new URL(e),r=n.pathname==="/"?"/.well-known/oauth-protected-resource":`/.well-known/oauth-protected-resource${n.pathname}`,i=new URL(r,n.origin);Uh(i.href);let s=await s1(i.href,{signal:t});if(!s.ok)throw new Error(`PRM discovery failed: HTTP ${s.status}`);let c=(await s.json()).authorization_servers?.[0];if(typeof c!="string")throw new Error("No authorization server in PRM");let l=new URL(c),u=l.pathname==="/"?"/.well-known/oauth-authorization-server":`/.well-known/oauth-authorization-server${l.pathname}`,d=new URL(u,l.origin);Uh(d.href);let p=await s1(d.href,{signal:t});if(!p.ok)throw new Error(`AS metadata failed: HTTP ${p.status}`);let f=await p.json();if(typeof f.authorization_endpoint!="string"||typeof f.token_endpoint!="string")throw new Error("Missing required endpoints in AS metadata");return{authorization:f.authorization_endpoint,token:f.token_endpoint,registration:f.registration_endpoint}}async function Kgt(e,t,n){let r=AbortSignal.timeout(mN);Uh(e);let i=await s1(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_name:n,redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}),signal:r});if(!i.ok)throw new Error(`DCR failed: HTTP ${i.status}`);let s=await i.json();if(typeof s.client_id!="string")throw new Error("DCR response missing client_id");return{clientId:s.client_id,clientSecret:s.client_secret}}async function Jgt(e,t,n,r,i){let s=Yxe(32),o=Yxe(64),c=await Ggt(o),l=new URL(e.authorization);for(let[u,d]of Object.entries({response_type:"code",client_id:t.clientId,redirect_uri:n,state:s,code_challenge:c,code_challenge_method:"S256",resource:i}))l.searchParams.set(u,d);return{authorizationUrl:l.href,pendingFlow:{state:s,codeVerifier:o,redirectUri:n,serverName:r,serverUrl:i,stagedClient:t,createdAt:Date.now()}}}async function Ygt(e,t,n,r,i,s){let o=AbortSignal.timeout(mN),c=new URLSearchParams({grant_type:"authorization_code",code:n,redirect_uri:i,client_id:t.clientId,code_verifier:r});s!==void 0&&c.set("resource",s),t.clientSecret!==void 0&&c.set("client_secret",t.clientSecret),Uh(e);let l=await s1(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:c.toString(),signal:o});if(!l.ok)throw new Error(`Token exchange failed: HTTP ${l.status}`);return Xxe(await l.json())}async function Xgt(e,t,n,r){let i=AbortSignal.timeout(mN),s=new URLSearchParams({grant_type:"refresh_token",refresh_token:n,client_id:t.clientId});r!==void 0&&s.set("resource",r),t.clientSecret!==void 0&&s.set("client_secret",t.clientSecret),Uh(e);let o=await s1(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:s.toString(),signal:i});if(!o.ok)throw new Error(`Token refresh failed: HTTP ${o.status}`);return Xxe(await o.json())}function Xxe(e){let t=e;if(typeof t.access_token!="string")throw new Error("Missing access_token");let n=typeof t.expires_in=="number"?t.expires_in:void 0;return{accessToken:t.access_token,refreshToken:typeof t.refresh_token=="string"?t.refresh_token:void 0,expiresAt:n!==void 0?Date.now()+n*1e3:void 0,tokenType:typeof t.token_type=="string"?t.token_type:"Bearer",scope:typeof t.scope=="string"?t.scope:void 0}}function Qgt(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var mN,yN=ce(()=>{"use strict";q2();mN=1e4;a(Yxe,"randomString");a(Ggt,"sha256Base64Url");a(Zgt,"discoverEndpoints");a(Kgt,"registerClient");a(Jgt,"buildAuthorizationUrl");a(Ygt,"exchangeCode");a(Xgt,"refreshToken");a(Xxe,"parseTokenResponse");a(Qgt,"isTokenExpired")});var ir,oSe,wN=ce(()=>{Bn();kr();ir=class extends Kr{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},oSe=class extends xt{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new ir("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function mZ(e){return CN.test(e)}function RN(e){return e.invocation.modelInvocable}function Nb(e){return e.invocation.userInvocable}function gZ(e){let t=P0t(e);return[`<skill_content name="${D0t(e.name)}">`,"<skill_resources>",...t,"</skill_resources>","","<skill_instructions>",e.content,"</skill_instructions>","</skill_content>"].join(`
155
+ `)}),t.length>0?t:[{type:"text",text:"(empty MCP result)"}]}var bgt,kgt,Egt,fN=ce(()=>{"use strict";ia();pN();bgt=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a(xgt,"globToRegExp");a(Pxe,"evaluateMcpToolPolicy");a(gf,"scrubMcpErrorMessage");a(Dxe,"publicToolName");a(Sgt,"hashSuffix");a(Mxe,"supportedOutputSchema");kgt=new Set(["image/png","image/jpeg"]),Egt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(_gt,"isImageMediaType");a(Lxe,"decodeImageBlock");a(jxe,"containsImage");a(j2,"mapMcpResultToContentBlocks")});var KG,Fxe=ce(()=>{KG={name:"dsh-edge",version:"0.19.0",description:"Your DeepSeek Harness, anywhere \u2014 deploy a persistent personal coding agent to Cloudflare Workers in one command",author:"pawaca",license:"MIT",type:"module",bin:{"dsh-edge":"scripts/cli.mjs"},files:["dist","worker","scripts/*.d.mts","scripts/*.mjs","wrangler.jsonc","README.md","README.zh.md","LICENSE","THIRD_PARTY_NOTICES.md"],repository:{type:"git",url:"git+https://github.com/pawaca/dsh-edge.git",directory:"apps/dsh-edge"},homepage:"https://github.com/pawaca/dsh-edge#readme",bugs:{url:"https://github.com/pawaca/dsh-edge/issues"},keywords:["deepseek","deepseek-harness","ai-agents","byok","cloudflare-workers","durable-objects","self-hosted"],engines:{node:">=22.14.0"},publishConfig:{access:"public"},dshEdge:{upstreamVersion:"0.2.0-rc.1"},scripts:{"bundle:direct":"pnpm run web:build && pnpm --dir standalone run build:worker:direct && node standalone/scripts/promote.mjs direct","bundle:isolated":"pnpm run web:build && pnpm --dir standalone run build:worker:isolated && node standalone/scripts/promote.mjs isolated","bundle:workers":"pnpm --dir standalone run build && pnpm --dir standalone run verify && node standalone/scripts/promote.mjs all",dev:"pnpm run bundle:direct && node scripts/dev.mjs direct","dev:isolated":"pnpm run bundle:isolated && node scripts/dev.mjs isolated","dev:container":"pnpm run bundle:isolated && node scripts/dev.mjs container","dsh-edge":"node scripts/cli.mjs","example:install":"node examples/install-keyless.mjs","install:cloudflare":"pnpm run bundle:workers && node scripts/cli.mjs install","legal:write":"node scripts/legal-files.mjs write","pack:verify":"node scripts/verify-packed.mjs",prepack:"node scripts/legal-files.mjs verify && pnpm run bundle:workers","web:build":"pnpm --dir standalone run build:web && node standalone/scripts/promote.mjs web",test:"vitest run --root ../.. --project edge-runtime","test:integration":"pnpm run bundle:workers && node tests/run-session-integration.mjs","test:container":"pnpm run bundle:isolated && node tests/container.integration.mjs","test:snapshot":"vitest run --root ../.. --config apps/dsh-edge/vitest.snapshot.config.ts",typecheck:"tsc --noEmit"},dependencies:{"@clack/prompts":"1.7.0","compare-versions":"6.1.1",execa:"^10.0.1","jsonc-parser":"^3.3.1",wrangler:"4.129.0"},devDependencies:{"@cfworker/json-schema":"^4.1.1","@cloudflare/computer":"0.3.1","@cloudflare/workers-types":"5.20260904.1","@deepseek-ai/cordis":"4.0.4","@deepseek-ai/cosmokit":"1.8.5","@deepseek-ai/dsh-agent":"0.2.0-rc.1","@deepseek-ai/dsh-agent-loop":"0.2.0-rc.1","@deepseek-ai/dsh-anonymous-user-id":"0.2.0-rc.1","@deepseek-ai/dsh-api-gateway":"0.2.0-rc.1","@deepseek-ai/dsh-api-job-controller":"0.2.0-rc.1","@deepseek-ai/dsh-api-remotes":"0.2.0-rc.1","@deepseek-ai/dsh-api-session-controller":"0.2.0-rc.1","@deepseek-ai/dsh-api-settings-controller":"0.2.0-rc.1","@deepseek-ai/dsh-api-workspace-controller":"0.2.0-rc.1","@deepseek-ai/dsh-api-workspace-files":"0.2.0-rc.1","@deepseek-ai/dsh-attachment":"0.2.0-rc.1","@deepseek-ai/dsh-brand":"0.2.0-rc.1","@deepseek-ai/dsh-client-locale":"0.2.0-rc.1","@deepseek-ai/dsh-client-store":"0.2.0-rc.1","@deepseek-ai/dsh-client-ui-chat":"0.2.0-rc.1","@deepseek-ai/dsh-client-ui-conversation":"0.2.0-rc.1","@deepseek-ai/dsh-client-ui-settings":"0.2.0-rc.1","@deepseek-ai/dsh-client-ui-settings-general":"0.2.0-rc.1","@deepseek-ai/dsh-client-ui-theme":"0.2.0-rc.1","@deepseek-ai/dsh-commands":"0.2.0-rc.1","@deepseek-ai/dsh-compaction":"0.2.0-rc.1","@deepseek-ai/dsh-compaction-basic":"0.2.0-rc.1","@deepseek-ai/dsh-compaction-tool-result-pruner":"0.2.0-rc.1","@deepseek-ai/dsh-credentials":"0.2.0-rc.1","@deepseek-ai/dsh-file-reference":"0.2.0-rc.1","@deepseek-ai/dsh-fs":"0.2.0-rc.1","@deepseek-ai/dsh-goal":"0.2.0-rc.1","@deepseek-ai/dsh-goal-round-driver":"0.2.0-rc.1","@deepseek-ai/dsh-host-directory-picker":"0.2.0-rc.1","@deepseek-ai/dsh-host-plugin-inventory":"0.2.0-rc.1","@deepseek-ai/dsh-invariants":"0.2.0-rc.1","@deepseek-ai/dsh-jobs":"0.2.0-rc.1","@deepseek-ai/dsh-jobs-local":"0.2.0-rc.1","@deepseek-ai/dsh-launch-environment":"0.2.0-rc.1","@deepseek-ai/dsh-llm":"0.2.0-rc.1","@deepseek-ai/dsh-llm-deepseek":"0.2.0-rc.1","@deepseek-ai/dsh-llm-deepseek-api-key":"0.2.0-rc.1","@deepseek-ai/dsh-message-feedback":"0.2.0-rc.1","@deepseek-ai/dsh-output-retention":"0.2.0-rc.1","@deepseek-ai/dsh-plan-mode":"0.2.0-rc.1","@deepseek-ai/dsh-ptc-runtime":"0.2.0-rc.1","@deepseek-ai/dsh-sandbox":"0.2.0-rc.1","@deepseek-ai/dsh-schedule":"0.2.0-rc.1","@deepseek-ai/dsh-scope":"0.2.0-rc.1","@deepseek-ai/dsh-session":"0.2.0-rc.1","@deepseek-ai/dsh-session-format":"0.2.0-rc.1","@deepseek-ai/dsh-session-format-catalog":"0.2.0-rc.1","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.0-rc.1","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.0-rc.1","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.0-rc.1","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.0-rc.1","@deepseek-ai/dsh-session-persistence":"0.2.0-rc.1","@deepseek-ai/dsh-session-projection":"0.2.0-rc.1","@deepseek-ai/dsh-session-projection-cache":"0.2.0-rc.1","@deepseek-ai/dsh-session-query":"0.2.0-rc.1","@deepseek-ai/dsh-session-reference":"0.2.0-rc.1","@deepseek-ai/dsh-session-title":"0.2.0-rc.1","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.0-rc.1","@deepseek-ai/dsh-session-title-llm":"0.2.0-rc.1","@deepseek-ai/dsh-settings":"0.2.0-rc.1","@deepseek-ai/dsh-skill":"0.2.0-rc.1","@deepseek-ai/dsh-spill":"0.2.0-rc.1","@deepseek-ai/dsh-spill-policy":"0.2.0-rc.1","@deepseek-ai/dsh-storage":"0.2.0-rc.1","@deepseek-ai/dsh-storage-domain":"0.2.0-rc.1","@deepseek-ai/dsh-subagent":"0.2.0-rc.1","@deepseek-ai/dsh-subagent-in-process-driver":"0.2.0-rc.1","@deepseek-ai/dsh-subagent-spawn-in-process":"0.2.0-rc.1","@deepseek-ai/dsh-system-prompt":"0.2.0-rc.1","@deepseek-ai/dsh-timeout":"0.2.0-rc.1","@deepseek-ai/dsh-token-meter":"0.2.0-rc.1","@deepseek-ai/dsh-tool-ask-user":"0.2.0-rc.1","@deepseek-ai/dsh-tool-call-timeout-policy":"0.2.0-rc.1","@deepseek-ai/dsh-tool-fs":"0.2.0-rc.1","@deepseek-ai/dsh-tool-goal":"0.2.0-rc.1","@deepseek-ai/dsh-tool-jobs":"0.2.0-rc.1","@deepseek-ai/dsh-tool-skill":"0.2.0-rc.1","@deepseek-ai/dsh-tool-subagent":"0.2.0-rc.1","@deepseek-ai/dsh-tool-web":"0.2.0-rc.1","@deepseek-ai/dsh-tool-workflow":"0.2.0-rc.1","@deepseek-ai/dsh-tools":"0.2.0-rc.1","@deepseek-ai/dsh-typert-protocol":"0.2.0-rc.1","@deepseek-ai/dsh-typert-registry":"0.2.0-rc.1","@deepseek-ai/dsh-user-approval":"0.2.0-rc.1","@deepseek-ai/dsh-user-questions":"0.2.0-rc.1","@deepseek-ai/dsh-util-values":"0.2.0-rc.1","@deepseek-ai/dsh-web":"0.2.0-rc.1","@deepseek-ai/dsh-web-fetch-http":"0.2.0-rc.1","@deepseek-ai/dsh-web-search-deepseek":"0.2.0-rc.1","@deepseek-ai/dsh-workflow":"0.2.0-rc.1","@deepseek-ai/dsh-workspace":"0.2.0-rc.1","@deepseek-ai/schemastery":"3.18.4","@mixmark-io/domino":"2.2.0","@modelcontextprotocol/sdk":"1.30.0",acorn:"8.18.0","fast-png":"8.0.0","jpeg-js":"0.4.4","just-bash":"3.4.2",playwright:"^1.49.0",sucrase:"3.35.1",typescript:"^6.0.3",vitest:"^4.1.8",ws:"^8.21.0"}}});var i1,qxe,Uxe,F2=ce(()=>{"use strict";Fxe();i1=KG.version,qxe=KG.dshEdge.upstreamVersion,Uxe=`npx dsh-edge@${i1.includes("-")?"next":"latest"} upgrade`});function Rgt(e){let t=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/iu.exec(e);if(t!==null)return t[1];let n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/iu.exec(e);if(n!==null){let r=parseInt(n[1],16),i=parseInt(n[2],16);return`${String(r>>8)}.${String(r&255)}.${String(i>>8)}.${String(i&255)}`}}function $gt(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function Uh(e){let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("MCP server URL must use http: or https: protocol.");let n=t.hostname.toLowerCase(),r=n.endsWith(".")?n.slice(0,-1):n,i=r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r;if(!(i==="localhost"||i==="127.0.0.1"||i==="::1")){for(let s of Igt)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if($gt(i)){let s=Rgt(i),o=s??i;for(let c of Agt)if(c.test(o))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`);if(s===void 0){for(let c of Cgt)if(c.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function Ogt(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function zxe(e,t,n){Uh(e);let r=new aN(new URL(e),{requestInit:{headers:Ogt(t),signal:n},fetch:s1}),i=new sN({name:"dsh-edge",version:i1},{capabilities:{},jsonSchemaValidator:Ngt});return await i.connect(r),{client:i,close:a(async()=>{await i.close().catch(()=>{})},"close")}}async function Bxe(e,t,n){let r=AbortSignal.timeout(xo.probeTimeoutMs),i;try{i=await zxe(t,n,r)}catch(c){throw new Error(gf(c instanceof Error?c.message:String(c)))}let{client:s,close:o}=i;try{let c=[],l=new Set,u=new Set,d;for(let h=0;h<xo.maxCatalogPages;h++){let g=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let y of g.tools){if(c.length>=xo.maxToolsPerServer)break;let v=Dxe(e,y.name);if(l.has(v))throw new Error(`Server listed tool "${y.name}" more than once`);l.add(v);let x=y.annotations?.readOnlyHint,w=Mxe(y.outputSchema);c.push({name:y.name,publicName:v,description:y.description??"",inputSchema:y.inputSchema??{type:"object"},...w!==void 0?{outputSchema:w}:{},...x!==void 0?{annotations:{readOnlyHint:x}}:{}})}if(c.length>=xo.maxToolsPerServer||(d=g.nextCursor??void 0,d===void 0))break;if(u.has(d))throw new Error("Server repeated a tools/list continuation cursor");u.add(d)}let p=s.getServerVersion?.(),f=s.getInstructions?.();return{tools:c,serverInfo:p?{name:p.name,version:p.version}:void 0,instructions:typeof f=="string"&&f.length>0?f.slice(0,xo.maxInstructionsLength):void 0}}finally{await o()}}async function hN(e,t,n,r,i,s){let o=s??xo.callTimeoutMs,c=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),l;try{l=await zxe(e,r,c)}catch(u){throw new Error(gf(u instanceof Error?u.message:String(u)))}try{let u=await l.client.callTool({name:t,arguments:n},void 0,{signal:c});return{content:u.content??[],structuredContent:u.structuredContent,isError:u.isError===!0}}catch(u){throw new Error(gf(u instanceof Error?u.message:String(u)))}finally{await l.close()}}var Igt,Agt,Cgt,Ngt,s1,q2=ce(()=>{"use strict";Vbe();_xe();Nxe();fN();pN();F2();Igt=[".internal",".local",".localhost"],Agt=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],Cgt=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(Rgt,"extractMappedIPv4");a($gt,"isIpAddress");a(Uh,"assertSafeUrl");a(Ogt,"buildHeaders");Ngt=new dN,s1=a(async(e,t)=>{let n=await globalThis.fetch(e,{...t,redirect:"manual"});if(n.status>=300&&n.status<400)throw new Error(`MCP server returned HTTP ${String(n.status)} redirect; redirects are blocked for security.`);return n},"noRedirectFetch");a(zxe,"connectClient");a(Bxe,"probe");a(hN,"callTool")});import{Buffer as Pgt}from"node:buffer";function jgt(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Lgt.has(e.code)}function Hxe(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Mgt.has(e.code)}function Vxe(e,t,n){let r=Pgt.from(e,"base64");if(e.length===0&&t==="reject"||r.toString("base64")!==e)throw new rr(n==="INVALID_IMAGE_BASE64"?"Image upload is not canonical base64.":"File upload is not canonical base64.",n);return new Uint8Array(r)}function Fgt(e){return Vxe(e,"reject","INVALID_IMAGE_BASE64")}function qgt(e){return{data:Fgt(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function U2(e,t){return e.saveImages(t.map(qgt))}async function Ugt(e,t){return e.saveFile({data:Vxe(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function Gxe(e,t,n){let r=Math.min(1,Math.sqrt(n/(e*t)));if(r===1)return{width:e,height:t};if(e>=t){let o=Math.max(1,Math.floor(e*r)),c=Math.max(1,Math.round(o*t/e));for(;o*c>n&&o>1;)o-=1,c=Math.max(1,Math.round(o*t/e));return{width:o,height:c}}let i=Math.max(1,Math.floor(t*r)),s=Math.max(1,Math.round(i*e/t));for(;s*i>n&&i>1;)i-=1,s=Math.max(1,Math.round(i*e/t));return{width:s,height:i}}function JG(e,t,n){return n>=Math.max(e,t)?{width:e,height:t}:e>=t?{width:n,height:Math.max(1,Math.round(n*t/e))}:{width:Math.max(1,Math.round(n*e/t)),height:n}}var Wxe,Dgt,Mgt,Lgt,rr,YG,zh=ce(()=>{Bn();Wxe=["TOO_MANY_IMAGES","IMAGES_TOO_LARGE","UNSUPPORTED_IMAGE_TYPE","INVALID_IMAGE_BASE64","INVALID_IMAGE","IMAGE_TYPE_MISMATCH","IMAGE_TOO_LARGE","IMAGE_TOO_MANY_PIXELS","IMAGE_DIMENSION_TOO_LARGE"],Dgt=[...Wxe,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],Mgt=new Set(Wxe),Lgt=new Set(Dgt),rr=class extends Error{static{a(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};a(jgt,"isAttachmentError");a(Hxe,"isImageAdmissionError");a(Vxe,"decodeCanonicalBase64");a(Fgt,"decodeBase64");a(qgt,"saveInput");a(U2,"admitEncodedImages");a(Ugt,"admitEncodedFile");a(Gxe,"requestImageDimensions");a(JG,"longEdgeDimensions");YG=class extends xt{static{a(this,"AttachmentStore")}constructor(e){super(e,"attachments")}validateImageBatch(e){let{maxImagesPerMessage:t,maxMessageImageBytes:n,mediaTypes:r}=this.imageLimits;if(e.length>t)throw new rr("Image batch exceeds the configured image-count limit.","TOO_MANY_IMAGES");if(e.reduce((i,s)=>i+s.data.byteLength,0)>n)throw new rr("Image batch exceeds the configured aggregate image-byte limit.","IMAGES_TOO_LARGE");for(let i of e)if(!r.includes(i.mediaType))throw new rr(`Image type ${i.mediaType} is not accepted by this deployment.`,"UNSUPPORTED_IMAGE_TYPE")}async saveImages(e){this.validateImageBatch(e);for(let n of e)await this.validateImage(n);let t=[];for(let n of e)t.push(await this.saveImage(n));return t}async admitPromptContent(e){if(e.every(r=>r.type!=="image"))return e.map(r=>r.type==="text"?{type:"text",text:r.text}:{type:"file",attachment:r.attachment});let t=await U2(this,e.filter(r=>r.type==="image")),n=0;return e.map(r=>r.type==="text"?{type:"text",text:r.text}:r.type==="file"?{type:"file",attachment:r.attachment}:{type:"image",attachment:t[n++]})}admitEncodedFile(e){return Ugt(this,e)}isAttachmentError(e){return jgt(e)}imageHostPath(e){}saveFile(e){return Promise.reject(new rr("The mounted attachment provider cannot store verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}saveFileStream(e){return Promise.reject(new rr("The mounted attachment provider cannot stream verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}async*readFileStream(e,t){t?.throwIfAborted(),await Promise.reject(new rr("The mounted attachment provider cannot read verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}fileHostPath(e){}readImageRequest(e,t,n){return n?.throwIfAborted(),Promise.reject(new rr("The mounted attachment provider cannot derive model-request images.","ATTACHMENT_PROJECTION_UNSUPPORTED"))}}});var gN={};Ln(gN,{buildAuthorizationUrl:()=>Jgt,discoverEndpoints:()=>Zgt,exchangeCode:()=>Ygt,isTokenExpired:()=>Qgt,refreshToken:()=>Xgt,registerClient:()=>Kgt});function Yxe(e){let t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,n=>n.toString(16).padStart(2,"0")).join("").slice(0,e)}async function Ggt(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return btoa(String.fromCharCode(...new Uint8Array(n))).replace(/\+/gu,"-").replace(/\//gu,"_").replace(/=/gu,"")}async function Zgt(e){let t=AbortSignal.timeout(mN),n=new URL(e),r=n.pathname==="/"?"/.well-known/oauth-protected-resource":`/.well-known/oauth-protected-resource${n.pathname}`,i=new URL(r,n.origin);Uh(i.href);let s=await s1(i.href,{signal:t});if(!s.ok)throw new Error(`PRM discovery failed: HTTP ${s.status}`);let c=(await s.json()).authorization_servers?.[0];if(typeof c!="string")throw new Error("No authorization server in PRM");let l=new URL(c),u=l.pathname==="/"?"/.well-known/oauth-authorization-server":`/.well-known/oauth-authorization-server${l.pathname}`,d=new URL(u,l.origin);Uh(d.href);let p=await s1(d.href,{signal:t});if(!p.ok)throw new Error(`AS metadata failed: HTTP ${p.status}`);let f=await p.json();if(typeof f.authorization_endpoint!="string"||typeof f.token_endpoint!="string")throw new Error("Missing required endpoints in AS metadata");return{authorization:f.authorization_endpoint,token:f.token_endpoint,registration:f.registration_endpoint}}async function Kgt(e,t,n){let r=AbortSignal.timeout(mN);Uh(e);let i=await s1(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_name:n,redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}),signal:r});if(!i.ok)throw new Error(`DCR failed: HTTP ${i.status}`);let s=await i.json();if(typeof s.client_id!="string")throw new Error("DCR response missing client_id");return{clientId:s.client_id,clientSecret:s.client_secret}}async function Jgt(e,t,n,r,i){let s=Yxe(32),o=Yxe(64),c=await Ggt(o),l=new URL(e.authorization);for(let[u,d]of Object.entries({response_type:"code",client_id:t.clientId,redirect_uri:n,state:s,code_challenge:c,code_challenge_method:"S256",resource:i}))l.searchParams.set(u,d);return{authorizationUrl:l.href,pendingFlow:{state:s,codeVerifier:o,redirectUri:n,serverName:r,serverUrl:i,stagedClient:t,createdAt:Date.now()}}}async function Ygt(e,t,n,r,i,s){let o=AbortSignal.timeout(mN),c=new URLSearchParams({grant_type:"authorization_code",code:n,redirect_uri:i,client_id:t.clientId,code_verifier:r});s!==void 0&&c.set("resource",s),t.clientSecret!==void 0&&c.set("client_secret",t.clientSecret),Uh(e);let l=await s1(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:c.toString(),signal:o});if(!l.ok)throw new Error(`Token exchange failed: HTTP ${l.status}`);return Xxe(await l.json())}async function Xgt(e,t,n,r){let i=AbortSignal.timeout(mN),s=new URLSearchParams({grant_type:"refresh_token",refresh_token:n,client_id:t.clientId});r!==void 0&&s.set("resource",r),t.clientSecret!==void 0&&s.set("client_secret",t.clientSecret),Uh(e);let o=await s1(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:s.toString(),signal:i});if(!o.ok)throw new Error(`Token refresh failed: HTTP ${o.status}`);return Xxe(await o.json())}function Xxe(e){let t=e;if(typeof t.access_token!="string")throw new Error("Missing access_token");let n=typeof t.expires_in=="number"?t.expires_in:void 0;return{accessToken:t.access_token,refreshToken:typeof t.refresh_token=="string"?t.refresh_token:void 0,expiresAt:n!==void 0?Date.now()+n*1e3:void 0,tokenType:typeof t.token_type=="string"?t.token_type:"Bearer",scope:typeof t.scope=="string"?t.scope:void 0}}function Qgt(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var mN,yN=ce(()=>{"use strict";q2();mN=1e4;a(Yxe,"randomString");a(Ggt,"sha256Base64Url");a(Zgt,"discoverEndpoints");a(Kgt,"registerClient");a(Jgt,"buildAuthorizationUrl");a(Ygt,"exchangeCode");a(Xgt,"refreshToken");a(Xxe,"parseTokenResponse");a(Qgt,"isTokenExpired")});var ir,oSe,wN=ce(()=>{Bn();kr();ir=class extends Kr{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},oSe=class extends xt{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new ir("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function mZ(e){return CN.test(e)}function RN(e){return e.invocation.modelInvocable}function Nb(e){return e.invocation.userInvocable}function gZ(e){let t=P0t(e);return[`<skill_content name="${D0t(e.name)}">`,"<skill_resources>",...t,"</skill_resources>","","<skill_instructions>",e.content,"</skill_instructions>","</skill_content>"].join(`
156
156
  `)}function P0t(e){let t=e.resourceBase;if(t===void 0)return[`Resources for this skill are managed by provider "${Ob(e.provider)}".`,"Load referenced resources only as needed."];switch(t.kind){case"directory":return[`Base directory for this skill: ${Ob(t.path)}`,"Resolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed."];case"url":return[`Base URL for this skill: ${Ob(t.url)}`,"Resolve relative URLs mentioned by this skill against the base URL before using them. Load referenced resources only as needed."];case"opaque":return[`Resources for this skill: ${Ob(t.description)}`,"Load referenced resources only as needed."];default:return Ei(t,"SkillResourceBase.kind")}}function D0t(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;")}function Ob(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function L0t(e,t){if(Array.isArray(e))return{candidates:e,complete:!0};if(e===null||typeof e!="object")throw ISe(t);let n=e;if(!Array.isArray(n.candidates)||typeof n.complete!="boolean")throw ISe(t);return n}function ISe(e){return new TypeError(`skill provider "${e}" list() must return an array or { candidates, complete } observation`)}function F0t(e){return{name:e.name,description:e.description,...e.whenToUse!==void 0?{whenToUse:e.whenToUse}:{},invocation:e.invocation,source:e.source,provider:e.provider,...e.resourceBase!==void 0?{resourceBase:e.resourceBase}:{},rank:N0t,locator:e,...e.path!==void 0?{path:e.path}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}function q0t(e,t){if(typeof e.name!="string")throw new TypeError(`skill provider "${t}" returned a non-string skill name`);if(!CN.test(e.name))throw new Error(`skill provider "${t}" returned invalid skill name "${e.name}"`);if(typeof e.description!="string")throw new TypeError(`skill provider "${t}" returned skill "${e.name}" with a non-string description`);if(e.description.length===0)throw new Error(`skill provider "${t}" returned skill "${e.name}" without a description`);if(yZ(e.invocation,`skill provider "${t}" returned skill "${e.name}"`),e.whenToUse!==void 0&&typeof e.whenToUse!="string")throw new TypeError(`skill provider "${t}" returned skill "${e.name}" with a non-string whenToUse`);if(typeof e.source!="string")throw new TypeError(`skill provider "${t}" returned skill "${e.name}" with a non-string source`);if(typeof e.rank!="number"||!Number.isFinite(e.rank))throw new Error(`skill provider "${t}" returned skill "${e.name}" with an invalid rank`);if(typeof e.provider!="string")throw new TypeError(`skill provider "${t}" returned skill "${e.name}" with a non-string provider`);if(e.provider!==t)throw new Error(`skill provider "${t}" returned skill "${e.name}" for provider "${e.provider}"`);if(e.path!==void 0&&typeof e.path!="string")throw new TypeError(`skill provider "${t}" returned skill "${e.name}" with a non-string path`)}function U0t(e){if(!CN.test(e.name))throw new Error(`invalid skill name "${e.name}"`);if(e.description.length===0)throw new Error(`skill "${e.name}" requires a description`);yZ(e.invocation,`runtime skill "${e.name}"`)}function z0t(e){let t=e.name,n=e.description,r=e.whenToUse,i=e.invocation,s=e.source,o=e.provider,c=e.content,l=e.path;if(typeof t!="string")throw new TypeError("loaded skill name must be a string");if(!CN.test(t))throw new Error(`loaded skill has invalid name "${t}"`);if(typeof n!="string")throw new TypeError(`loaded skill "${t}" description must be a string`);if(n.length===0)throw new Error(`loaded skill "${t}" requires a description`);if(yZ(i,`loaded skill "${t}"`),r!==void 0&&typeof r!="string")throw new TypeError(`loaded skill "${t}" whenToUse must be a string`);if(typeof s!="string")throw new TypeError(`loaded skill "${t}" source must be a string`);if(typeof o!="string")throw new TypeError(`loaded skill "${t}" provider must be a string`);if(typeof c!="string")throw new TypeError(`loaded skill "${t}" content must be a string`);if(l!==void 0&&typeof l!="string")throw new TypeError(`loaded skill "${t}" path must be a string`)}function B0t(e){let{name:t,description:n,whenToUse:r,invocation:i,source:s,provider:o,resourceBase:c}=e;return{name:t,...e.path===void 0?{}:{path:e.path},description:n,...r!==void 0?{whenToUse:r}:{},invocation:i,source:s,provider:o,...c!==void 0?{resourceBase:c}:{}}}function yZ(e,t){if(e===void 0)return;if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError(`${t} with a non-object invocation policy`);let n=e;if(typeof n.modelInvocable!="boolean")throw new TypeError(`${t} with a non-boolean invocation.modelInvocable`);if(typeof n.userInvocable!="boolean")throw new TypeError(`${t} with a non-boolean invocation.userInvocable`)}function W0t(e,t){return $Se(e.name,t.name)}function $Se(e,t){return e<t?-1:e>t?1:0}function H0t(e,t){return e.candidate.rank-t.candidate.rank||e.providerOrder-t.providerOrder||e.localOrder-t.localOrder}function V0t(e,t,n=1){if(!Number.isInteger(t)||t<n)throw new Error(`skill: ${e} must be an integer greater than or equal to ${n}`)}function ASe(e,t){return t===void 0?e:(H2(t),new Promise((n,r)=>{let i=a(()=>{t.removeEventListener("abort",s)},"cleanup"),s=a(()=>{i(),r(AN(t.reason))},"onAbort");t.addEventListener("abort",s,{once:!0}),e.then(o=>{i(),n(o)},o=>{i(),r(AN(o))})}))}function H2(e){if(e?.aborted===!0)throw AN(e.reason)}function AN(e){try{if(e instanceof Error)return e}catch{}return new Error(IN(e))}function IN(e){try{return String(e)}catch{return"[unrenderable thrown value]"}}var CN,TSe,O0t,TN,N0t,CSe,M0t,RSe,j0t,Pb=ce(()=>{Bn();cs();Mc();Tn();CN=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,TSe=128,O0t=2,TN="runtime",N0t=250,CSe=600;a(mZ,"isSkillName");a(RN,"isModelInvocable");a(Nb,"isUserInvocable");a(gZ,"renderSkillContent");a(P0t,"renderResourceHint");a(D0t,"escapeAttr");a(Ob,"escapeText");M0t=class{static{a(this,"SkillLayer")}providers;runtime=new Map;constructor(e){this.providers=new Yp(t=>new Error(e===void 0?`a skill provider named "${t}" is already registered`:`a skill provider named "${t}" is already registered in this scope`))}isEmpty(){return this.providers.isEmpty()&&this.runtime.size===0}},RSe=class extends xt{static{a(this,"SkillRegistry")}static Config=W.object({collectCacheMaxEntries:W.number().default(TSe)});collectCacheMaxEntries;layers=new Xp(e=>new M0t(e),()=>{this.invalidateCache()});collectCache=new Map;revision=0;nextProviderOrder=0;scopeIds=new WeakMap;nextScopeId=1;constructor(e,t={}){super(e,"skills"),this.collectCacheMaxEntries=t.collectCacheMaxEntries??TSe,V0t("collectCacheMaxEntries",this.collectCacheMaxEntries)}registerProvider(e){let t=new AbortController,n,r,i={signal:t.signal,invalidate:a(()=>{let s=n;s!==void 0&&s.layer.providers.get(s.name)?.provider===r&&this.invalidateCache()},"invalidate")};try{r=e(i);let s=r.name;if(s===TN)throw new Error(`"${TN}" is reserved for runtime skill registrations`);let o=this.nextProviderOrder;return this.nextProviderOrder+=1,this.layers.effect(this.ctx,c=>{let l=c.providers.insert(s,{provider:r,order:o});return n={layer:c,name:s},()=>{n=void 0,l(),t.abort(new Error(`skill provider "${s}" disposed`))}},{label:"skills.registerProvider()"})}catch(s){throw t.abort(s),s}}register(e){U0t(e);let t=Dc(this.ctx),n=t===void 0?this.layers.global:this.layers.peek(t);if(n!==void 0&&n.runtime.has(e.name))return this.ctx.logger.warn(`runtime skill "${e.name}" ignored because it is already registered`),()=>{};let r={...e,invocation:e.invocation??{modelInvocable:!0,userInvocable:!0},provider:e.provider??TN};return this.layers.effect(this.ctx,i=>(i.runtime.set(r.name,r),()=>{i.runtime.delete(r.name)}),{label:"skills.register()"})}async list(e={}){return(await this.snapshot(e)).skills}async snapshot(e={}){let t=await this.collect(e);return{skills:[...t.entries.values()].map(n=>B0t(n.candidate)).sort(W0t),complete:t.cacheable}}async get(e,t={}){if(!mZ(e))return;let n=await this.collect(t);H2(t.signal);let r=n.entries.get(e);if(r===void 0)return;let i=await ASe(r.provider.get(r.candidate,t),t.signal);if(i!==void 0){if(z0t(i),i.name!==r.candidate.name){this.invalidateEntry(r);return}return i}}async collect(e){H2(e.signal);let t=1;for(;;){let n=this.revision,r=this.collectCacheKey(e.cwd,mE(e.scope),n),i=this.collectCache.get(r);if(i!==void 0)return{entries:i,cacheable:!0};let s=await this.collectFresh(e);if(H2(e.signal),n!==this.revision){if(t<O0t){t+=1;continue}return{entries:s.entries,cacheable:!1}}if(s.cacheable&&(this.collectCache.set(r,s.entries),this.collectCache.size>this.collectCacheMaxEntries)){let o=this.collectCache.keys().next();this.collectCache.delete(o.value)}return s}}async collectFresh(e){let t=[this.layers.global,...this.layers.chainLayers(e.scope)],n=new Map,r=!0;for(let i of t){let s=await this.collectLayer(i,e);s.cacheable||(r=!1);for(let o of s.entries)n.set(o.candidate.name,o)}return{entries:n,cacheable:r}}async collectLayer(e,t){let n=await this.listLayerCandidates(e,t);n.entries.sort(H0t);let r=new Set,i=[];for(let s of n.entries){let o=s.candidate;if(r.has(o.name)){this.ctx.logger.warn(`skill "${o.name}" from ${o.source} ignored because a higher-priority skill already exists`);continue}r.add(o.name),i.push(s)}return{entries:i,cacheable:n.cacheable}}async listLayerCandidates(e,t){H2(t.signal);let n=[],r=!0,i=0;for(let s of[...e.runtime.values()].sort((o,c)=>$Se(o.name,c.name)))n.push({candidate:F0t(s),provider:j0t,providerOrder:-1,localOrder:i,layer:e}),i+=1;for(let{provider:s,order:o}of[...e.providers.values()]){let c=0,l;try{l=await ASe(s.list(t),t.signal)}catch(d){if(t.signal?.aborted===!0)throw AN(t.signal.reason);r=!1,this.ctx.logger.warn(`skill provider "${s.name}" skipped: ${IN(d)}`)}if(l===void 0)continue;let u=L0t(l,s.name);u.complete||(r=!1);for(let d of u.candidates)q0t(d,s.name),n.push({candidate:d,provider:s,providerOrder:o,localOrder:c,layer:e}),c+=1}return{entries:n,cacheable:r}}invalidateCache(){this.revision+=1,this.collectCache.clear(),this.notifyChange()}invalidateEntry(e){e.layer.providers.get(e.provider.name)?.provider===e.provider&&this.invalidateCache()}scopeId(e){let t=this.scopeIds.get(e);return t===void 0&&(t=this.nextScopeId,this.nextScopeId+=1,this.scopeIds.set(e,t)),t}collectCacheKey(e,t,n){return JSON.stringify({cwd:e,scopes:t.map(r=>this.scopeId(r)),revision:n})}notifyChange(){for(let e of this.ctx.events.dispatch("emit",["skills/change"]))try{let t=e();Promise.resolve(t).catch(n=>{this.ctx.logger.warn(`skills/change listener rejected: ${IN(n)}`)})}catch(t){this.ctx.logger.warn(`skills/change listener threw: ${IN(t)}`)}}};a(L0t,"normalizeProviderObservation");a(ISe,"invalidProviderObservation");j0t={name:TN,list(){return Promise.resolve([])},get(e){return Promise.resolve(e.locator)}};a(F0t,"runtimeCandidate");a(q0t,"validateCandidate");a(U0t,"validateRuntimeSkill");a(z0t,"validateDefinition");a(B0t,"toSummary");a(yZ,"validateInvocation");a(W0t,"compareSkillSummary");a($Se,"compareCodePoints");a(H0t,"compareIndexedCandidates");a(V0t,"assertPositiveInteger");a(ASe,"waitWithAbort");a(H2,"throwIfAborted");a(AN,"toError");a(IN,"errorMessage")});var Qu,Mb=ce(()=>{Qu=class{static{a(this,"Deque")}buffer=new Array(16);head=0;count=0;get size(){return this.count}pushBack(e){this.ensureCapacity();let t=this.head+this.count;this.buffer[t<this.buffer.length?t:t-this.buffer.length]=e,this.count+=1}pushFront(e){this.ensureCapacity(),this.head=this.head===0?this.buffer.length-1:this.head-1,this.buffer[this.head]=e,this.count+=1}popFront(){if(this.count===0)return;let e=this.buffer[this.head];return this.buffer[this.head]=void 0,this.head+=1,this.head===this.buffer.length&&(this.head=0),this.count-=1,this.compact(),e}clear(){this.buffer=new Array(16),this.head=0,this.count=0}ensureCapacity(){this.count<this.buffer.length||this.resize(this.buffer.length*2)}compact(){if(this.count===0){this.head=0;return}this.buffer.length>16&&this.count<=this.buffer.length/4&&this.resize(Math.max(16,this.buffer.length/2))}resize(e){let t=new Array(e),n=this.head;for(let r=0;r<this.count;r+=1)t[r]=this.buffer[n],n+=1,n===this.buffer.length&&(n=0);this.buffer=t,this.head=0}}});var Wh,fke,$Z=ce(()=>{Bn();Wh=class extends Error{static{a(this,"DirectoryPickerError")}code;path;constructor(e,t,n){super(n),this.code=e,this.path=t,this.name="DirectoryPickerError"}},fke=class extends xt{static{a(this,"DirectoryPicker")}constructor(e){super(e,"directoryPicker")}}});var a_e=we((W7n,NP)=>{var o_e=o_e||function(e){return Buffer.from(e).toString("base64")};function iSt(e){var t=this,n=Math.round,r=Math.floor,i=new Array(64),s=new Array(64),o=new Array(64),c=new Array(64),l,u,d,p,f=new Array(65535),h=new Array(65535),g=new Array(64),y=new Array(64),v=[],x=0,w=7,S=new Array(64),k=new Array(64),E=new Array(64),_=new Array(256),I=new Array(2048),j,D=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],L=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],O=[0,1,2,3,4,5,6,7,8,9,10,11],V=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],Q=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],A=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],U=[0,1,2,3,4,5,6,7,8,9,10,11],C=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],R=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function $(oe){for(var Me=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99],Se=0;Se<64;Se++){var at=r((Me[Se]*oe+50)/100);at<1?at=1:at>255&&(at=255),i[D[Se]]=at}for(var ze=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99],Le=0;Le<64;Le++){var gt=r((ze[Le]*oe+50)/100);gt<1?gt=1:gt>255&&(gt=255),s[D[Le]]=gt}for(var nt=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379],Ve=0,ht=0;ht<8;ht++)for(var Re=0;Re<8;Re++)o[Ve]=1/(i[D[Ve]]*nt[ht]*nt[Re]*8),c[Ve]=1/(s[D[Ve]]*nt[ht]*nt[Re]*8),Ve++}a($,"initQuantTables");function N(oe,Me){for(var Se=0,at=0,ze=new Array,Le=1;Le<=16;Le++){for(var gt=1;gt<=oe[Le];gt++)ze[Me[at]]=[],ze[Me[at]][0]=Se,ze[Me[at]][1]=Le,at++,Se++;Se*=2}return ze}a(N,"computeHuffmanTbl");function P(){l=N(L,O),u=N(A,U),d=N(V,Q),p=N(C,R)}a(P,"initHuffmanTbl");function G(){for(var oe=1,Me=2,Se=1;Se<=15;Se++){for(var at=oe;at<Me;at++)h[32767+at]=Se,f[32767+at]=[],f[32767+at][1]=Se,f[32767+at][0]=at;for(var ze=-(Me-1);ze<=-oe;ze++)h[32767+ze]=Se,f[32767+ze]=[],f[32767+ze][1]=Se,f[32767+ze][0]=Me-1+ze;oe<<=1,Me<<=1}}a(G,"initCategoryNumber");function Y(){for(var oe=0;oe<256;oe++)I[oe]=19595*oe,I[oe+256>>0]=38470*oe,I[oe+512>>0]=7471*oe+32768,I[oe+768>>0]=-11059*oe,I[oe+1024>>0]=-21709*oe,I[oe+1280>>0]=32768*oe+8421375,I[oe+1536>>0]=-27439*oe,I[oe+1792>>0]=-5329*oe}a(Y,"initRGBYUVTable");function X(oe){for(var Me=oe[0],Se=oe[1]-1;Se>=0;)Me&1<<Se&&(x|=1<<w),Se--,w--,w<0&&(x==255?(z(255),z(0)):z(x),w=7,x=0)}a(X,"writeBits");function z(oe){v.push(oe)}a(z,"writeByte");function ne(oe){z(oe>>8&255),z(oe&255)}a(ne,"writeWord");function ye(oe,Me){var Se,at,ze,Le,gt,nt,Ve,ht,Re=0,St,Bt=8,dt=64;for(St=0;St<Bt;++St){Se=oe[Re],at=oe[Re+1],ze=oe[Re+2],Le=oe[Re+3],gt=oe[Re+4],nt=oe[Re+5],Ve=oe[Re+6],ht=oe[Re+7];var fn=Se+ht,zt=Se-ht,Lt=at+Ve,ae=at-Ve,Ne=ze+nt,He=ze-nt,st=Le+gt,At=Le-gt,Ke=fn+st,rn=fn-st,Qt=Lt+Ne,hn=Lt-Ne;oe[Re]=Ke+Qt,oe[Re+4]=Ke-Qt;var Pt=(hn+rn)*.707106781;oe[Re+2]=rn+Pt,oe[Re+6]=rn-Pt,Ke=At+He,Qt=He+ae,hn=ae+zt;var Rr=(Ke-hn)*.382683433,Pr=.5411961*Ke+Rr,is=1.306562965*hn+Rr,ki=Qt*.707106781,or=zt+ki,ss=zt-ki;oe[Re+5]=ss+Pr,oe[Re+3]=ss-Pr,oe[Re+1]=or+is,oe[Re+7]=or-is,Re+=8}for(Re=0,St=0;St<Bt;++St){Se=oe[Re],at=oe[Re+8],ze=oe[Re+16],Le=oe[Re+24],gt=oe[Re+32],nt=oe[Re+40],Ve=oe[Re+48],ht=oe[Re+56];var $s=Se+ht,Xs=Se-ht,fo=at+Ve,jt=at-Ve,On=ze+nt,ho=ze-nt,ma=Le+gt,Oo=Le-gt,No=$s+ma,Uo=$s-ma,ga=fo+On,Ba=fo-On;oe[Re]=No+ga,oe[Re+32]=No-ga;var zl=(Ba+Uo)*.707106781;oe[Re+16]=Uo+zl,oe[Re+48]=Uo-zl,No=Oo+ho,ga=ho+jt,Ba=jt+Xs;var Jc=(No-Ba)*.382683433,Id=.5411961*No+Jc,Ad=1.306562965*Ba+Jc,Cd=ga*.707106781,Rd=Xs+Cd,th=Xs-Cd;oe[Re+40]=th+Id,oe[Re+24]=th-Id,oe[Re+8]=Rd+Ad,oe[Re+56]=Rd-Ad,Re++}var Np;for(St=0;St<dt;++St)Np=oe[St]*Me[St],g[St]=Np>0?Np+.5|0:Np-.5|0;return g}a(ye,"fDCTQuant");function ve(){ne(65504),ne(16),z(74),z(70),z(73),z(70),z(0),z(1),z(1),z(0),ne(1),ne(1),z(0),z(0)}a(ve,"writeAPP0");function le(oe){if(oe){ne(65505),oe[0]===69&&oe[1]===120&&oe[2]===105&&oe[3]===102?ne(oe.length+2):(ne(oe.length+5+2),z(69),z(120),z(105),z(102),z(0));for(var Me=0;Me<oe.length;Me++)z(oe[Me])}}a(le,"writeAPP1");function ke(oe,Me){ne(65472),ne(17),z(8),ne(Me),ne(oe),z(3),z(1),z(17),z(0),z(2),z(17),z(1),z(3),z(17),z(1)}a(ke,"writeSOF0");function Ee(){ne(65499),ne(132),z(0);for(var oe=0;oe<64;oe++)z(i[oe]);z(1);for(var Me=0;Me<64;Me++)z(s[Me])}a(Ee,"writeDQT");function ue(){ne(65476),ne(418),z(0);for(var oe=0;oe<16;oe++)z(L[oe+1]);for(var Me=0;Me<=11;Me++)z(O[Me]);z(16);for(var Se=0;Se<16;Se++)z(V[Se+1]);for(var at=0;at<=161;at++)z(Q[at]);z(1);for(var ze=0;ze<16;ze++)z(A[ze+1]);for(var Le=0;Le<=11;Le++)z(U[Le]);z(17);for(var gt=0;gt<16;gt++)z(C[gt+1]);for(var nt=0;nt<=161;nt++)z(R[nt])}a(ue,"writeDHT");function de(oe){typeof oe>"u"||oe.constructor!==Array||oe.forEach(Me=>{if(typeof Me=="string"){ne(65534);var Se=Me.length;ne(Se+2);var at;for(at=0;at<Se;at++)z(Me.charCodeAt(at))}})}a(de,"writeCOM");function rt(){ne(65498),ne(12),z(3),z(1),z(0),z(2),z(17),z(3),z(17),z(0),z(63),z(0)}a(rt,"writeSOS");function We(oe,Me,Se,at,ze){for(var Le=ze[0],gt=ze[240],nt,Ve=16,ht=63,Re=64,St=ye(oe,Me),Bt=0;Bt<Re;++Bt)y[D[Bt]]=St[Bt];var dt=y[0]-Se;Se=y[0],dt==0?X(at[0]):(nt=32767+dt,X(at[h[nt]]),X(f[nt]));for(var fn=63;fn>0&&y[fn]==0;fn--);if(fn==0)return X(Le),Se;for(var zt=1,Lt;zt<=fn;){for(var ae=zt;y[zt]==0&&zt<=fn;++zt);var Ne=zt-ae;if(Ne>=Ve){Lt=Ne>>4;for(var He=1;He<=Lt;++He)X(gt);Ne=Ne&15}nt=32767+y[zt],X(ze[(Ne<<4)+h[nt]]),X(f[nt]),zt++}return fn!=ht&&X(Le),Se}a(We,"processDU");function tt(){for(var oe=String.fromCharCode,Me=0;Me<256;Me++)_[Me]=oe(Me)}a(tt,"initCharLookupTable"),this.encode=function(oe,Me){var Se=new Date().getTime();Me&&Ae(Me),v=new Array,x=0,w=7,ne(65496),ve(),de(oe.comments),le(oe.exifBuffer),Ee(),ke(oe.width,oe.height),ue(),rt();var at=0,ze=0,Le=0;x=0,w=7,this.encode.displayName="_encode_";for(var gt=oe.data,nt=oe.width,Ve=oe.height,ht=nt*4,Re=nt*3,St,Bt=0,dt,fn,zt,Lt,ae,Ne,He,st;Bt<Ve;){for(St=0;St<ht;){for(Lt=ht*Bt+St,ae=Lt,Ne=-1,He=0,st=0;st<64;st++)He=st>>3,Ne=(st&7)*4,ae=Lt+He*ht+Ne,Bt+He>=Ve&&(ae-=ht*(Bt+1+He-Ve)),St+Ne>=ht&&(ae-=St+Ne-ht+4),dt=gt[ae++],fn=gt[ae++],zt=gt[ae++],S[st]=(I[dt]+I[fn+256>>0]+I[zt+512>>0]>>16)-128,k[st]=(I[dt+768>>0]+I[fn+1024>>0]+I[zt+1280>>0]>>16)-128,E[st]=(I[dt+1280>>0]+I[fn+1536>>0]+I[zt+1792>>0]>>16)-128;at=We(S,o,at,l,d),ze=We(k,c,ze,u,p),Le=We(E,c,Le,u,p),St+=32}Bt+=8}if(w>=0){var At=[];At[1]=w+1,At[0]=(1<<w+1)-1,X(At)}if(ne(65497),typeof NP>"u")return new Uint8Array(v);return Buffer.from(v);var Ke,rn};function Ae(oe){if(oe<=0&&(oe=1),oe>100&&(oe=100),j!=oe){var Me=0;oe<50?Me=Math.floor(5e3/oe):Me=Math.floor(200-oe*2),$(Me),j=oe}}a(Ae,"setQuality");function xe(){var oe=new Date().getTime();e||(e=50),tt(),P(),G(),Y(),Ae(e);var Me=new Date().getTime()-oe}a(xe,"init"),xe()}a(iSt,"JPEGEncoder");typeof NP<"u"?NP.exports=s_e:typeof window<"u"&&(window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=s_e);function s_e(e,t){typeof t>"u"&&(t=50);var n=new iSt(t),r=n.encode(e,t);return{data:r,width:e.width,height:e.height}}a(s_e,"encode")});var l_e=we((V7n,UK)=>{var qK=a((function(){"use strict";var t=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),n=4017,r=799,i=3406,s=2276,o=1567,c=3784,l=5793,u=2896;function d(){}a(d,"constructor");function p(w,S){for(var k=0,E=[],_,I,j=16;j>0&&!w[j-1];)j--;E.push({children:[],index:0});var D=E[0],L;for(_=0;_<j;_++){for(I=0;I<w[_];I++){for(D=E.pop(),D.children[D.index]=S[k];D.index>0;){if(E.length===0)throw new Error("Could not recreate Huffman Table");D=E.pop()}for(D.index++,E.push(D);E.length<=_;)E.push(L={children:[],index:0}),D.children[D.index]=L.children,D=L;k++}_+1<j&&(E.push(L={children:[],index:0}),D.children[D.index]=L.children,D=L)}return E[0].children}a(p,"buildHuffmanTable");function f(w,S,k,E,_,I,j,D,L,O){var V=k.precision,Q=k.samplesPerLine,A=k.scanLines,U=k.mcusPerLine,C=k.progressive,R=k.maxH,$=k.maxV,N=S,P=0,G=0;function Y(){if(G>0)return G--,P>>G&1;if(P=w[S++],P==255){var Re=w[S++];if(Re)throw new Error("unexpected marker: "+(P<<8|Re).toString(16))}return G=7,P>>>7}a(Y,"readBit");function X(Re){for(var St=Re,Bt;(Bt=Y())!==null;){if(St=St[Bt],typeof St=="number")return St;if(typeof St!="object")throw new Error("invalid huffman sequence")}return null}a(X,"decodeHuffman");function z(Re){for(var St=0;Re>0;){var Bt=Y();if(Bt===null)return;St=St<<1|Bt,Re--}return St}a(z,"receive");function ne(Re){var St=z(Re);return St>=1<<Re-1?St:St+(-1<<Re)+1}a(ne,"receiveAndExtend");function ye(Re,St){var Bt=X(Re.huffmanTableDC),dt=Bt===0?0:ne(Bt);St[0]=Re.pred+=dt;for(var fn=1;fn<64;){var zt=X(Re.huffmanTableAC),Lt=zt&15,ae=zt>>4;if(Lt===0){if(ae<15)break;fn+=16;continue}fn+=ae;var Ne=t[fn];St[Ne]=ne(Lt),fn++}}a(ye,"decodeBaseline");function ve(Re,St){var Bt=X(Re.huffmanTableDC),dt=Bt===0?0:ne(Bt)<<L;St[0]=Re.pred+=dt}a(ve,"decodeDCFirst");function le(Re,St){St[0]|=Y()<<L}a(le,"decodeDCSuccessive");var ke=0;function Ee(Re,St){if(ke>0){ke--;return}for(var Bt=I,dt=j;Bt<=dt;){var fn=X(Re.huffmanTableAC),zt=fn&15,Lt=fn>>4;if(zt===0){if(Lt<15){ke=z(Lt)+(1<<Lt)-1;break}Bt+=16;continue}Bt+=Lt;var ae=t[Bt];St[ae]=ne(zt)*(1<<L),Bt++}}a(Ee,"decodeACFirst");var ue=0,de;function rt(Re,St){for(var Bt=I,dt=j,fn=0;Bt<=dt;){var zt=t[Bt],Lt=St[zt]<0?-1:1;switch(ue){case 0:var ae=X(Re.huffmanTableAC),Ne=ae&15,fn=ae>>4;if(Ne===0)fn<15?(ke=z(fn)+(1<<fn),ue=4):(fn=16,ue=1);else{if(Ne!==1)throw new Error("invalid ACn encoding");de=ne(Ne),ue=fn?2:3}continue;case 1:case 2:St[zt]?St[zt]+=(Y()<<L)*Lt:(fn--,fn===0&&(ue=ue==2?3:0));break;case 3:St[zt]?St[zt]+=(Y()<<L)*Lt:(St[zt]=de<<L,ue=0);break;case 4:St[zt]&&(St[zt]+=(Y()<<L)*Lt);break}Bt++}ue===4&&(ke--,ke===0&&(ue=0))}a(rt,"decodeACSuccessive");function We(Re,St,Bt,dt,fn){var zt=Bt/U|0,Lt=Bt%U,ae=zt*Re.v+dt,Ne=Lt*Re.h+fn;Re.blocks[ae]===void 0&&O.tolerantDecoding||St(Re,Re.blocks[ae][Ne])}a(We,"decodeMcu");function tt(Re,St,Bt){var dt=Bt/Re.blocksPerLine|0,fn=Bt%Re.blocksPerLine;Re.blocks[dt]===void 0&&O.tolerantDecoding||St(Re,Re.blocks[dt][fn])}a(tt,"decodeBlock");var Ae=E.length,xe,oe,Me,Se,at,ze;C?I===0?ze=D===0?ve:le:ze=D===0?Ee:rt:ze=ye;var Le=0,gt,nt;Ae==1?nt=E[0].blocksPerLine*E[0].blocksPerColumn:nt=U*k.mcusPerColumn,_||(_=nt);for(var Ve,ht;Le<nt;){for(oe=0;oe<Ae;oe++)E[oe].pred=0;if(ke=0,Ae==1)for(xe=E[0],at=0;at<_;at++)tt(xe,ze,Le),Le++;else for(at=0;at<_;at++){for(oe=0;oe<Ae;oe++)for(xe=E[oe],Ve=xe.h,ht=xe.v,Me=0;Me<ht;Me++)for(Se=0;Se<Ve;Se++)We(xe,ze,Le,Me,Se);if(Le++,Le===nt)break}if(Le===nt)do{if(w[S]===255&&w[S+1]!==0)break;S+=1}while(S<w.length-2);if(G=0,gt=w[S]<<8|w[S+1],gt<65280)throw new Error("marker was not found");if(gt>=65488&&gt<=65495)S+=2;else break}return S-N}a(f,"decodeScan");function h(w,S){var k=[],E=S.blocksPerLine,_=S.blocksPerColumn,I=E<<3,j=new Int32Array(64),D=new Uint8Array(64);function L(N,P,G){var Y=S.quantizationTable,X,z,ne,ye,ve,le,ke,Ee,ue,de=G,rt;for(rt=0;rt<64;rt++)de[rt]=N[rt]*Y[rt];for(rt=0;rt<8;++rt){var We=8*rt;if(de[1+We]==0&&de[2+We]==0&&de[3+We]==0&&de[4+We]==0&&de[5+We]==0&&de[6+We]==0&&de[7+We]==0){ue=l*de[0+We]+512>>10,de[0+We]=ue,de[1+We]=ue,de[2+We]=ue,de[3+We]=ue,de[4+We]=ue,de[5+We]=ue,de[6+We]=ue,de[7+We]=ue;continue}X=l*de[0+We]+128>>8,z=l*de[4+We]+128>>8,ne=de[2+We],ye=de[6+We],ve=u*(de[1+We]-de[7+We])+128>>8,Ee=u*(de[1+We]+de[7+We])+128>>8,le=de[3+We]<<4,ke=de[5+We]<<4,ue=X-z+1>>1,X=X+z+1>>1,z=ue,ue=ne*c+ye*o+128>>8,ne=ne*o-ye*c+128>>8,ye=ue,ue=ve-ke+1>>1,ve=ve+ke+1>>1,ke=ue,ue=Ee+le+1>>1,le=Ee-le+1>>1,Ee=ue,ue=X-ye+1>>1,X=X+ye+1>>1,ye=ue,ue=z-ne+1>>1,z=z+ne+1>>1,ne=ue,ue=ve*s+Ee*i+2048>>12,ve=ve*i-Ee*s+2048>>12,Ee=ue,ue=le*r+ke*n+2048>>12,le=le*n-ke*r+2048>>12,ke=ue,de[0+We]=X+Ee,de[7+We]=X-Ee,de[1+We]=z+ke,de[6+We]=z-ke,de[2+We]=ne+le,de[5+We]=ne-le,de[3+We]=ye+ve,de[4+We]=ye-ve}for(rt=0;rt<8;++rt){var tt=rt;if(de[8+tt]==0&&de[16+tt]==0&&de[24+tt]==0&&de[32+tt]==0&&de[40+tt]==0&&de[48+tt]==0&&de[56+tt]==0){ue=l*G[rt+0]+8192>>14,de[0+tt]=ue,de[8+tt]=ue,de[16+tt]=ue,de[24+tt]=ue,de[32+tt]=ue,de[40+tt]=ue,de[48+tt]=ue,de[56+tt]=ue;continue}X=l*de[0+tt]+2048>>12,z=l*de[32+tt]+2048>>12,ne=de[16+tt],ye=de[48+tt],ve=u*(de[8+tt]-de[56+tt])+2048>>12,Ee=u*(de[8+tt]+de[56+tt])+2048>>12,le=de[24+tt],ke=de[40+tt],ue=X-z+1>>1,X=X+z+1>>1,z=ue,ue=ne*c+ye*o+2048>>12,ne=ne*o-ye*c+2048>>12,ye=ue,ue=ve-ke+1>>1,ve=ve+ke+1>>1,ke=ue,ue=Ee+le+1>>1,le=Ee-le+1>>1,Ee=ue,ue=X-ye+1>>1,X=X+ye+1>>1,ye=ue,ue=z-ne+1>>1,z=z+ne+1>>1,ne=ue,ue=ve*s+Ee*i+2048>>12,ve=ve*i-Ee*s+2048>>12,Ee=ue,ue=le*r+ke*n+2048>>12,le=le*n-ke*r+2048>>12,ke=ue,de[0+tt]=X+Ee,de[56+tt]=X-Ee,de[8+tt]=z+ke,de[48+tt]=z-ke,de[16+tt]=ne+le,de[40+tt]=ne-le,de[24+tt]=ye+ve,de[32+tt]=ye-ve}for(rt=0;rt<64;++rt){var Ae=128+(de[rt]+8>>4);P[rt]=Ae<0?0:Ae>255?255:Ae}}a(L,"quantizeAndInverse"),x(I*_*8);for(var O,V,Q=0;Q<_;Q++){var A=Q<<3;for(O=0;O<8;O++)k.push(new Uint8Array(I));for(var U=0;U<E;U++){L(S.blocks[Q][U],D,j);var C=0,R=U<<3;for(V=0;V<8;V++){var $=k[A+V];for(O=0;O<8;O++)$[R+O]=D[C++]}}}return k}a(h,"buildComponentData");function g(w){return w<0?0:w>255?255:w}a(g,"clampTo8bit"),d.prototype={load:a(function(S){var k=new XMLHttpRequest;k.open("GET",S,!0),k.responseType="arraybuffer",k.onload=(function(){var E=new Uint8Array(k.response||k.mozResponseArrayBuffer);this.parse(E),this.onload&&this.onload()}).bind(this),k.send(null)},"load"),parse:a(function(S){var k=this.opts.maxResolutionInMP*1e3*1e3,E=0,_=S.length;function I(){var ae=S[E]<<8|S[E+1];return E+=2,ae}a(I,"readUint16");function j(){var ae=I(),Ne=S.subarray(E,E+ae-2);return E+=Ne.length,Ne}a(j,"readDataBlock");function D(ae){var Ne=1,He=1,st,At;for(At in ae.components)ae.components.hasOwnProperty(At)&&(st=ae.components[At],Ne<st.h&&(Ne=st.h),He<st.v&&(He=st.v));var Ke=Math.ceil(ae.samplesPerLine/8/Ne),rn=Math.ceil(ae.scanLines/8/He);for(At in ae.components)if(ae.components.hasOwnProperty(At)){st=ae.components[At];var Qt=Math.ceil(Math.ceil(ae.samplesPerLine/8)*st.h/Ne),hn=Math.ceil(Math.ceil(ae.scanLines/8)*st.v/He),Pt=Ke*st.h,Rr=rn*st.v,Pr=Rr*Pt,is=[];x(Pr*256);for(var ki=0;ki<Rr;ki++){for(var or=[],ss=0;ss<Pt;ss++)or.push(new Int32Array(64));is.push(or)}st.blocksPerLine=Qt,st.blocksPerColumn=hn,st.blocks=is}ae.maxH=Ne,ae.maxV=He,ae.mcusPerLine=Ke,ae.mcusPerColumn=rn}a(D,"prepareComponents");var L=null,O=null,V=null,Q,A,U=[],C=[],R=[],$=[],N=I(),P=-1;if(this.comments=[],N!=65496)throw new Error("SOI not found");for(N=I();N!=65497;){var G,Y,X;switch(N){case 65280:break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var z=j();if(N===65534){var ne=String.fromCharCode.apply(null,z);this.comments.push(ne)}N===65504&&z[0]===74&&z[1]===70&&z[2]===73&&z[3]===70&&z[4]===0&&(L={version:{major:z[5],minor:z[6]},densityUnits:z[7],xDensity:z[8]<<8|z[9],yDensity:z[10]<<8|z[11],thumbWidth:z[12],thumbHeight:z[13],thumbData:z.subarray(14,14+3*z[12]*z[13])}),N===65505&&z[0]===69&&z[1]===120&&z[2]===105&&z[3]===102&&z[4]===0&&(this.exifBuffer=z.subarray(5,z.length)),N===65518&&z[0]===65&&z[1]===100&&z[2]===111&&z[3]===98&&z[4]===101&&z[5]===0&&(O={version:z[6],flags0:z[7]<<8|z[8],flags1:z[9]<<8|z[10],transformCode:z[11]});break;case 65499:for(var ye=I(),ve=ye+E-2;E<ve;){var le=S[E++];x(256);var ke=new Int32Array(64);if(le>>4===0)for(Y=0;Y<64;Y++){var Ee=t[Y];ke[Ee]=S[E++]}else if(le>>4===1)for(Y=0;Y<64;Y++){var Ee=t[Y];ke[Ee]=I()}else throw new Error("DQT: invalid table spec");U[le&15]=ke}break;case 65472:case 65473:case 65474:I(),Q={},Q.extended=N===65473,Q.progressive=N===65474,Q.precision=S[E++],Q.scanLines=I(),Q.samplesPerLine=I(),Q.components={},Q.componentsOrder=[];var ue=Q.scanLines*Q.samplesPerLine;if(ue>k){var de=Math.ceil((ue-k)/1e6);throw new Error(`maxResolutionInMP limit exceeded by ${de}MP`)}var rt=S[E++],We,tt=0,Ae=0;for(G=0;G<rt;G++){We=S[E];var xe=S[E+1]>>4,oe=S[E+1]&15,Me=S[E+2];if(xe<=0||oe<=0)throw new Error("Invalid sampling factor, expected values above 0");Q.componentsOrder.push(We),Q.components[We]={h:xe,v:oe,quantizationIdx:Me},E+=3}D(Q),C.push(Q);break;case 65476:var Se=I();for(G=2;G<Se;){var at=S[E++],ze=new Uint8Array(16),Le=0;for(Y=0;Y<16;Y++,E++)Le+=ze[Y]=S[E];x(16+Le);var gt=new Uint8Array(Le);for(Y=0;Y<Le;Y++,E++)gt[Y]=S[E];G+=17+Le,(at>>4===0?$:R)[at&15]=p(ze,gt)}break;case 65501:I(),A=I();break;case 65500:I(),I();break;case 65498:var nt=I(),Ve=S[E++],ht=[],Re;for(G=0;G<Ve;G++){Re=Q.components[S[E++]];var St=S[E++];Re.huffmanTableDC=$[St>>4],Re.huffmanTableAC=R[St&15],ht.push(Re)}var Bt=S[E++],dt=S[E++],fn=S[E++],zt=f(S,E,Q,ht,A,Bt,dt,fn>>4,fn&15,this.opts);E+=zt;break;case 65535:S[E]!==255&&E--;break;default:if(S[E-3]==255&&S[E-2]>=192&&S[E-2]<=254){E-=3;break}else if(N===224||N==225){if(P!==-1)throw new Error(`first unknown JPEG marker at offset ${P.toString(16)}, second unknown JPEG marker ${N.toString(16)} at offset ${(E-1).toString(16)}`);P=E-1;let ae=I();if(S[E+ae-2]===255){E+=ae-2;break}}throw new Error("unknown JPEG marker "+N.toString(16))}N=I()}if(C.length!=1)throw new Error("only single frame JPEGs supported");for(var G=0;G<C.length;G++){var Lt=C[G].components;for(var Y in Lt)Lt[Y].quantizationTable=U[Lt[Y].quantizationIdx],delete Lt[Y].quantizationIdx}this.width=Q.samplesPerLine,this.height=Q.scanLines,this.jfif=L,this.adobe=O,this.components=[];for(var G=0;G<Q.componentsOrder.length;G++){var Re=Q.components[Q.componentsOrder[G]];this.components.push({lines:h(Q,Re),scaleX:Re.h/Q.maxH,scaleY:Re.v/Q.maxV})}},"parse"),getData:a(function(S,k){var E=this.width/S,_=this.height/k,I,j,D,L,O,V,Q,A,U,C,R=0,$,N,P,G,Y,X,z,ne,ye,ve,le,ke=S*k*this.components.length;x(ke);var Ee=new Uint8Array(ke);switch(this.components.length){case 1:for(I=this.components[0],C=0;C<k;C++)for(O=I.lines[0|C*I.scaleY*_],U=0;U<S;U++)$=O[0|U*I.scaleX*E],Ee[R++]=$;break;case 2:for(I=this.components[0],j=this.components[1],C=0;C<k;C++)for(O=I.lines[0|C*I.scaleY*_],V=j.lines[0|C*j.scaleY*_],U=0;U<S;U++)$=O[0|U*I.scaleX*E],Ee[R++]=$,$=V[0|U*j.scaleX*E],Ee[R++]=$;break;case 3:for(le=!0,this.adobe&&this.adobe.transformCode?le=!0:typeof this.opts.colorTransform<"u"&&(le=!!this.opts.colorTransform),I=this.components[0],j=this.components[1],D=this.components[2],C=0;C<k;C++)for(O=I.lines[0|C*I.scaleY*_],V=j.lines[0|C*j.scaleY*_],Q=D.lines[0|C*D.scaleY*_],U=0;U<S;U++)le?($=O[0|U*I.scaleX*E],N=V[0|U*j.scaleX*E],P=Q[0|U*D.scaleX*E],ne=g($+1.402*(P-128)),ye=g($-.3441363*(N-128)-.71413636*(P-128)),ve=g($+1.772*(N-128))):(ne=O[0|U*I.scaleX*E],ye=V[0|U*j.scaleX*E],ve=Q[0|U*D.scaleX*E]),Ee[R++]=ne,Ee[R++]=ye,Ee[R++]=ve;break;case 4:if(!this.adobe)throw new Error("Unsupported color mode (4 components)");for(le=!1,this.adobe&&this.adobe.transformCode?le=!0:typeof this.opts.colorTransform<"u"&&(le=!!this.opts.colorTransform),I=this.components[0],j=this.components[1],D=this.components[2],L=this.components[3],C=0;C<k;C++)for(O=I.lines[0|C*I.scaleY*_],V=j.lines[0|C*j.scaleY*_],Q=D.lines[0|C*D.scaleY*_],A=L.lines[0|C*L.scaleY*_],U=0;U<S;U++)le?($=O[0|U*I.scaleX*E],N=V[0|U*j.scaleX*E],P=Q[0|U*D.scaleX*E],G=A[0|U*L.scaleX*E],Y=255-g($+1.402*(P-128)),X=255-g($-.3441363*(N-128)-.71413636*(P-128)),z=255-g($+1.772*(N-128))):(Y=O[0|U*I.scaleX*E],X=V[0|U*j.scaleX*E],z=Q[0|U*D.scaleX*E],G=A[0|U*L.scaleX*E]),Ee[R++]=255-Y,Ee[R++]=255-X,Ee[R++]=255-z,Ee[R++]=255-G;break;default:throw new Error("Unsupported color mode")}return Ee},"getData"),copyToImageData:a(function(S,k){var E=S.width,_=S.height,I=S.data,j=this.getData(E,_),D=0,L=0,O,V,Q,A,U,C,R,$,N;switch(this.components.length){case 1:for(V=0;V<_;V++)for(O=0;O<E;O++)Q=j[D++],I[L++]=Q,I[L++]=Q,I[L++]=Q,k&&(I[L++]=255);break;case 3:for(V=0;V<_;V++)for(O=0;O<E;O++)R=j[D++],$=j[D++],N=j[D++],I[L++]=R,I[L++]=$,I[L++]=N,k&&(I[L++]=255);break;case 4:for(V=0;V<_;V++)for(O=0;O<E;O++)U=j[D++],C=j[D++],Q=j[D++],A=j[D++],R=255-g(U*(1-A/255)+A),$=255-g(C*(1-A/255)+A),N=255-g(Q*(1-A/255)+A),I[L++]=R,I[L++]=$,I[L++]=N,k&&(I[L++]=255);break;default:throw new Error("Unsupported color mode")}},"copyToImageData")};var y=0,v=0;function x(w=0){var S=y+w;if(S>v){var k=Math.ceil((S-v)/1024/1024);throw new Error(`maxMemoryUsageInMB limit exceeded by at least ${k}MB`)}y=S}return a(x,"requestMemoryAllocation"),d.resetMaxMemoryUsage=function(w){y=0,v=w},d.getBytesAllocated=function(){return y},d.requestMemoryAllocation=x,d}),"jpegImage")();typeof UK<"u"?UK.exports=c_e:typeof window<"u"&&(window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=c_e);function c_e(e,t={}){var n={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512},r={...n,...t},i=new Uint8Array(e),s=new qK;s.opts=r,qK.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),s.parse(i);var o=r.formatAsRGBA?4:3,c=s.width*s.height*o;try{qK.requestMemoryAllocation(c);var l={width:s.width,height:s.height,exifBuffer:s.exifBuffer,data:r.useTArray?new Uint8Array(c):Buffer.alloc(c)};s.comments.length>0&&(l.comments=s.comments)}catch(u){throw u instanceof RangeError?new Error("Could not allocate enough memory for the image. Required: "+c):u instanceof ReferenceError&&u.message==="Buffer is not defined"?new Error("Buffer is not globally defined in this environment. Consider setting useTArray to true"):u}return s.copyToImageData(l,r.formatAsRGBA),l}a(c_e,"decode")});var d_e=we((Z7n,u_e)=>{var sSt=a_e(),oSt=l_e();u_e.exports={encode:sSt,decode:oSt}});function j_e(e,t){let n=0,r=0,s=a(o=>{let c;for(let[l,u]of o.entries()){let d=u;if(u.type==="image"){if(n===t[r]){if(u.offloaded===!0)throw new Error(`image/offload: image index ${n} is already offloaded`);d={...u,offloaded:!0},r+=1}n+=1}d!==u&&(c??=o.slice(0,l)),c?.push(d)}return c??o},"visit")(e.content);if(r!==t.length)throw new Error(`image/offload: image index ${t[r]} does not exist`);return pn({...e,content:s})}var F_e=ce(()=>{cs();a(j_e,"offloadMessageImages")});function q_e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function U_e(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0&&!Object.is(e,-0)}var zP,tJ=ce(()=>{F_e();a(q_e,"isRecord");a(U_e,"isIndex");zP={type:"image/offload",project(e,t){let n=e.data;if(!q_e(n)||Object.keys(n).length!==1||!Array.isArray(n.targets)||n.targets.length===0)throw new Error("image/offload: data must contain a nonempty targets array");let r=new Map,i=new Set(t.nodes);for(let s of n.targets){if(!q_e(s)||Object.keys(s).length!==2||!U_e(s.seq)||!Array.isArray(s.imageIndexes)||s.imageIndexes.length===0)throw new Error("image/offload: each target must contain a seq and nonempty imageIndexes");let o=s.seq;if(r.has(o))throw new Error(`image/offload: duplicate target seq ${o}`);if(!i.has(o))throw new Error(`image/offload: target seq ${o} is not a current surface node`);let c=t.events[o-t.baseSeq];if(c?.type!=="user/message"&&c?.type!=="tool/result")throw new Error(`image/offload: target seq ${o} must be user/message or tool/result`);let l=-1;for(let d of s.imageIndexes){if(!U_e(d)||d<=l)throw new Error("image/offload: imageIndexes must be strictly increasing non-negative safe integers");l=d}let u=t.messages.get(o)??(c.type==="user/message"?c.data:c.data.message);r.set(o,j_e(u,s.imageIndexes))}return r}}});var r4,oTe=ce(()=>{tJ();r4=[zP]});async function fTe(e,t,n){let r=n===void 0?void 0:{signal:n},i=await e.open(t,"read",r),s;try{s=await i.read(0,void 0,r)}catch(c){try{await i.close()}catch{}throw c}await i.close();let{events:o}=s;return{eventState:s.eventState,header:i.header,inheritedEventCount:i.inheritedEventCount,events:[...o,...CR(o)]}}function LJ(e,t){if(e.id!==t.id||e.createdAt!==t.createdAt||e.cwd!==t.cwd||e.parentSession!==t.parentSession||e.isSeeded!==t.isSeeded||(e.delegationDepth??0)!==(t.delegationDepth??0))throw new Ir(`session source headers conflict for session "${e.id}"`,"SESSION_QUERY_SOURCE_CONFLICT")}function i4(e,t,n,r){try{r?.throwIfAborted();let i=n(t);return r?.throwIfAborted(),{sessionId:e,status:"fulfilled",value:i}}catch(i){return r?.aborted&&r.throwIfAborted(),{sessionId:e,status:"rejected",reason:i}}}function jJ(e){return{header:e.header,events:e.snapshotEvents()}}function s4(e,t){return e.map(n=>t.get(n))}async function FJ(e,t){try{return(await e.list(t===void 0?void 0:{signal:t})).map(n=>n.header)}catch(n){throw t?.aborted&&t.throwIfAborted(),new Ir(`session persistence listing failed: ${zJ(n)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:n})}}async function aTe(e,t,n){try{return await fTe(e,t,n)}catch(r){throw n?.aborted&&n.throwIfAborted(),r instanceof Error&&r.name==="SessionPersistenceCorruptionError"?new Ir(`stored session "${t}" is corrupt: ${zJ(r)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:r}):new Ir(`failed to read stored session "${t}": ${zJ(r)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:r})}}function cTe(e){return{header:structuredClone(e.header),inheritedEventCount:e.inheritedEventCount,events:e.snapshotEvents().map(t=>structuredClone(t))}}function j_t(e,t){return t.header.createdAt-e.header.createdAt||e.header.id.localeCompare(t.header.id)}function o4(e){return new Ir(`session "${e}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND")}function zJ(e){return e instanceof Error?e.message:"unknown error"}function CT(e){if(e?.aborted===!0)throw new Ir("session observation was aborted","SESSION_QUERY_ABORTED",{cause:e.reason})}function lTe(e,t){return uTe(t,"SessionPersistenceNotFoundError")?BJ(e,t):uTe(t,"SessionPersistenceCorruptionError")?new Ir(`stored session "${e}" is corrupt: ${t.message}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:t}):new Ir(`failed to observe session "${e}": ${a4(t)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:t})}function BJ(e,t){return new Ir(`session "${e}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND",t===void 0?void 0:{cause:t})}function a4(e){return e instanceof Error?e.message:"unknown error"}function uTe(e,t){return e instanceof Error&&e.name===t}function q_t(e){switch(e.type){case"user/message":return qJ(e.data.content);case"assistant/message":return qJ(e.data.message.content);case"tool/call":return RT([e.data.name,e.data.arguments]);case"tool/result":return RT([qJ(e.data.message.content),e.data.error?.name??"",e.data.error?.code??""]);case"todo/write":return RT(e.data.todos.flatMap(t=>[t.status,t.content]));case"turn/end":return U_t(e.data.reason);case"turn/start":case"step/start":case"step/end":case"assistant/attempt":case"request/header":return"";default:return""}}function U_t(e){switch(e.kind){case"error":return RT(["error",e.error.message]);case"aborted":return"aborted";case"max-tokens":case"interrupted":return e.kind;case"completed":return"";default:return""}}function qJ(e){return RT(e.flatMap(z_t))}function z_t(e){switch(e.type){case"text":return[e.text];case"reasoning":return[];case"tool-call":return[e.name,e.arguments];default:return[]}}function RT(e){return e.map(t=>t.trim()).filter(Boolean).join(`
157
157
  `)}function HJ(e,t){let n=B_t(t),r=[];for(let i of t){let s=q_t(i);s.length!==0&&r.push({sessionId:e,seq:i.seq,type:i.type,time:i.time,surface:n.get(i.seq)??"log-only",text:s})}return r}function B_t(e){let t;try{t=s5(e,r4)}catch(r){throw new Ir(`invalid session surface: ${r instanceof Error?r.message:"unknown error"}`,"SESSION_QUERY_INVALID_SURFACE",{cause:r})}let n=new Map;for(let r of t.nodes)n.set(r,"current");for(let r of t.replacements)for(let i of r.shadowedSeqs)n.set(i,"shadowed");return n}function VJ(e,t=[]){let n=t.map(H_t);return e.filter(r=>n.every(i=>i(r)))}function d4(e,t=[]){let n=t.map(V_t);return e.filter(r=>n.every(i=>i(r)))}function GJ(e){return hTe(e),e.map(t=>{switch(t.kind){case"id":return{kind:t.kind,values:l4(t.kind,t.values)};case"cwd":return{kind:t.kind,values:dTe(t.kind,t.values)};case"created-at":return mTe(t.kind,t);case"parent":return{kind:t.kind,values:dTe(t.kind,t.values)};case"availability":{let n=l4(t.kind,t.values);return h4(t.kind,n,["live","persisted"]),{kind:t.kind,values:n}}default:return f4(t)}})}function p4(e){return hTe(e),e.map(t=>{switch(t.kind){case"seq":case"time":return mTe(t.kind,t);case"type":return{kind:t.kind,values:l4(t.kind,t.values)};case"surface":{let n=l4(t.kind,t.values);return h4(t.kind,n,["current","shadowed","log-only"]),{kind:t.kind,values:n}}case"text":if(typeof t.text!="string")throw lx("text filter text must be a string");return{kind:t.kind,text:t.text};default:return f4(t)}})}function W_t(e){let t=e.trim();if(t.length===0)throw new Ir("session text filter must contain non-whitespace text","SESSION_QUERY_INVALID_FILTER");let n=t.split(/\s+/u).map(r=>r.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")).join("\\s+");return new RegExp(n,"iu")}function H_t(e){switch(e.kind){case"id":return t=>e.values.includes(t.header.id);case"cwd":return t=>e.values.includes(t.header.cwd??null);case"created-at":{let t=u4(e.kind,e);return n=>WJ(n.header.createdAt,t)}case"parent":return t=>e.values.includes(t.header.parentSession??null);case"availability":return h4(e.kind,e.values,["live","persisted"]),t=>e.values.some(n=>n==="live"?t.live:t.persisted);default:return f4(e)}}function V_t(e){switch(e.kind){case"seq":{let t=u4(e.kind,e);return n=>WJ(n.seq,t)}case"time":{let t=u4(e.kind,e);return n=>WJ(n.time,t)}case"type":return t=>e.values.includes(t.type);case"surface":return h4(e.kind,e.values,["current","shadowed","log-only"]),t=>e.values.includes(t.surface);case"text":{let t=W_t(e.text);return n=>t.test(n.text)}default:return f4(e)}}function l4(e,t){if(!gTe(t)||t.some(n=>typeof n!="string"))throw lx(`${e} filter values must be an array of strings`);return[...t]}function hTe(e){if(!Array.isArray(e))throw lx("filters must be an array")}function dTe(e,t){if(!gTe(t)||t.some(n=>n!==null&&typeof n!="string"))throw lx(`${e} filter values must be an array of strings or null`);return[...t]}function mTe(e,t){let n={kind:e,...t.from===void 0?{}:{from:t.from},...t.to===void 0?{}:{to:t.to}};return u4(e,n),n}function f4(e){let t=e.kind;throw lx(`unknown filter kind ${typeof t=="string"?`"${t}"`:"(missing)"}`)}function h4(e,t,n){for(let r of t)if(!n.includes(r))throw new Ir(`session ${e} filter contains unknown value "${r}"`,"SESSION_QUERY_INVALID_FILTER")}function u4(e,t){if(t.from!==void 0&&!Number.isFinite(t.from))throw UJ(e,"from must be finite");if(t.to!==void 0&&!Number.isFinite(t.to))throw UJ(e,"to must be finite");if(t.from!==void 0&&t.to!==void 0&&t.from>t.to)throw UJ(e,"from must be less than or equal to to");return t}function WJ(e,t){return(t.from===void 0||e>=t.from)&&(t.to===void 0||e<=t.to)}function UJ(e,t){return lx(`${e} filter ${t}`)}function lx(e){return new Ir(`session ${e}`,"SESSION_QUERY_INVALID_FILTER")}function gTe(e){return Array.isArray(e)}function G_t(e,t){return ZJ(e,t).records}function Z_t(e,t){return ZJ(e,t).currentSeqs.map(n=>{let r=t[n];if(r===void 0||r.seq!==n||!rg(r))throw new Ir(`invalid session surface: current node ${n} is not a surface event`,"SESSION_QUERY_INVALID_SURFACE");return vE(r)})}function K_t(e,t,n){let r=t[n];if(r===void 0||r.seq!==n)throw new Ir(`session "${e}" has no event at seq ${n}`,"SESSION_QUERY_EVENT_NOT_FOUND");let i=ZJ(e,t),s=[],o=i.replacedBy.get(n);for(;o!==void 0;)s.push(o),o=i.replacedBy.get(o);let c=[];for(let d of t)d.seq<=n||pTe(d).includes(n)&&c.push(d.seq);let l=i.records[n],u=i.replacedBy.get(n);return{target:l,...u===void 0?{}:{replacedBy:u},replacementChain:s,replacedEventSeqs:i.replacedEventSeqs.get(n)??[],sourceEventSeqs:[...pTe(r)],derivedEventSeqs:c}}function J_t(e,t){let n=new Map(e.map(p=>[p.header.id,p])),r=n.get(t);if(r===void 0)throw new Ir(`session "${t}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND");let i=[],s=new Set([t]),o,c=r.header.parentSession;for(;c!==void 0;){if(s.has(c))throw new Ir(`session lineage contains a cycle at "${c}"`,"SESSION_QUERY_INVALID_LINEAGE");s.add(c);let p=n.get(c);if(p===void 0){o=c;break}i.push(p),c=p.header.parentSession}let l=new Map;for(let p of e){let f=p.header.parentSession;if(f===void 0)continue;let h=l.get(f)??[];h.push(p),l.set(f,h)}for(let p of l.values())p.sort((f,h)=>f.header.createdAt-h.header.createdAt||f.header.id.localeCompare(h.header.id));let u=Y_t(l,t),d={target:c4(r),ancestors:i.map(c4),descendants:u};return o!==void 0?{...d,complete:!1,unresolvedParentId:o}:{...d,complete:!0,root:c4(i.at(-1)??r)}}function ZJ(e,t){let n;try{n=s5(t,r4)}catch(o){throw new Ir(`invalid session surface: ${o instanceof Error?o.message:"unknown error"}`,"SESSION_QUERY_INVALID_SURFACE",{cause:o})}let r=new Set(n.nodes),i=new Map,s=new Map;for(let o of n.replacements){let c=o.shadowedSeqs;s.set(o.seq,c);for(let l of c)i.set(l,o.seq)}return{records:t.map(o=>({sessionId:e,seq:o.seq,type:o.type,time:o.time,surface:r.has(o.seq)?"current":i.has(o.seq)?"shadowed":"log-only"})),replacedBy:i,replacedEventSeqs:s,currentSeqs:[...n.nodes]}}function pTe(e){return e.sourceEventSeqs??[]}function Y_t(e,t){let n=[],r=[{sessionId:t,descendants:n}];for(;r.length>0;){let i=r.pop(),s=[];for(let o of e.get(i.sessionId)??[]){let c={session:c4(o),descendants:[]};s.push(c),i.descendants.push(c)}for(let o=s.length-1;o>=0;o-=1){let c=s[o];r.push({sessionId:c.session.header.id,descendants:c.descendants})}}return n}function c4(e){return{...e,header:structuredClone(e.header)}}var Ir,L_t,F_t,yTe,KJ=ce(()=>{oTe();Bn();Zs();kg();kr();Ir=class extends Kr{static{a(this,"SessionQueryError")}constructor(e,t,n){super(e,t,n)}};a(fTe,"readColdSessionLog");a(LJ,"assertSessionHeadersCompatible");L_t=class{static{a(this,"SessionCorpus")}_ctx;_persistedReadConcurrency;_persistence;_optionalPersistenceFiber;constructor(e,t){this._ctx=e,this._persistedReadConcurrency=t,this._optionalPersistenceFiber=e.inject(["sessionPersistence"],n=>{let r=n.sessionPersistence;this._persistence=r,n.effect(()=>()=>{this._persistence===r&&(this._persistence=void 0)},"sessionQuery.persistenceBinding")}),e.effect(()=>()=>this._optionalPersistenceFiber.dispose(),"sessionQuery.optionalPersistence")}async listSessions(e){e?.throwIfAborted();let t=this._persistence,n=t===void 0?[]:await FJ(t,e);e?.throwIfAborted();let r=new Map;for(let i of n)r.set(i.id,{header:structuredClone(i),live:!1,persisted:!0});for(let i of this._ctx.sessions.list()){let s=r.get(i.id);s!==void 0&&LJ(i.header,s.header),r.set(i.id,{header:structuredClone(i.header),live:!0,persisted:s!==void 0})}return[...r.values()].sort(j_t)}async load(e,t){t?.throwIfAborted();let n=this._ctx.sessions.get(e);if(n!==void 0){let l=cTe(n);return t?.throwIfAborted(),l}let r=this._persistence;if(r===void 0)throw o4(e);let i=(await FJ(r,t)).find(l=>l.id===e);if(t?.throwIfAborted(),i===void 0)throw o4(e);let s=await aTe(r,e,t);t?.throwIfAborted();let o=this._ctx.sessions.get(e);if(o!==void 0){let l=cTe(o);return t?.throwIfAborted(),l}LJ(s.header,i);let c={header:structuredClone(s.header),inheritedEventCount:s.inheritedEventCount,events:s.events.map(l=>structuredClone(l))};return t?.throwIfAborted(),c}async projectMany(e,t,n){let r=[...new Set(e)];n?.throwIfAborted();let i=new Map,s=[];for(let g of r){let y=this._ctx.sessions.get(g);y===void 0?s.push(g):i.set(g,i4(g,jJ(y),t,n))}if(s.length===0)return s4(r,i);let o=this._persistence;if(o===void 0){for(let g of s)i.set(g,{sessionId:g,status:"rejected",reason:o4(g)});return s4(r,i)}let c;try{c=await FJ(o,n),n?.throwIfAborted()}catch(g){n?.aborted&&n.throwIfAborted();for(let y of s)i.set(y,{sessionId:y,status:"rejected",reason:g});return s4(r,i)}let l=new Map(c.map(g=>[g.id,g])),u=a(async g=>{let y=l.get(g);if(y===void 0){let v=this._ctx.sessions.get(g);i.set(g,v===void 0?{sessionId:g,status:"rejected",reason:o4(g)}:i4(g,jJ(v),t,n));return}try{n?.throwIfAborted();let v=await aTe(o,g,n);n?.throwIfAborted();let x=this._ctx.sessions.get(g);if(x!==void 0){i.set(g,i4(g,jJ(x),t,n));return}LJ(v.header,y),i.set(g,i4(g,{header:v.header,events:v.events},t,n))}catch(v){n?.aborted&&n.throwIfAborted(),i.set(g,{sessionId:g,status:"rejected",reason:v})}},"resolvePersisted"),d=0,p=a(async()=>{for(;;){n?.throwIfAborted();let g=d;if(g>=s.length)return;d+=1,await u(s[g])}},"worker"),f=Math.min(this._persistedReadConcurrency,s.length),h=await Promise.allSettled(Array.from({length:f},()=>p()));n?.aborted&&n.throwIfAborted();for(let g of h)if(g.status==="rejected")throw g.reason;return n?.throwIfAborted(),s4(r,i)}};a(i4,"projectSource");a(jJ,"sourceLive");a(s4,"orderedResults");a(FJ,"listPersisted");a(aTe,"inspectPersisted");a(cTe,"snapshotLive");a(j_t,"compareSessions");a(o4,"notFound$1");a(zJ,"errorMessage$1");F_t=class{static{a(this,"SessionObservationReader")}ctx;cacheCapacity;cache=new Map;constructor(e,t=5){this.ctx=e,this.cacheCapacity=t}async read(e,t={}){let{signal:n,projectionMode:r="all"}=t;for(;;){CT(n);let i=this.ctx.sessions.get(e);if(i!==void 0)return this.live(i,r);let s=this.ctx.get("sessionPersistence");if(s===void 0)throw BJ(e);let o=await this.statSource(s,e,n),c=this.ctx.sessions.get(e);if(c!==void 0)return this.live(c,r);let l=this.cachedEntry(s.identity,e,o.revision);if(l===void 0){let d=await this.loadSource(s,e,n);CT(n);let p=this.ctx.sessions.get(e);if(p!==void 0)return this.live(p,r);let f=d.events,h;try{h=this.ctx.sessions.prepare(e,{seed:f,meta:structuredClone(d.header),inheritedEventCount:d.inheritedEventCount,eventState:d.eventState})}catch(g){if(this.ctx.sessions.get(e)!==void 0)continue;throw new Ir(`stored session "${e}" is corrupt: ${a4(g)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:g})}l={persistenceIdentity:s.identity,revision:o.revision,session:h,events:Object.freeze(f),refs:0},this.store(e,l)}let u;try{u=r==="none"?void 0:this.preparedProjections(l)}catch(d){throw new Ir(`failed to project session "${e}": ${a4(d)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:d})}return this.preparedLease(e,l,u)}}async statSource(e,t,n){let r;try{r=await e.stat(t,n===void 0?void 0:{signal:n})}catch(i){throw CT(n),lTe(t,i)}if(CT(n),r===void 0)throw BJ(t);if(r.header.id!==t)throw new Ir(`session persistence returned "${r.header.id}" for "${t}"`,"SESSION_QUERY_SOURCE_CONFLICT");return r}async loadSource(e,t,n){try{return await fTe(e,t,n)}catch(r){throw CT(n),lTe(t,r)}}cachedEntry(e,t,n){let r=this.cache.get(t);if(!(r===void 0||r.persistenceIdentity!==e||r.revision!==n))return this.cache.delete(t),this.cache.set(t,r),r}store(e,t){this.cache.delete(e),this.cache.set(e,t),this.evictPastCapacity(t)}evictPastCapacity(e){if(!(this.cache.size<=this.cacheCapacity)){for(let[t,n]of this.cache)if(!(n===e||n.refs>0)&&(this.cache.delete(t),this.cache.size<=this.cacheCapacity))return}}preparedLease(e,t,n){t.refs+=1;let r=a(()=>{let i=!1;return{source:"prepared",header:t.session.header,inheritedEventCount:t.session.inheritedEventCount,events:t.events,cursor:t.events.at(-1)?.seq??-1,revision:t.revision,...n===void 0?{}:{projections:n},retain:a(()=>{if(i)throw new Error(`session observation "${e}" is disposed`);return t.refs+=1,r()},"retain"),[Symbol.dispose]:()=>{i||(i=!0,t.refs-=1,t.refs===0&&this.evictPastCapacity())}}},"lease");return r()}live(e,t){let n=e.seq,r,i;try{i=t==="none"?void 0:this.ctx.get("sessionProjections")?.snapshot(e)}catch(o){throw new Ir(`failed to project session "${e.id}": ${a4(o)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:o})}let s=a(()=>{let o=!1;return{source:"live",header:e.header,inheritedEventCount:e.inheritedEventCount,get events(){return r??=e.snapshotEvents(En(0),n),r},cursor:n===0?-1:sn(n-1),...i===void 0?{}:{projections:i},retain:a(()=>{if(o)throw new Error(`session observation "${e.id}" is disposed`);return s()},"retain"),[Symbol.dispose]:()=>{o=!0}}},"lease");return s()}preparedProjections(e){let t=this.ctx.get("sessionProjections");if(t===void 0)return;let n=this.ctx.get("sessionProjectionCache");return n===void 0?t.hydrate(e.session,{},e.events,En(0)):n.hydratePrepared(e.session,e.events)}};a(CT,"throwIfObservationAborted");a(lTe,"mapPersistenceFailure");a(BJ,"notFound");a(a4,"errorMessage");a(uTe,"hasErrorName");a(q_t,"extractSessionEventText");a(U_t,"turnEndText");a(qJ,"contentText");a(z_t,"blockText");a(RT,"joinText");a(HJ,"buildSessionEventSearchDocuments");a(B_t,"classifySurface");a(VJ,"filterSessionResults");a(d4,"filterSessionEventDocuments");a(GJ,"materializeSessionResultFilters");a(p4,"materializeSessionEventResultFilters");a(W_t,"compileSessionTextFilter");a(H_t,"sessionPredicate");a(V_t,"eventPredicate");a(l4,"copyStrings");a(hTe,"assertArray");a(dTe,"copyNullableStrings");a(mTe,"copyRange");a(f4,"unknownFilter");a(h4,"assertAllowedValues");a(u4,"validateRange");a(WJ,"matchesRange");a(UJ,"invalidRange");a(lx,"invalidFilter");a(gTe,"isRuntimeArray");a(G_t,"eventRecords");a(Z_t,"currentSurfaceEvents");a(K_t,"traceEvent");a(J_t,"traceSession");a(ZJ,"analyzeEventLog");a(pTe,"eventSources");a(Y_t,"buildDescendants");a(c4,"cloneRecord");yTe=class extends xt{static{a(this,"SessionQueryEngine")}static inject=["sessions"];_readWindowMax;_corpus;_observations;constructor(e,t={}){if(super(e,"sessionQuery"),this._readWindowMax=t.readWindowMax??50,!Number.isInteger(this._readWindowMax)||this._readWindowMax<0)throw new Ir("session-query: readWindowMax must be a non-negative integer","SESSION_QUERY_INVALID_CONFIG");let n=t.persistedReadConcurrency??4;if(!Number.isSafeInteger(n)||n<1)throw new Ir("session-query: persistedReadConcurrency must be a positive safe integer","SESSION_QUERY_INVALID_CONFIG");let r=t.preparedSessionCacheSize??5;if(!Number.isSafeInteger(r)||r<1)throw new Ir("session-query: preparedSessionCacheSize must be a positive safe integer","SESSION_QUERY_INVALID_CONFIG");this._corpus=new L_t(e,n),this._observations=new F_t(e,r)}observeSession(e,t={}){return this._observations.read(e,t)}listSessions(e){return this._corpus.listSessions(e)}async readSession(e){let t=await this._corpus.load(e);return m0.create(e,t.events,t.header,t.inheritedEventCount,r4),{session:structuredClone(t.header),inheritedEventCount:t.inheritedEventCount,events:t.events.map(vE)}}async filterSessions(e,t){let n=GJ(e);return this._filterSessions(n,t)}async readTitle(e,t){return(await this.readTitleSnapshot(e,t)).title}async readTitleSnapshot(e,t){let n=(await this.readTitleSnapshots([e],t))[0];if(n.status==="rejected")throw n.reason;return n.value}async readTitleSnapshots(e,t){return this._corpus.projectMany(e,n=>{let r=Sg(n.events);return{session:structuredClone(n.header),...r===void 0?{}:{title:r}}},t)}async listEvents(e){return G_t(e,(await this._corpus.load(e)).events)}async filterEvents(e,t){let n=p4(t);return this._filterEvents(e,n)}async _filterSessions(e,t){return VJ(await this._corpus.listSessions(t),e)}async _filterEvents(e,t){return d4(HJ(e,(await this._corpus.load(e)).events),t)}async readSurface(e){let t=await this._corpus.load(e);return{session:structuredClone(t.header),inheritedEventCount:t.inheritedEventCount,capturedThroughSeq:t.events.at(-1)?.seq??null,events:Z_t(e,t.events)}}async traceSession(e,t){let n=await this._corpus.listSessions(t);return t?.throwIfAborted(),J_t(n,e)}async traceEvent(e,t){let n=await this._corpus.load(e.sessionId,t);return t?.throwIfAborted(),{session:n.header,...K_t(e.sessionId,n.events,e.seq)}}async readEvent(e,t){let n=this._readWindow("before",e.before),r=this._readWindow("after",e.after),i=e.sessionId,s=e.seq;return this._readEvent(i,s,n,r,t)}async _readEvent(e,t,n,r,i){let s=await this._corpus.load(e,i);i?.throwIfAborted();let o=s.events[t];if(o===void 0||o.seq!==t)throw new Ir(`session "${e}" has no event at seq ${t}`,"SESSION_QUERY_EVENT_NOT_FOUND");let c=sn(Math.max(0,t-n)),l=sn(Math.min(s.events.length-1,t+r)),u=vE(o),d=s.events.slice(c,l+1).map(p=>p===o?u:vE(p));return{session:structuredClone(s.header),inheritedEventCount:s.inheritedEventCount,target:u,events:d,startSeq:c,endSeq:l}}_readWindow(e,t){if(t===void 0)return 0;if(!Number.isInteger(t)||t<0||t>this._readWindowMax)throw new Ir(`${e} must be an integer between 0 and ${this._readWindowMax}`,"SESSION_QUERY_INVALID_WINDOW");return t}}});var ux=we((DLn,CTe)=>{"use strict";CTe.exports=k1;k1.CAPTURING_PHASE=1;k1.AT_TARGET=2;k1.BUBBLING_PHASE=3;function k1(e,t){if(this.type="",this.target=null,this.currentTarget=null,this.eventPhase=k1.AT_TARGET,this.bubbles=!1,this.cancelable=!1,this.isTrusted=!1,this.defaultPrevented=!1,this.timeStamp=Date.now(),this._propagationStopped=!1,this._immediatePropagationStopped=!1,this._initialized=!0,this._dispatching=!1,e&&(this.type=e),t)for(var n in t)this[n]=t[n]}a(k1,"Event");k1.prototype=Object.create(Object.prototype,{constructor:{value:k1},stopPropagation:{value:a(function(){this._propagationStopped=!0},"stopPropagation")},stopImmediatePropagation:{value:a(function(){this._propagationStopped=!0,this._immediatePropagationStopped=!0},"stopImmediatePropagation")},preventDefault:{value:a(function(){this.cancelable&&(this.defaultPrevented=!0)},"preventDefault")},initEvent:{value:a(function(t,n,r){this._initialized=!0,!this._dispatching&&(this._propagationStopped=!1,this._immediatePropagationStopped=!1,this.defaultPrevented=!1,this.isTrusted=!1,this.target=null,this.type=t,this.bubbles=n,this.cancelable=r)},"initEvent")}})});var nY=we((LLn,$Te)=>{"use strict";var RTe=ux();$Te.exports=tY;function tY(){RTe.call(this),this.view=null,this.detail=0}a(tY,"UIEvent");tY.prototype=Object.create(RTe.prototype,{constructor:{value:tY},initUIEvent:{value:a(function(e,t,n,r,i){this.initEvent(e,t,n),this.view=r,this.detail=i},"value")}})});var iY=we((FLn,NTe)=>{"use strict";var OTe=nY();NTe.exports=rY;function rY(){OTe.call(this),this.screenX=this.screenY=this.clientX=this.clientY=0,this.ctrlKey=this.altKey=this.shiftKey=this.metaKey=!1,this.button=0,this.buttons=1,this.relatedTarget=null}a(rY,"MouseEvent");rY.prototype=Object.create(OTe.prototype,{constructor:{value:rY},initMouseEvent:{value:a(function(e,t,n,r,i,s,o,c,l,u,d,p,f,h,g){switch(this.initEvent(e,t,n,r,i),this.screenX=s,this.screenY=o,this.clientX=c,this.clientY=l,this.ctrlKey=u,this.altKey=d,this.shiftKey=p,this.metaKey=f,this.button=h,h){case 0:this.buttons=1;break;case 1:this.buttons=4;break;case 2:this.buttons=2;break;default:this.buttons=0;break}this.relatedTarget=g},"value")},getModifierState:{value:a(function(e){switch(e){case"Alt":return this.altKey;case"Control":return this.ctrlKey;case"Shift":return this.shiftKey;case"Meta":return this.metaKey;default:return!1}},"value")}})});var b4=we((ULn,DTe)=>{"use strict";DTe.exports=w4;var h2t=1,m2t=3,g2t=4,y2t=5,v2t=7,w2t=8,b2t=9,x2t=11,S2t=12,k2t=13,E2t=14,_2t=15,T2t=17,I2t=18,A2t=19,C2t=20,R2t=21,$2t=22,O2t=23,N2t=24,P2t=25,D2t=[null,"INDEX_SIZE_ERR",null,"HIERARCHY_REQUEST_ERR","WRONG_DOCUMENT_ERR","INVALID_CHARACTER_ERR",null,"NO_MODIFICATION_ALLOWED_ERR","NOT_FOUND_ERR","NOT_SUPPORTED_ERR","INUSE_ATTRIBUTE_ERR","INVALID_STATE_ERR","SYNTAX_ERR","INVALID_MODIFICATION_ERR","NAMESPACE_ERR","INVALID_ACCESS_ERR",null,"TYPE_MISMATCH_ERR","SECURITY_ERR","NETWORK_ERR","ABORT_ERR","URL_MISMATCH_ERR","QUOTA_EXCEEDED_ERR","TIMEOUT_ERR","INVALID_NODE_TYPE_ERR","DATA_CLONE_ERR"],M2t=[null,"INDEX_SIZE_ERR (1): the index is not in the allowed range",null,"HIERARCHY_REQUEST_ERR (3): the operation would yield an incorrect nodes model","WRONG_DOCUMENT_ERR (4): the object is in the wrong Document, a call to importNode is required","INVALID_CHARACTER_ERR (5): the string contains invalid characters",null,"NO_MODIFICATION_ALLOWED_ERR (7): the object can not be modified","NOT_FOUND_ERR (8): the object can not be found here","NOT_SUPPORTED_ERR (9): this operation is not supported","INUSE_ATTRIBUTE_ERR (10): setAttributeNode called on owned Attribute","INVALID_STATE_ERR (11): the object is in an invalid state","SYNTAX_ERR (12): the string did not match the expected pattern","INVALID_MODIFICATION_ERR (13): the object can not be modified in this way","NAMESPACE_ERR (14): the operation is not allowed by Namespaces in XML","INVALID_ACCESS_ERR (15): the object does not support the operation or argument",null,"TYPE_MISMATCH_ERR (17): the type of the object does not match the expected type","SECURITY_ERR (18): the operation is insecure","NETWORK_ERR (19): a network error occurred","ABORT_ERR (20): the user aborted an operation","URL_MISMATCH_ERR (21): the given URL does not match another URL","QUOTA_EXCEEDED_ERR (22): the quota has been exceeded","TIMEOUT_ERR (23): a timeout occurred","INVALID_NODE_TYPE_ERR (24): the supplied node is invalid or has an invalid ancestor for this operation","DATA_CLONE_ERR (25): the object can not be cloned."],PTe={INDEX_SIZE_ERR:h2t,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:m2t,WRONG_DOCUMENT_ERR:g2t,INVALID_CHARACTER_ERR:y2t,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:v2t,NOT_FOUND_ERR:w2t,NOT_SUPPORTED_ERR:b2t,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:x2t,SYNTAX_ERR:S2t,INVALID_MODIFICATION_ERR:k2t,NAMESPACE_ERR:E2t,INVALID_ACCESS_ERR:_2t,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:T2t,SECURITY_ERR:I2t,NETWORK_ERR:A2t,ABORT_ERR:C2t,URL_MISMATCH_ERR:R2t,QUOTA_EXCEEDED_ERR:$2t,TIMEOUT_ERR:O2t,INVALID_NODE_TYPE_ERR:N2t,DATA_CLONE_ERR:P2t};function w4(e){Error.call(this),Error.captureStackTrace(this,this.constructor),this.code=e,this.message=M2t[e],this.name=D2t[e]}a(w4,"DOMException");w4.prototype.__proto__=Error.prototype;for(v4 in PTe)sY={value:PTe[v4]},Object.defineProperty(w4,v4,sY),Object.defineProperty(w4.prototype,v4,sY);var sY,v4});var x4=we(MTe=>{MTe.isApiWritable=!globalThis.__domino_frozen__});var io=we(Ci=>{"use strict";var ro=b4(),So=ro,L2t=x4().isApiWritable;Ci.NAMESPACE={HTML:"http://www.w3.org/1999/xhtml",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/",MATHML:"http://www.w3.org/1998/Math/MathML",SVG:"http://www.w3.org/2000/svg",XLINK:"http://www.w3.org/1999/xlink"};Ci.IndexSizeError=function(){throw new ro(So.INDEX_SIZE_ERR)};Ci.HierarchyRequestError=function(){throw new ro(So.HIERARCHY_REQUEST_ERR)};Ci.WrongDocumentError=function(){throw new ro(So.WRONG_DOCUMENT_ERR)};Ci.InvalidCharacterError=function(){throw new ro(So.INVALID_CHARACTER_ERR)};Ci.NoModificationAllowedError=function(){throw new ro(So.NO_MODIFICATION_ALLOWED_ERR)};Ci.NotFoundError=function(){throw new ro(So.NOT_FOUND_ERR)};Ci.NotSupportedError=function(){throw new ro(So.NOT_SUPPORTED_ERR)};Ci.InvalidStateError=function(){throw new ro(So.INVALID_STATE_ERR)};Ci.SyntaxError=function(){throw new ro(So.SYNTAX_ERR)};Ci.InvalidModificationError=function(){throw new ro(So.INVALID_MODIFICATION_ERR)};Ci.NamespaceError=function(){throw new ro(So.NAMESPACE_ERR)};Ci.InvalidAccessError=function(){throw new ro(So.INVALID_ACCESS_ERR)};Ci.TypeMismatchError=function(){throw new ro(So.TYPE_MISMATCH_ERR)};Ci.SecurityError=function(){throw new ro(So.SECURITY_ERR)};Ci.NetworkError=function(){throw new ro(So.NETWORK_ERR)};Ci.AbortError=function(){throw new ro(So.ABORT_ERR)};Ci.UrlMismatchError=function(){throw new ro(So.URL_MISMATCH_ERR)};Ci.QuotaExceededError=function(){throw new ro(So.QUOTA_EXCEEDED_ERR)};Ci.TimeoutError=function(){throw new ro(So.TIMEOUT_ERR)};Ci.InvalidNodeTypeError=function(){throw new ro(So.INVALID_NODE_TYPE_ERR)};Ci.DataCloneError=function(){throw new ro(So.DATA_CLONE_ERR)};Ci.nyi=function(){throw new Error("NotYetImplemented")};Ci.shouldOverride=function(){throw new Error("Abstract function; should be overriding in subclass.")};Ci.assert=function(e,t){if(!e)throw new Error("Assertion failed: "+(t||"")+`
158
158
  `+new Error().stack)};Ci.expose=function(e,t){for(var n in e)Object.defineProperty(t.prototype,n,{value:e[n],writable:L2t})};Ci.merge=function(e,t){for(var n in t)e[n]=t[n]};Ci.documentOrder=function(e,t){return 3-(e.compareDocumentPosition(t)&6)};Ci.toASCIILowerCase=function(e){return e.replace(/[A-Z]+/g,function(t){return t.toLowerCase()})};Ci.toASCIIUpperCase=function(e){return e.replace(/[a-z]+/g,function(t){return t.toUpperCase()})}});var oY=we((HLn,jTe)=>{"use strict";var E1=ux(),j2t=iY(),F2t=io();jTe.exports=LTe;function LTe(){}a(LTe,"EventTarget");LTe.prototype={addEventListener:a(function(t,n,r){if(n){r===void 0&&(r=!1),this._listeners||(this._listeners=Object.create(null)),this._listeners[t]||(this._listeners[t]=[]);for(var i=this._listeners[t],s=0,o=i.length;s<o;s++){var c=i[s];if(c.listener===n&&c.capture===r)return}var l={listener:n,capture:r};typeof n=="function"&&(l.f=n),i.push(l)}},"addEventListener"),removeEventListener:a(function(t,n,r){if(r===void 0&&(r=!1),this._listeners){var i=this._listeners[t];if(i)for(var s=0,o=i.length;s<o;s++){var c=i[s];if(c.listener===n&&c.capture===r){i.length===1?this._listeners[t]=void 0:i.splice(s,1);return}}}},"removeEventListener"),dispatchEvent:a(function(t){return this._dispatchEvent(t,!1)},"dispatchEvent"),_dispatchEvent:a(function(t,n){typeof n!="boolean"&&(n=!1);function r(u,d){var p=d.type,f=d.eventPhase;if(d.currentTarget=u,f!==E1.CAPTURING_PHASE&&u._handlers&&u._handlers[p]){var h=u._handlers[p],g;if(typeof h=="function")g=h.call(d.currentTarget,d);else{var y=h.handleEvent;if(typeof y!="function")throw new TypeError("handleEvent property of event handler object isnot a function.");g=y.call(h,d)}d.type==="mouseover"?g===!0&&d.preventDefault():g===!1&&d.preventDefault()}var v=u._listeners&&u._listeners[p];if(v){v=v.slice();for(var x=0,w=v.length;x<w;x++){if(d._immediatePropagationStopped)return;var S=v[x];if(!(f===E1.CAPTURING_PHASE&&!S.capture||f===E1.BUBBLING_PHASE&&S.capture))if(S.f)S.f.call(d.currentTarget,d);else{var k=S.listener.handleEvent;if(typeof k!="function")throw new TypeError("handleEvent property of event listener object is not a function.");k.call(S.listener,d)}}}}a(r,"invoke"),(!t._initialized||t._dispatching)&&F2t.InvalidStateError(),t.isTrusted=n,t._dispatching=!0,t.target=this;for(var i=[],s=this.parentNode;s;s=s.parentNode)i.push(s);t.eventPhase=E1.CAPTURING_PHASE;for(var o=i.length-1;o>=0&&(r(i[o],t),!t._propagationStopped);o--);if(t._propagationStopped||(t.eventPhase=E1.AT_TARGET,r(this,t)),t.bubbles&&!t._propagationStopped){t.eventPhase=E1.BUBBLING_PHASE;for(var c=0,l=i.length;c<l&&(r(i[c],t),!t._propagationStopped);c++);}if(t._dispatching=!1,t.eventPhase=E1.AT_TARGET,t.currentTarget=null,n&&!t.defaultPrevented&&t instanceof j2t)switch(t.type){case"mousedown":this._armed={x:t.clientX,y:t.clientY,t:t.timeStamp};break;case"mouseout":case"mouseover":this._armed=null;break;case"mouseup":this._isClick(t)&&this._doClick(t),this._armed=null;break}return!t.defaultPrevented},"_dispatchEvent"),_isClick:a(function(e){return this._armed!==null&&e.type==="mouseup"&&e.isTrusted&&e.button===0&&e.timeStamp-this._armed.t<1e3&&Math.abs(e.clientX-this._armed.x)<10&&Math.abs(e.clientY-this._armed.Y)<10},"_isClick"),_doClick:a(function(e){if(!this._click_in_progress){this._click_in_progress=!0;for(var t=this;t&&!t._post_click_activation_steps;)t=t.parentNode;t&&t._pre_click_activation_steps&&t._pre_click_activation_steps();var n=this.ownerDocument.createEvent("MouseEvent");n.initMouseEvent("click",!0,!0,this.ownerDocument.defaultView,1,e.screenX,e.screenY,e.clientX,e.clientY,e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,e.button,null);var r=this._dispatchEvent(n,!0);t&&(r?t._post_click_activation_steps&&t._post_click_activation_steps(n):t._cancelled_activation_steps&&t._cancelled_activation_steps())}},"_doClick"),_setEventHandler:a(function(t,n){this._handlers||(this._handlers=Object.create(null)),this._handlers[t]=n},"_setEventHandler"),_getEventHandler:a(function(t){return this._handlers&&this._handlers[t]||null},"_getEventHandler")}});var aY=we((GLn,FTe)=>{"use strict";var Xh=io(),nd=FTe.exports={valid:a(function(e){return Xh.assert(e,"list falsy"),Xh.assert(e._previousSibling,"previous falsy"),Xh.assert(e._nextSibling,"next falsy"),!0},"valid"),insertBefore:a(function(e,t){Xh.assert(nd.valid(e)&&nd.valid(t));var n=e,r=e._previousSibling,i=t,s=t._previousSibling;n._previousSibling=s,r._nextSibling=i,s._nextSibling=n,i._previousSibling=r,Xh.assert(nd.valid(e)&&nd.valid(t))},"insertBefore"),replace:a(function(e,t){Xh.assert(nd.valid(e)&&(t===null||nd.valid(t))),t!==null&&nd.insertBefore(t,e),nd.remove(e),Xh.assert(nd.valid(e)&&(t===null||nd.valid(t)))},"replace"),remove:a(function(e){Xh.assert(nd.valid(e));var t=e._previousSibling;if(t!==e){var n=e._nextSibling;t._nextSibling=n,n._previousSibling=t,e._previousSibling=e._nextSibling=e,Xh.assert(nd.valid(e))}},"remove")}});var cY=we((KLn,GTe)=>{"use strict";GTe.exports={serializeOne:V2t,\u0275escapeMatchingClosingTag:WTe,\u0275escapeClosingCommentTag:HTe,\u0275escapeProcessingInstructionContent:VTe};var BTe=io(),_1=BTe.NAMESPACE,qTe={STYLE:!0,SCRIPT:!0,XMP:!0,IFRAME:!0,NOEMBED:!0,NOFRAMES:!0,PLAINTEXT:!0},q2t={area:!0,base:!0,basefont:!0,bgsound:!0,br:!0,col:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},U2t={},UTe=/[&<>\u00A0]/g,zTe=/[&"<>\u00A0]/g;function z2t(e){return UTe.test(e)?e.replace(UTe,t=>{switch(t){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case"\xA0":return"&nbsp;"}}):e}a(z2t,"escape");function B2t(e){return zTe.test(e)?e.replace(zTe,t=>{switch(t){case"<":return"&lt;";case">":return"&gt;";case"&":return"&amp;";case'"':return"&quot;";case"\xA0":return"&nbsp;"}}):e}a(B2t,"escapeAttr");function W2t(e){var t=e.namespaceURI;return t?t===_1.XML?"xml:"+e.localName:t===_1.XLINK?"xlink:"+e.localName:t===_1.XMLNS?e.localName==="xmlns"?"xmlns":"xmlns:"+e.localName:e.name:e.localName}a(W2t,"attrname");function WTe(e,t){let n="</"+t;if(!e.toLowerCase().includes(n))return e;let r=[...e],i=e.matchAll(new RegExp(n,"ig"));for(let s of i)r[s.index]="&lt;";return r.join("")}a(WTe,"escapeMatchingClosingTag");var H2t=/--!?>/;function HTe(e){return H2t.test(e)?e.replace(/(--\!?)>/g,"$1&gt;"):e}a(HTe,"escapeClosingCommentTag");function VTe(e){return e.includes(">")?e.replaceAll(">","&gt;"):e}a(VTe,"escapeProcessingInstructionContent");function V2t(e,t){var n="";switch(e.nodeType){case 1:var r=e.namespaceURI,i=r===_1.HTML,s=i||r===_1.SVG||r===_1.MATHML?e.localName:e.tagName;n+="<"+s;for(var o=0,c=e._numattrs;o<c;o++){var l=e._attr(o);n+=" "+W2t(l),l.value!==void 0&&(n+='="'+B2t(l.value)+'"')}if(n+=">",!(i&&q2t[s])){var u=e.serialize();qTe[s.toUpperCase()]&&(u=WTe(u,s)),i&&U2t[s]&&u.charAt(0)===`
@@ -5735,7 +5735,7 @@ The web search request used endpoint ${JSON.stringify(e)}. Search endpoint confi
5735
5735
  .error { padding: .75rem; border-radius: .5rem; background: #461d2b; color: #ffd6df; }
5736
5736
  .hint { margin: 1.5rem 0 0; font-size: .875rem; }
5737
5737
  code { padding: .1rem .3rem; border-radius: .3rem; background: #0c1222; color: #edf2ff; }
5738
- `}a(kDe,"pageStyles");F2();var xne="enabled",Sne=Object.freeze({id:"direct",capabilities:Object.freeze(["bash"]),plan:"free",shell:"just-bash-direct",probe:a(e=>e.LOADER===void 0?"available":"needs-binding","probe")}),zI=Object.freeze({id:"dynamic-worker",capabilities:Object.freeze(["bash","coding"]),plan:"paid",shell:"just-bash-isolated",probe:a(e=>e.LOADER===void 0?"needs-binding":"available","probe")}),kne=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===xne?"available":"needs-binding","probe")}),JBt=Object.freeze([kne,zI,Sne]);function Ene(e,t=JBt){return t.filter(n=>n.probe(e)==="available")}a(Ene,"availableEdgeRuntimeProviders");function _ne(e){let t=a(r=>e.find(i=>i.capabilities.includes(r)),"first"),n=t("bash");if(n===void 0)throw new Error("No available runtime provider serves the bash layer.");return{bash:n.id,container:t("container")?.id??null}}a(_ne,"resolveEdgeRuntimeSelection");function KD(e){let t=Ene(e),{bash:n,container:r}=_ne(t);return t.find(i=>i.id===(r??n)).shell}a(KD,"resolveEdgeRuntimeShell");function YBt(){return"dsh-edge@0.19.0-alpha.2/direct"}a(YBt,"resolveEdgeDeploymentId");function BI(e){return{baseURL:tK(e.DEEPSEEK_BASE_URL),maxTokens:iK(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:u1(e.DEEPSEEK_MODEL),reasoningEffort:nK(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:o3(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:rK(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:by(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(BI,"resolveEdgeDeploymentConfig");function XBt(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(XBt,"edgeDeploymentApiKeyConfigured");function QBt(e){let t=tK(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(QBt,"projectedEdgeBaseURL");function Tne(e,t){return{shell:KD(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:YBt(),apiKeyConfigured:XBt(e),baseURL:QBt(e.DEEPSEEK_BASE_URL),maxTokens:iK(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:u1(e.DEEPSEEK_MODEL),reasoningEffort:nK(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:o3(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:rK(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:by(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(Tne,"resolveEdgeDeploymentProfile");function JD(e){BI(e);let t=Tne(e);return{ok:!0,service:"dsh-edge",storage:t.storage,attachmentStorage:t.attachmentStorage,shell:t.shell,agent:"upstream-react-loop-agent",access:"single-owner-cookie",deploymentId:t.deploymentId,...e.CF_VERSION_METADATA===void 0?{}:{workerVersionId:e.CF_VERSION_METADATA.id},version:i1,upstreamVersion:qxe,status:"ready"}}a(JD,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as mcn}from"node:async_hooks";import{RpcTarget as eWt}from"cloudflare:workers";function tWt(e){let{intervalMs:t,ping:n,onFailure:r}=e,i=!1,s=setInterval(()=>{i||n().catch(o=>{i||(i=!0,clearInterval(s),r(o instanceof Error?o:new Error(String(o))))})},t);return()=>{i||(i=!0,clearInterval(s))}}a(tWt,"startHeartbeat");async function nWt(e,t){let n=AbortSignal.timeout(t.timeoutMs),r=await e.fetchPort(t.port,`http://container${t.path}`,{method:"HEAD",signal:n});if(r.body?.cancel(),!r.ok)throw new Error(`computerd health returned ${r.status}`)}a(nWt,"probeComputerdHealth");var rWt="computer.internal",iWt="/health",Ine="/api",sWt=8080,oWt=3e4,aWt=2e4,cWt=1,lWt=2e3,uWt=250,dWt=2e3;function pWt(e,t){if(t===void 0||e===null)return!1;let n=e.indexOf(" ");if(n===-1||e.slice(0,n).toLowerCase()!=="bearer")return!1;let r=e.slice(n+1).trim();if(r.length!==t.length)return!1;let i=0;for(let s=0;s<t.length;s+=1)i|=r.charCodeAt(s)^t.charCodeAt(s);return i===0}a(pWt,"bearerMatches");var XD=class{static{a(this,"CloudflareContainerBackend")}type="cloudflare-container";id;#e;#t;#r;#n;#i;#s;#a;#c;constructor(e){this.id=e.id??"container-shell",this.#t=e.egress??{mode:"none"},this.#r=this.#t.mode==="http-gateway"?crypto.randomUUID():void 0,this.#e={container:e.container,workspace:e.workspace,containerEnv:e.containerEnv,egressHost:e.egressHost??rWt,containerPort:e.containerPort??sWt,connectTimeoutMs:e.connectTimeoutMs??oWt,heartbeatIntervalMs:e.heartbeatIntervalMs??aWt,restartAttempts:e.restartAttempts??cWt,healthProbeTimeoutMs:e.healthProbeTimeoutMs??lWt,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??uWt,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??dWt}}async connect(){if(this.#c)return this.#c;let e=Date.now()+this.#e.connectTimeoutMs,t=await(await this.#e.container()).getWorkspaceContainer(),n=await t.exitInfo().catch(()=>null),r={PORT:String(this.#e.containerPort),MOUNT_POINT:"/workspace",...this.#e.containerEnv},i,s;try{({runtimeId:i,clientSecret:s}=await t.start({env:r,enableInternet:this.#t.mode==="direct"}))}catch(p){throw new yc(this.#d("start",{attempt:1,maxAttempts:this.#e.restartAttempts+1,restarts:0,lastError:p,priorExit:n}),{cause:p})}try{await t.interceptOutboundHttp(this.#e.egressHost,this.#e.workspace),this.#t.mode==="http-gateway"&&this.#r!==void 0&&await t.interceptAllOutboundHttp(this.#e.workspace,this.#r)}catch(p){throw new yc(this.#d("egress",{attempt:1,maxAttempts:this.#e.restartAttempts+1,restarts:0,lastError:p,priorExit:n}),{cause:p})}this.#n=s,this.#u(),i=await this.#p(t,r,e,n,i),await this.#f(t,e),await this.#v(t,e,s);let o=await this.#h(e),c=T8(o),l,u=new Promise(p=>{let f=!1,h=a(()=>{f||(f=!0,l?.(),p(),this.#c=void 0)},"onClose");o.addEventListener("close",h,{once:!0}),o.addEventListener("error",h,{once:!0}),c.onRpcBroken(h)});this.#e.heartbeatIntervalMs>0&&(l=tWt({intervalMs:this.#e.heartbeatIntervalMs,ping:a(()=>c.sync.watermarks(),"ping"),onFailure:a(()=>{try{o.close()}catch{}},"onFailure")}));let d={rpc:c,runtimeId:i,closed:u,close:a(async()=>{l?.();try{c[Symbol.dispose]?.()}catch{}try{o.close()}catch{}this.#c=void 0},"close")};return this.#c=d,d}async handleFetch(e){if(this.#t.mode==="http-gateway"&&this.#r!==void 0&&e.headers.get("x-workspace-egress-token")===this.#r){let i=new Headers(e.headers),s=i.get(VS),o;try{o=new URL(s??"")}catch{return new Response("invalid egress URL",{status:400})}if(o.protocol!=="http:"&&o.protocol!=="https:")return new Response("invalid egress URL",{status:400});i.delete(iC),i.delete(VS);let c=new Request(e,{headers:i});return this.#t.gateway.fetch(new Request(o,c))}if(new URL(e.url).pathname!==Ine)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${Ine} requires a websocket upgrade`,{status:400});if(!pWt(e.headers.get("authorization"),this.#n))return new Response("unauthorized",{status:401,headers:{"www-authenticate":"Bearer"}});let t=new WebSocketPair,[n,r]=[t[0],t[1]];if(r.accept(),this.#s)this.#s(r);else return r.close(1011,"no pending connect"),new Response("no pending connect",{status:409});return new Response(null,{status:101,webSocket:n})}#u(){this.#i=new Promise((e,t)=>{this.#s=e,this.#a=t}),this.#i.catch(()=>{})}#o(){this.#i=void 0,this.#s=void 0,this.#a=void 0}async#p(e,t,n,r,i){let s=this.#e.restartAttempts+1,o=Math.max(0,n-Date.now()),c=Math.max(250,Math.floor(o/s)),l=0,u=0,d,p=i;for(;l<s;){l++;let f=Math.min(n,Date.now()+c);if(await this.#m(e,f).then(()=>!0,h=>(d=h,!1)))return p;if(l<s)try{({runtimeId:p}=await e.restart({env:t,enableInternet:this.#t.mode==="direct"})),u++}catch(h){throw this.#a?.(h),this.#o(),new yc(this.#d("restart",{attempt:l,maxAttempts:s,restarts:u,lastError:h}),{cause:h})}}throw this.#a?.(new Error("computerd never became healthy")),this.#o(),new yc(this.#d("health",{attempt:l,maxAttempts:s,restarts:u,lastError:d,priorExit:r}),d instanceof Error?{cause:d}:void 0)}async#m(e,t){let n=this.#e.healthRetryInitialDelayMs,r;for(;Date.now()<t;)try{await nWt(e,{port:this.#e.containerPort,path:"/health",timeoutMs:Math.min(this.#e.healthProbeTimeoutMs,Math.max(50,t-Date.now()))});return}catch(i){r=i;let s=t-Date.now();if(s<=0)break;await fWt(Math.min(n,s)),n=Math.min(n*2,this.#e.healthRetryMaxDelayMs)}throw r??new Error("computerd health probe timed out")}#d(e,t){let n=t.priorExit?` priorExit=${JSON.stringify(t.priorExit.reason)}`:"";return`CloudflareContainerBackend(${this.id}): connect failed at stage=${e} port=${this.#e.containerPort} attempt=${t.attempt}/${t.maxAttempts} restarts=${t.restarts} timeoutMs=${this.#e.connectTimeoutMs}${n} lastError=${EDe(t.lastError)}`}async#f(e,t){let n;try{let r=await e.fetchPort(this.#e.containerPort,"http://container/api",{signal:AbortSignal.timeout(Math.min(this.#e.healthProbeTimeoutMs,Math.max(50,t-Date.now())))});n=r.status,await r.text().catch(()=>"")}catch{return}if(n!==401)throw this.#a?.(new Error("container is not enforcing RPC_CLIENT_SECRET")),this.#o(),new yc(`CloudflareContainerBackend(${this.id}) [stage=auth]: container served an unauthenticated request to /api with ${n}, so this workspace would run without authorization. A container or image predating RPC_CLIENT_SECRET has to be recycled.`)}async#v(e,t,n){let r=Math.max(0,t-Date.now()),i;try{i=await e.fetchPort(this.#e.containerPort,"http://container/connect",{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${n}`},body:JSON.stringify({base:`http://${this.#e.egressHost}`,health:iWt,api:Ine,healthTimeoutMs:r})})}catch(s){throw this.#a?.(s),this.#o(),new yc(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${EDe(s)}`,{cause:s})}if(!i.ok){let s=await i.text().catch(()=>""),o=new Error(`/connect ${i.status}`);throw this.#a?.(o),this.#o(),new yc(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect returned ${i.status}: ${s}`,{cause:o})}}async#h(e){let t=this.#i;if(!t)throw new Error("CloudflareContainerBackend: upgrade promise missing");let n=Math.max(0,e-Date.now()),r;try{return await Promise.race([t,new Promise((i,s)=>{r=setTimeout(()=>s(new yc(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#o()}}};function fWt(e){return new Promise(t=>setTimeout(t,e))}a(fWt,"sleep");function EDe(e){return e instanceof Error?e.message:String(e)}a(EDe,"describeError");var _De="computer:container-client-secret",hWt=16;function mWt(){let e=crypto.getRandomValues(new Uint8Array(hWt));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(mWt,"generate");var gWt=class{static{a(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(_De);if(typeof e=="string"&&e.length>0)return e;let t=mWt();return await this.storage.put(_De,t),t}},TDe="computer:container-launch-record";async function IDe(e){return{enableInternet:e.enableInternet,envDigest:await vWt(e.env)}}a(IDe,"launchRecordFor");function yWt(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}a(yWt,"sameLaunch");async function vWt(e){let t=Object.keys(e).sort().map(r=>`${r.length}:${r}=${e[r]?.length??0}:${e[r]??""}`).join(";"),n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")}a(vWt,"digestEnv");var wWt=class{static{a(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(TDe)??null}async set(e){await this.storage.put(TDe,e)}},ADe=new WeakMap;function Rne(e){let t=ADe.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},ADe.set(e,t)),t}a(Rne,"getContainerLifecycle");function YD(e){return Rne(e).exit}a(YD,"containerExitInfo");function CDe(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}a(CDe,"formatExitReason");function RDe(e,t,n){let r=Rne(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>$De(r,i,void 0,n),s=>$De(r,i,s,n))}a(RDe,"installContainerMonitor");async function Ane(e,t){let n=Rne(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}a(Ane,"destroyContainerExpectingExit");async function $De(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=CDe(n),o=Date.now();e.exit={reason:s,exitedAt:o},i?console.info({message:"workspace.container.exited",reason:s,exitedAt:o,expected:!0}):console.warn({message:"workspace.container.exited",reason:s,exitedAt:o,expected:!1});try{await r?.()}catch(c){console.error({message:"workspace.container.exit_cleanup_failed",reason:CDe(c),exitedAt:Date.now()})}}a($De,"recordExit");var Cne="computer:container-runtime-identity",bWt=class{static{a(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(Cne)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(Cne,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(Cne)}},xWt=class extends eWt{static{a(this,"WorkspaceContainerAPI")}#e;#t;#r;#n;#i;constructor(e){if(super(),!e.container)throw new Error("WorkspaceContainerAPI: DO is not container-enabled (check wrangler.jsonc)");this.#e=e.container,this.#t=e,this.#r=new bWt(e.storage),this.#n=new gWt(e.storage),this.#i=new wWt(e.storage)}async start(e){let t=YD(this.#t),n=await this.#n.ensure(),r=await IDe(e);if(t!==null){try{await Ane(this.#t,this.#e)}catch{}return this.#s(e,n,r,"launched")}if(!this.#e.running)return this.#s(e,n,r,"launched");let i=await this.#i.get();if(i===null||!yWt(i,r)){console.warn({message:i===null?"container was started outside WorkspaceContainerAPI; relaunching so the requested environment applies":"running container was launched with a different spec; relaunching",component:"workspace-container",requested:r,actual:i});try{await Ane(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return RDe(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await Ane(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await IDe(e),"launched")}async setInactivityTimeout(e){await this.#e.setInactivityTimeout(e)}async#s(e,t,n,r){let i=await this.#r.markStarted();try{this.#e.start({enableInternet:e.enableInternet,env:{...e.env,RPC_CLIENT_SECRET:t}})}catch(s){throw await this.#r.clear(i),s}return await this.#i.set(n),RDe(this.#t,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:YD(this.#t)}}async exitInfo(){return YD(this.#t)}async interceptAllOutboundHttp(e,t){let n=this.#t.exports.WorkspaceProxy({props:{...e,egressToken:t}});await Promise.all([this.#e.interceptAllOutboundHttp(n),this.#e.interceptOutboundHttps("*",n)])}async interceptOutboundHttp(e,t){let n=this.#t.exports;await this.#e.interceptOutboundHttp(e,n.WorkspaceProxy({props:t}))}fetchPort(e,t,n){let r=YD(this.#t);if(r!==null)throw new yc(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function ODe(e){class t extends e{static{a(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new xWt(this.ctx)}}return t}a(ODe,"withWorkspaceContainer");var SWt={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function PDe(e,t){let n=t.indexOf("."),r=t.indexOf("/"),i=n>=0?n:r;if(i<0)return;let s=t.slice(0,i),o=t.slice(i+1),c=SWt[s]??s,l=e[c];if(l===void 0)return;let u=l[o];return typeof u=="function"?u:void 0}a(PDe,"resolve");function kWt(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}a(kWt,"errorResponse");async function $ne(e,t,n,r,i){let s=PDe(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}a($ne,"callEdgeApi");async function DDe(e,t){let r=new URL(t.url).pathname;if(t.method!=="POST"||!r.startsWith("/api/"))return new Response("not found",{status:404});if(r==="/api/respond")return Response.json({accepted:!1,reason:"not-pending"});let i=r.slice(5);if(PDe(e,i)===void 0)return new Response("not found",{status:404});let s;try{s=await t.json()}catch{return new Response("body is not JSON",{status:400})}let o=typeof s.rpcId=="string"?s.rpcId:"invalid-request",c=s.payload??{};try{let l=await $ne(e,i,o,c,t.signal);return l===void 0?new Response("not found",{status:404}):Response.json({type:"server-response",rpcId:l.rpcId,result:l.result})}catch(l){return kWt(o,{code:"internal",message:String(l),details:{}})}}a(DDe,"dispatchEdgeApi");kr();Zs();kg();import{DurableObject as gcn}from"cloudflare:workers";var QD=class{constructor(t,n=Date.now,r=2){this.sleepAfterMs=t;this.now=n;this.maxConcurrent=r}sleepAfterMs;now;maxConcurrent;static{a(this,"ContainerActivity")}inFlight=0;lastActivity;stopping;waiters=[];async admit(t){let n=this.now();for(;this.stopping!==void 0||this.inFlight>=this.maxConcurrent;){if(t?.throwIfAborted(),this.stopping!==void 0){await EWt(this.stopping,t);continue}await new Promise((r,i)=>{let s=a(()=>{t?.removeEventListener("abort",o),r()},"wake"),o=a(()=>{let c=this.waiters.indexOf(s);c!==-1&&this.waiters.splice(c,1),i(t.reason)},"abort");this.waiters.push(s),t?.addEventListener("abort",o,{once:!0})})}return t?.aborted===!0&&(this.waiters.shift()?.(),t.throwIfAborted()),{release:this.begin(),queuedMs:this.now()-n}}begin(){this.inFlight+=1,this.lastActivity=this.now();let t=!1;return()=>{t||(t=!0,this.inFlight-=1,this.lastActivity=this.now(),this.waiters.shift()?.())}}async stopIfIdle(t){return this.idle()?await this.stop(t):"busy"}async stopNow(t){return this.inFlight===0?await this.stop(t):"busy"}snapshot(){return{runningCommands:this.inFlight,lastActivityAt:this.lastActivity??null}}async stop(t){if(this.stopping!==void 0)return"busy";let n="stopped",r=t().catch(i=>{n="failed",this.lastActivity=this.now(),console.error("dsh-edge container stop failed.",i)});this.stopping=r;try{await r}finally{this.stopping=void 0}return n}deadline(){return this.inFlight>0?this.now()+this.sleepAfterMs():this.lastActivity===void 0?this.now():this.lastActivity+this.sleepAfterMs()}idle(){return this.inFlight===0&&(this.lastActivity===void 0||this.now()>=this.lastActivity+this.sleepAfterMs())}};function EWt(e,t){return t===void 0?e:new Promise((n,r)=>{let i=a(()=>r(t.reason),"abort");t.addEventListener("abort",i,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",i))})}a(EWt,"untilAborted");import{WorkerEntrypoint as WJn}from"cloudflare:workers";var _v=Qc(MDe());var One=a((e,t,n)=>{let r=e instanceof RegExp?LDe(e,n):e,i=t instanceof RegExp?LDe(t,n):t,s=r!==null&&i!=null&&_Wt(r,i,n);return s&&{start:s[0],end:s[1],pre:n.slice(0,s[0]),body:n.slice(s[0]+r.length,s[1]),post:n.slice(s[1]+i.length)}},"balanced"),LDe=a((e,t)=>{let n=t.match(e);return n?n[0]:null},"maybeMatch"),_Wt=a((e,t,n)=>{let r,i,s,o,c,l=n.indexOf(e),u=n.indexOf(t,l+1),d=l;if(l>=0&&u>0){if(e===t)return[l,u];for(r=[],s=n.length;d>=0&&!c;){if(d===l)r.push(d),l=n.indexOf(e,d+1);else if(r.length===1){let p=r.pop();p!==void 0&&(c=[p,u])}else i=r.pop(),i!==void 0&&i<s&&(s=i,o=u),u=n.indexOf(t,d+1);d=l<u&&l>=0?l:u}r.length&&o!==void 0&&(c=[s,o])}return c},"range");var jDe="\0SLASH"+Math.random()+"\0",FDe="\0OPEN"+Math.random()+"\0",Dne="\0CLOSE"+Math.random()+"\0",qDe="\0COMMA"+Math.random()+"\0",UDe="\0PERIOD"+Math.random()+"\0",TWt=new RegExp(jDe,"g"),IWt=new RegExp(FDe,"g"),AWt=new RegExp(Dne,"g"),CWt=new RegExp(qDe,"g"),RWt=new RegExp(UDe,"g"),$Wt=/\\\\/g,OWt=/\\{/g,NWt=/\\}/g,PWt=/\\,/g,DWt=/\\\./g,MWt=1e5,LWt=4e6;function Nne(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}a(Nne,"numeric");function jWt(e){return e.replace($Wt,jDe).replace(OWt,FDe).replace(NWt,Dne).replace(PWt,qDe).replace(DWt,UDe)}a(jWt,"escapeBraces");function FWt(e){return e.replace(TWt,"\\").replace(IWt,"{").replace(AWt,"}").replace(CWt,",").replace(RWt,".")}a(FWt,"unescapeBraces");function zDe(e){if(!e)return[""];let t=[],n=One("{","}",e);if(!n)return e.split(",");let{pre:r,body:i,post:s}=n,o=r.split(",");o[o.length-1]+="{"+i+"}";let c=zDe(s);return s.length&&(o[o.length-1]+=c.shift(),o.push.apply(o,c)),t.push.apply(t,o),t}a(zDe,"parseCommaParts");function BDe(e,t={}){if(!e)return[];let{max:n=MWt,maxLength:r=LWt}=t;return e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),Pne(jWt(e),n,r,!0).map(FWt)}a(BDe,"expand");function qWt(e){return"{"+e+"}"}a(qWt,"embrace");function UWt(e){return/^-?0\d/.test(e)}a(UWt,"isPadded");function zWt(e,t){return e<=t}a(zWt,"lte");function BWt(e,t){return e>=t}a(BWt,"gte");function WI(e,t,n,r,i,s){let o=[],c=0;for(let l=0;l<e.length;l++)for(let u=0;u<n.length;u++){if(o.length>=r)return o;let d=e[l]+t+n[u];if(!(s&&!d)){if(c+d.length>i)return o;o.push(d),c+=d.length}}return o}a(WI,"combine");function WWt(e,t,n,r){let i=e.split(/\.\./),s=[];if(i[0]===void 0||i[1]===void 0)return s;let o=Nne(i[0]),c=Nne(i[1]),l=Math.max(i[0].length,i[1].length),u=i.length===3&&i[2]!==void 0?Math.max(Math.abs(Nne(i[2])),1):1,d=zWt;c<o&&(u*=-1,d=BWt);let f=i.some(UWt),h=0;for(let g=o;d(g,c)&&s.length<n;g+=u){let y;if(t)y=String.fromCharCode(g),y==="\\"&&(y="");else if(y=String(g),f){let v=l-y.length;if(v>0){let x=new Array(v+1).join("0");g<0?y="-"+x+y.slice(1):y=x+y}}if(h+y.length>r)break;s.push(y),h+=y.length}return s}a(WWt,"expandSequence");function Pne(e,t,n,r){let i=[""],s=!1,o=!0;for(;;){let c=One("{","}",e);if(!c)return WI(i,e,[""],t,n,s);let l=c.pre;if(/\$$/.test(l)){if(i=WI(i,l+"{"+c.body+"}",[""],t,n,s&&!c.post.length),o=!1,!c.post.length)break;e=c.post;continue}let u=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(c.body),d=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(c.body),p=u||d,f=c.body.indexOf(",")>=0;if(!p&&!f){if(c.post.match(/,(?!,).*\}/)){e=c.pre+"{"+c.body+Dne+c.post,r=!0;continue}return WI(i,l+"{"+c.body+"}"+c.post,[""],t,n,s)}o&&(s=r&&!p,o=!1);let h;if(p)h=WWt(c.body,d,t,n);else{let g=zDe(c.body);if(g.length===1&&g[0]!==void 0&&(g=Pne(g[0],t,n,!1).map(qWt),g.length===1)){if(i=WI(i,l+g[0],[""],t,n,s&&!c.post.length),!c.post.length)break;e=c.post;continue}let y=s&&!c.post.length&&!l;for(let x=0;y&&x<i.length;x++)i[x]&&(y=!1);h=[];let v=0;e:for(let x=0;x<g.length;x++){let w=Pne(g[x],t,n,!1);for(let S=0;S<w.length;S++){let k=w[S];if(!(y&&!k)){if(h.length>=t||v+k.length>n)break e;h.push(k),v+=k.length}}}}if(i=WI(i,l,h,t,n,s&&!c.post.length),!c.post.length)break;e=c.post}return i}a(Pne,"expand_");var HI=a(e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")},"assertValidPattern");var HWt={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},VI=a(e=>e.replace(/[[\]\\-]/g,"\\$&"),"braceEscape"),VWt=a(e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"regexpEscape"),WDe=a(e=>e.join(""),"rangesToString"),HDe=a((e,t)=>{let n=t;if(e.charAt(n)!=="[")throw new Error("not in a brace expression");let r=[],i=[],s=n+1,o=!1,c=!1,l=!1,u=!1,d=n,p="";e:for(;s<e.length;){let y=e.charAt(s);if((y==="!"||y==="^")&&s===n+1){u=!0,s++;continue}if(y==="]"&&o&&!l){d=s+1;break}if(o=!0,y==="\\"&&!l){l=!0,s++;continue}if(y==="["&&!l){for(let[v,[x,w,S]]of Object.entries(HWt))if(e.startsWith(v,s)){if(p)return["$.",!1,e.length-n,!0];s+=v.length,S?i.push(x):r.push(x),c=c||w;continue e}}if(l=!1,p){y>p?r.push(VI(p)+"-"+VI(y)):y===p&&r.push(VI(y)),p="",s++;continue}if(e.startsWith("-]",s+1)){r.push(VI(y+"-")),s+=2;continue}if(e.startsWith("-",s+1)){p=y,s+=2;continue}r.push(VI(y)),s++}if(d<s)return["",!1,0,!1];if(!r.length&&!i.length)return["$.",!1,e.length-n,!0];if(i.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!u){let y=r[0].length===2?r[0].slice(-1):r[0];return[VWt(y),!1,d-n,!1]}let f="["+(u?"^":"")+WDe(r)+"]",h="["+(u?"":"^")+WDe(i)+"]";return[r.length&&i.length?"("+f+"|"+h+")":r.length?f:h,c,d-n,!0]},"parseClass");var ky=a((e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!0}={})=>n?t?e.replace(/\[([^/\\])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^/\\])\]/g,"$1$2").replace(/\\([^/])/g,"$1"):t?e.replace(/\[([^/\\{}])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^/\\{}])\]/g,"$1$2").replace(/\\([^/{}])/g,"$1"),"unescape");var $l,GWt=new Set(["!","?","+","*","@"]),Mne=a(e=>GWt.has(e),"isExtglobType"),VDe=a(e=>Mne(e.type),"isExtglobAST"),ZWt=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),KWt=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),JWt=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),GDe=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),YWt="(?!(?:^|/)\\.\\.?(?:$|/))",tM="(?!\\.)",XWt=new Set(["[","."]),QWt=new Set(["..","."]),eHt=new Set("().*{}+?[]^$\\!"),tHt=a(e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"regExpEscape"),Lne="[^/]",ZDe=Lne+"*?",KDe=Lne+"+?",nHt=0,Z1=class{static{a(this,"AST")}type;#e;#t;#r=!1;#n=[];#i;#s;#a;#c=!1;#u;#o;#p=!1;id=++nHt;get depth(){return(this.#i?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#e.id,parent:this.#i?.id,depth:this.depth,partsLength:this.#n.length,parts:this.#n}}constructor(t,n,r={}){this.type=t,t&&(this.#t=!0),this.#i=n,this.#e=this.#i?this.#i.#e:this,this.#u=this.#e===this?r:this.#e.#u,this.#a=this.#e===this?[]:this.#e.#a,t==="!"&&!this.#e.#c&&this.#a.push(this),this.#s=this.#i?this.#i.#n.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let t of this.#n)if(typeof t!="string"&&(t.type||t.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#o!==void 0?this.#o:this.type?this.#o=this.type+"("+this.#n.map(t=>String(t)).join("|")+")":this.#o=this.#n.map(t=>String(t)).join("")}#m(){if(this!==this.#e)throw new Error("should only call on root");if(this.#c)return this;this.toString(),this.#c=!0;let t;for(;t=this.#a.pop();){if(t.type!=="!")continue;let n=t,r=n.#i;for(;r;){for(let i=n.#s+1;!r.type&&i<r.#n.length;i++)for(let s of t.#n){if(typeof s=="string")throw new Error("string part in extglob AST??");s.copyIn(r.#n[i])}n=r,r=n.#i}}return this}push(...t){for(let n of t)if(n!==""){if(typeof n!="string"&&!(n instanceof $l&&n.#i===this))throw new Error("invalid part: "+n);this.#n.push(n)}}toJSON(){let t=this.type===null?this.#n.slice().map(n=>typeof n=="string"?n:n.toJSON()):[this.type,...this.#n.map(n=>n.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#c&&this.#i?.type==="!")&&t.push({}),t}isStart(){if(this.#e===this)return!0;if(!this.#i?.isStart())return!1;if(this.#s===0)return!0;let t=this.#i;for(let n=0;n<this.#s;n++){let r=t.#n[n];if(!(r instanceof $l&&r.type==="!"))return!1}return!0}isEnd(){if(this.#e===this||this.#i?.type==="!")return!0;if(!this.#i?.isEnd())return!1;if(!this.type)return this.#i?.isEnd();let t=this.#i?this.#i.#n.length:0;return this.#s===t-1}copyIn(t){typeof t=="string"?this.push(t):this.push(t.clone(this))}clone(t){let n=new $l(this.type,t);for(let r of this.#n)n.copyIn(r);return n}static#d(t,n,r,i,s){let o=i.maxExtglobRecursion??2,c=!1,l=!1,u=-1,d=!1;if(n.type===null){let y=r,v="";for(;y<t.length;){let x=t.charAt(y++);if(c||x==="\\"){c=!c,v+=x;continue}if(l){y===u+1?(x==="^"||x==="!")&&(d=!0):x==="]"&&!(y===u+2&&d)&&(l=!1),v+=x;continue}else if(x==="["){l=!0,u=y,d=!1,v+=x;continue}if(!i.noext&&Mne(x)&&t.charAt(y)==="("&&s<=o){n.push(v),v="";let S=new $l(x,n);y=$l.#d(t,S,y,i,s+1),n.push(S);continue}v+=x}return n.push(v),y}let p=r+1,f=new $l(null,n),h=[],g="";for(;p<t.length;){let y=t.charAt(p++);if(c||y==="\\"){c=!c,g+=y;continue}if(l){p===u+1?(y==="^"||y==="!")&&(d=!0):y==="]"&&!(p===u+2&&d)&&(l=!1),g+=y;continue}else if(y==="["){l=!0,u=p,d=!1,g+=y;continue}if(!i.noext&&Mne(y)&&t.charAt(p)==="("&&(s<=o||n&&n.#h(y))){let x=n&&n.#h(y)?0:1;f.push(g),g="";let w=new $l(y,f);f.push(w),p=$l.#d(t,w,p,i,s+x);continue}if(y==="|"){f.push(g),g="",h.push(f),f=new $l(null,n);continue}if(y===")")return g===""&&n.#n.length===0&&(n.#p=!0),f.push(g),g="",n.push(...h,f),p;g+=y}return n.type=null,n.#t=void 0,n.#n=[t.substring(r-1)],p}#f(t){return this.#v(t,KWt)}#v(t,n=ZWt){if(!t||typeof t!="object"||t.type!==null||t.#n.length!==1||this.type===null)return!1;let r=t.#n[0];return!r||typeof r!="object"||r.type===null?!1:this.#h(r.type,n)}#h(t,n=JWt){return!!n.get(this.type)?.includes(t)}#O(t,n){let r=t.#n[0],i=new $l(null,r,this.options);i.#n.push(""),r.push(i),this.#w(t,n)}#w(t,n){let r=t.#n[0];this.#n.splice(n,1,...r.#n);for(let i of r.#n)typeof i=="object"&&(i.#i=this);this.#o=void 0}#E(t){return!!GDe.get(this.type)?.has(t)}#_(t){if(!t||typeof t!="object"||t.type!==null||t.#n.length!==1||this.type===null||this.#n.length!==1)return!1;let n=t.#n[0];return!n||typeof n!="object"||n.type===null?!1:this.#E(n.type)}#T(t){let n=GDe.get(this.type),r=t.#n[0],i=n?.get(r.type);if(!i)return!1;this.#n=r.#n;for(let s of this.#n)typeof s=="object"&&(s.#i=this);this.type=i,this.#o=void 0,this.#p=!1}static fromGlob(t,n={}){let r=new $l(null,void 0,n);return $l.#d(t,r,0,n,0),r}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let t=this.toString(),[n,r,i,s]=this.toRegExpSource();if(!(i||this.#t||this.#u.nocase&&!this.#u.nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return r;let c=(this.#u.nocase?"i":"")+(s?"u":"");return Object.assign(new RegExp(`^${n}$`,c),{_src:n,_glob:t})}get options(){return this.#u}toRegExpSource(t){let n=t??!!this.#u.dot;if(this.#e===this&&(this.#l(),this.#m()),!VDe(this)){let l=this.isStart()&&this.isEnd()&&!this.#n.some(h=>typeof h!="string"),u=this.#n.map(h=>{let[g,y,v,x]=typeof h=="string"?$l.#b(h,this.#t,l):h.toRegExpSource(t);return this.#t=this.#t||v,this.#r=this.#r||x,g}).join(""),d="";if(this.isStart()&&typeof this.#n[0]=="string"&&!(this.#n.length===1&&QWt.has(this.#n[0]))){let g=XWt,y=n&&g.has(u.charAt(0))||u.startsWith("\\.")&&g.has(u.charAt(2))||u.startsWith("\\.\\.")&&g.has(u.charAt(4)),v=!n&&!t&&g.has(u.charAt(0));d=y?YWt:v?tM:""}let p="";return this.isEnd()&&this.#e.#c&&this.#i?.type==="!"&&(p="(?:$|\\/)"),[d+u+p,ky(u),this.#t=!!this.#t,this.#r]}let r=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",s=this.#g(n);if(this.isStart()&&this.isEnd()&&!s&&this.type!=="!"){let l=this.toString(),u=this;return u.#n=[l],u.type=null,u.#t=void 0,[l,ky(this.toString()),!1,!1]}let o=!r||t||n||!tM?"":this.#g(!0);o===s&&(o=""),o&&(s=`(?:${s})(?:${o})*?`);let c="";if(this.type==="!"&&this.#p)c=(this.isStart()&&!n?tM:"")+KDe;else{let l=this.type==="!"?"))"+(this.isStart()&&!n&&!t?tM:"")+ZDe+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;c=i+s+l}return[c,ky(s),this.#t=!!this.#t,this.#r]}#l(){if(VDe(this)){let t=0,n=!1;do{n=!0;for(let r=0;r<this.#n.length;r++){let i=this.#n[r];typeof i=="object"&&(i.#l(),this.#v(i)?(n=!1,this.#w(i,r)):this.#f(i)?(n=!1,this.#O(i,r)):this.#_(i)&&(n=!1,this.#T(i)))}}while(!n&&++t<10)}else for(let t of this.#n)typeof t=="object"&&t.#l();this.#o=void 0}#g(t){return this.#n.map(n=>{if(typeof n=="string")throw new Error("string type in extglob ast??");let[r,i,s,o]=n.toRegExpSource(t);return this.#r=this.#r||o,r}).filter(n=>!(this.isStart()&&this.isEnd())||!!n).join("|")}static#b(t,n,r=!1){let i=!1,s="",o=!1,c=!1;for(let l=0;l<t.length;l++){let u=t.charAt(l);if(i){i=!1,s+=(eHt.has(u)?"\\":"")+u;continue}if(u==="*"){if(c)continue;c=!0,s+=r&&/^[*]+$/.test(t)?KDe:ZDe,n=!0;continue}else c=!1;if(u==="\\"){l===t.length-1?s+="\\\\":i=!0;continue}if(u==="["){let[d,p,f,h]=HDe(t,l);if(f){s+=d,o=o||p,l+=f-1,n=n||h;continue}}if(u==="?"){s+=Lne,n=!0;continue}s+=tHt(u)}return[s,ky(t),!!n,o]}};$l=Z1;var jne=a((e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!1}={})=>n?t?e.replace(/[?*()[\]{}]/g,"[$&]"):e.replace(/[?*()[\]\\{}]/g,"\\$&"):t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&"),"escape");var da=a((e,t,n={})=>(HI(t),!n.nocomment&&t.charAt(0)==="#"?!1:new Zx(t,n).match(e)),"minimatch"),rHt=/^\*+([^+@!?*[(]*)$/,iHt=a(e=>t=>!t.startsWith(".")&&t.endsWith(e),"starDotExtTest"),sHt=a(e=>t=>t.endsWith(e),"starDotExtTestDot"),oHt=a(e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),"starDotExtTestNocase"),aHt=a(e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),"starDotExtTestNocaseDot"),cHt=/^\*+\.\*+$/,lHt=a(e=>!e.startsWith(".")&&e.includes("."),"starDotStarTest"),uHt=a(e=>e!=="."&&e!==".."&&e.includes("."),"starDotStarTestDot"),dHt=/^\.\*+$/,pHt=a(e=>e!=="."&&e!==".."&&e.startsWith("."),"dotStarTest"),fHt=/^\*+$/,hHt=a(e=>e.length!==0&&!e.startsWith("."),"starTest"),mHt=a(e=>e.length!==0&&e!=="."&&e!=="..","starTestDot"),gHt=/^\?+([^+@!?*[(]*)?$/,yHt=a(([e,t=""])=>{let n=XDe([e]);return t?(t=t.toLowerCase(),r=>n(r)&&r.toLowerCase().endsWith(t)):n},"qmarksTestNocase"),vHt=a(([e,t=""])=>{let n=QDe([e]);return t?(t=t.toLowerCase(),r=>n(r)&&r.toLowerCase().endsWith(t)):n},"qmarksTestNocaseDot"),wHt=a(([e,t=""])=>{let n=QDe([e]);return t?r=>n(r)&&r.endsWith(t):n},"qmarksTestDot"),bHt=a(([e,t=""])=>{let n=XDe([e]);return t?r=>n(r)&&r.endsWith(t):n},"qmarksTest"),XDe=a(([e])=>{let t=e.length;return n=>n.length===t&&!n.startsWith(".")},"qmarksTestNoExt"),QDe=a(([e])=>{let t=e.length;return n=>n.length===t&&n!=="."&&n!==".."},"qmarksTestNoExtDot"),eMe=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",JDe={win32:{sep:"\\"},posix:{sep:"/"}},xHt=eMe==="win32"?JDe.win32.sep:JDe.posix.sep;da.sep=xHt;var pc=Symbol("globstar **");da.GLOBSTAR=pc;var SHt="[^/]",kHt=SHt+"*?",EHt="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",_Ht="(?:(?!(?:\\/|^)\\.).)*?",THt=a((e,t={})=>n=>da(n,e,t),"filter");da.filter=THt;var ud=a((e,t={})=>Object.assign({},e,t),"ext"),IHt=a(e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return da;let t=da;return Object.assign(a((r,i,s={})=>t(r,i,ud(e,s)),"m"),{Minimatch:class extends t.Minimatch{static{a(this,"Minimatch")}constructor(i,s={}){super(i,ud(e,s))}static defaults(i){return t.defaults(ud(e,i)).Minimatch}},AST:class extends t.AST{static{a(this,"AST")}constructor(i,s,o={}){super(i,s,ud(e,o))}static fromGlob(i,s={}){return t.AST.fromGlob(i,ud(e,s))}},unescape:a((r,i={})=>t.unescape(r,ud(e,i)),"unescape"),escape:a((r,i={})=>t.escape(r,ud(e,i)),"escape"),filter:a((r,i={})=>t.filter(r,ud(e,i)),"filter"),defaults:a(r=>t.defaults(ud(e,r)),"defaults"),makeRe:a((r,i={})=>t.makeRe(r,ud(e,i)),"makeRe"),braceExpand:a((r,i={})=>t.braceExpand(r,ud(e,i)),"braceExpand"),match:a((r,i,s={})=>t.match(r,i,ud(e,s)),"match"),sep:t.sep,GLOBSTAR:pc})},"defaults");da.defaults=IHt;var tMe=a((e,t={})=>(HI(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:BDe(e,{max:t.braceExpandMax})),"braceExpand");da.braceExpand=tMe;var AHt=a((e,t={})=>new Zx(e,t).makeRe(),"makeRe");da.makeRe=AHt;var CHt=a((e,t,n={})=>{let r=new Zx(t,n);return e=e.filter(i=>r.match(i)),r.options.nonull&&!e.length&&e.push(t),e},"match");da.match=CHt;var YDe=/[?*]|[+@!]\(.*?\)|\[|\]/,RHt=a(e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"regExpEscape"),Zx=class{static{a(this,"Minimatch")}options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(t,n={}){HI(t),n=n||{},this.options=n,this.maxGlobstarRecursion=n.maxGlobstarRecursion??200,this.pattern=t,this.platform=n.platform||eMe,this.isWindows=this.platform==="win32";let r="allowWindowsEscape";this.windowsPathsNoEscape=!!n.windowsPathsNoEscape||n[r]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!n.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!n.nonegate,this.comment=!1,this.empty=!1,this.partial=!!n.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=n.windowsNoMagicRoot!==void 0?n.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let n of t)if(typeof n!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,n=this.options;if(!n.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],n.debug&&(this.debug=(...s)=>console.error(...s)),this.debug(this.pattern,this.globSet);let r=this.globSet.map(s=>this.slashSplit(s));this.globParts=this.preprocess(r),this.debug(this.pattern,this.globParts);let i=this.globParts.map((s,o,c)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=s[0]===""&&s[1]===""&&(s[2]==="?"||!YDe.test(s[2]))&&!YDe.test(s[3]),u=/^[a-z]:/i.test(s[0]);if(l)return[...s.slice(0,4),...s.slice(4).map(d=>this.parse(d))];if(u)return[s[0],...s.slice(1).map(d=>this.parse(d))]}return s.map(l=>this.parse(l))});if(this.debug(this.pattern,i),this.set=i.filter(s=>s.indexOf(!1)===-1),this.isWindows)for(let s=0;s<this.set.length;s++){let o=this.set[s];o[0]===""&&o[1]===""&&this.globParts[s][2]==="?"&&typeof o[3]=="string"&&/^[a-z]:$/i.test(o[3])&&(o[2]="?")}this.debug(this.pattern,this.set)}preprocess(t){if(this.options.noglobstar)for(let r of t)for(let i=0;i<r.length;i++)r[i]==="**"&&(r[i]="*");let{optimizationLevel:n=1}=this.options;return n>=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):n>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(n=>{let r=-1;for(;(r=n.indexOf("**",r+1))!==-1;){let i=r;for(;n[i+1]==="**";)i++;i!==r&&n.splice(r,i-r)}return n})}levelOneOptimize(t){return t.map(n=>(n=n.reduce((r,i)=>{let s=r[r.length-1];return i==="**"&&s==="**"?r:i===".."&&s&&s!==".."&&s!=="."&&s!=="**"?(r.pop(),r):(r.push(i),r)},[]),n.length===0?[""]:n))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let n=!1;do{if(n=!1,!this.preserveMultipleSlashes){for(let i=1;i<t.length-1;i++){let s=t[i];i===1&&s===""&&t[0]===""||(s==="."||s==="")&&(n=!0,t.splice(i,1),i--)}t[0]==="."&&t.length===2&&(t[1]==="."||t[1]==="")&&(n=!0,t.pop())}let r=0;for(;(r=t.indexOf("..",r+1))!==-1;){let i=t[r-1];i&&i!=="."&&i!==".."&&i!=="**"&&!(this.isWindows&&/^[a-z]:$/i.test(i))&&(n=!0,t.splice(r-1,2),r-=2)}}while(n);return t.length===0?[""]:t}firstPhasePreProcess(t){let n=!1;do{n=!1;for(let r of t){let i=-1;for(;(i=r.indexOf("**",i+1))!==-1;){let o=i;for(;r[o+1]==="**";)o++;o>i&&r.splice(i+1,o-i);let c=r[i+1],l=r[i+2],u=r[i+3];if(c!==".."||!l||l==="."||l===".."||!u||u==="."||u==="..")continue;n=!0,r.splice(i,1);let d=r.slice(0);d[i]="**",t.push(d),i--}if(!this.preserveMultipleSlashes){for(let o=1;o<r.length-1;o++){let c=r[o];o===1&&c===""&&r[0]===""||(c==="."||c==="")&&(n=!0,r.splice(o,1),o--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(n=!0,r.pop())}let s=0;for(;(s=r.indexOf("..",s+1))!==-1;){let o=r[s-1];if(o&&o!=="."&&o!==".."&&o!=="**"){n=!0;let l=s===1&&r[s+1]==="**"?["."]:[];r.splice(s-1,2,...l),r.length===0&&r.push(""),s-=2}}}}while(n);return t}secondPhasePreProcess(t){for(let n=0;n<t.length-1;n++)for(let r=n+1;r<t.length;r++){let i=this.partsMatch(t[n],t[r],!this.preserveMultipleSlashes);if(i){t[n]=[],t[r]=i;break}}return t.filter(n=>n.length)}partsMatch(t,n,r=!1){let i=0,s=0,o=[],c="";for(;i<t.length&&s<n.length;)if(t[i]===n[s])o.push(c==="b"?n[s]:t[i]),i++,s++;else if(r&&t[i]==="**"&&n[s]===t[i+1])o.push(t[i]),i++;else if(r&&n[s]==="**"&&t[i]===n[s+1])o.push(n[s]),s++;else if(t[i]==="*"&&n[s]&&(this.options.dot||!n[s].startsWith("."))&&n[s]!=="**"){if(c==="b")return!1;c="a",o.push(t[i]),i++,s++}else if(n[s]==="*"&&t[i]&&(this.options.dot||!t[i].startsWith("."))&&t[i]!=="**"){if(c==="a")return!1;c="b",o.push(n[s]),i++,s++}else return!1;return t.length===n.length&&o}parseNegate(){if(this.nonegate)return;let t=this.pattern,n=!1,r=0;for(let i=0;i<t.length&&t.charAt(i)==="!";i++)n=!n,r++;r&&(this.pattern=t.slice(r)),this.negate=n}matchOne(t,n,r=!1){let i=0,s=0;if(this.isWindows){let c=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),l=!c&&t[0]===""&&t[1]===""&&t[2]==="?"&&/^[a-z]:$/i.test(t[3]),u=typeof n[0]=="string"&&/^[a-z]:$/i.test(n[0]),d=!u&&n[0]===""&&n[1]===""&&n[2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3]),p=l?3:c?0:void 0,f=d?3:u?0:void 0;if(typeof p=="number"&&typeof f=="number"){let[h,g]=[t[p],n[f]];h.toLowerCase()===g.toLowerCase()&&(n[f]=h,s=f,i=p)}}let{optimizationLevel:o=1}=this.options;return o>=2&&(t=this.levelTwoFileOptimize(t)),n.includes(pc)?this.#e(t,n,r,i,s):this.#r(t,n,r,i,s)}#e(t,n,r,i,s){let o=n.indexOf(pc,s),c=n.lastIndexOf(pc),[l,u,d]=r?[n.slice(s,o),n.slice(o+1),[]]:[n.slice(s,o),n.slice(o+1,c),n.slice(c+1)];if(l.length){let w=t.slice(i,i+l.length);if(!this.#r(w,l,r,0,0))return!1;i+=l.length,s+=l.length}let p=0;if(d.length){if(d.length+i>t.length)return!1;let w=t.length-d.length;if(this.#r(t,d,r,w,0))p=d.length;else{if(t[t.length-1]!==""||i+d.length===t.length||(w--,!this.#r(t,d,r,w,0)))return!1;p=d.length+1}}if(!u.length){let w=!!p;for(let S=i;S<t.length-p;S++){let k=String(t[S]);if(w=!0,k==="."||k===".."||!this.options.dot&&k.startsWith("."))return!1}return r||w}let f=[[[],0]],h=f[0],g=0,y=[0];for(let w of u)w===pc?(y.push(g),h=[[],0],f.push(h)):(h[0].push(w),g++);let v=f.length-1,x=t.length-p;for(let w of f)w[1]=x-(y[v--]+w[0].length);return!!this.#t(t,f,i,0,r,0,!!p)}#t(t,n,r,i,s,o,c){let l=n[i];if(!l){for(let p=r;p<t.length;p++){c=!0;let f=t[p];if(f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1}return c}let[u,d]=l;for(;r<=d;){if(this.#r(t.slice(0,r+u.length),u,s,r,0)&&o<this.maxGlobstarRecursion){let h=this.#t(t,n,r+u.length,i+1,s,o+1,c);if(h!==!1)return h}let f=t[r];if(f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1;r++}return s||null}#r(t,n,r,i,s){let o,c,l,u;for(o=i,c=s,u=t.length,l=n.length;o<u&&c<l;o++,c++){this.debug("matchOne loop");let d=n[c],p=t[o];if(this.debug(n,d,p),d===!1||d===pc)return!1;let f;if(typeof d=="string"?(f=p===d,this.debug("string match",d,p,f)):(f=d.test(p),this.debug("pattern match",d,p,f)),!f)return!1}if(o===u&&c===l)return!0;if(o===u)return r;if(c===l)return o===u-1&&t[o]==="";throw new Error("wtf?")}braceExpand(){return tMe(this.pattern,this.options)}parse(t){HI(t);let n=this.options;if(t==="**")return pc;if(t==="")return"";let r,i=null;(r=t.match(fHt))?i=n.dot?mHt:hHt:(r=t.match(rHt))?i=(n.nocase?n.dot?aHt:oHt:n.dot?sHt:iHt)(r[1]):(r=t.match(gHt))?i=(n.nocase?n.dot?vHt:yHt:n.dot?wHt:bHt)(r):(r=t.match(cHt))?i=n.dot?uHt:lHt:(r=t.match(dHt))&&(i=pHt);let s=Z1.fromGlob(t,this.options).toMMPattern();return i&&typeof s=="object"&&Reflect.defineProperty(s,"test",{value:i}),s}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let n=this.options,r=n.noglobstar?kHt:n.dot?EHt:_Ht,i=new Set(n.nocase?["i"]:[]),s=t.map(l=>{let u=l.map(p=>{if(p instanceof RegExp)for(let f of p.flags.split(""))i.add(f);return typeof p=="string"?RHt(p):p===pc?pc:p._src});u.forEach((p,f)=>{let h=u[f+1],g=u[f-1];p!==pc||g===pc||(g===void 0?h!==void 0&&h!==pc?u[f+1]="(?:\\/|"+r+"\\/)?"+h:u[f]=r:h===void 0?u[f-1]=g+"(?:\\/|\\/"+r+")?":h!==pc&&(u[f-1]=g+"(?:\\/|\\/"+r+"\\/)"+h,u[f+1]=pc))});let d=u.filter(p=>p!==pc);if(this.partial&&d.length>=1){let p=[];for(let f=1;f<=d.length;f++)p.push(d.slice(0,f).join("/"));return"(?:"+p.join("|")+")"}return d.join("/")}).join("|"),[o,c]=t.length>1?["(?:",")"]:["",""];s="^"+o+s+c+"$",this.partial&&(s="^(?:\\/|"+o+s.slice(1,-1)+c+")$"),this.negate&&(s="^(?!"+s+").+$");try{this.regexp=new RegExp(s,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,n=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&n)return!0;let r=this.options;this.isWindows&&(t=t.split("\\").join("/"));let i=this.slashSplit(t);this.debug(this.pattern,"split",i);let s=this.set;this.debug(this.pattern,"set",s);let o=i[i.length-1];if(!o)for(let c=i.length-2;!o&&c>=0;c--)o=i[c];for(let c of s){let l=i;if(r.matchBase&&c.length===1&&(l=[o]),this.matchOne(l,c,n))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(t){return da.defaults(t).Minimatch}};da.AST=Z1;da.Minimatch=Zx;da.escape=jne;da.unescape=ky;import{gunzipSync as DGt}from"node:zlib";var GI=class{static{a(this,"Diff")}diff(t,n,r={}){let i;typeof r=="function"?(i=r,r={}):"callback"in r&&(i=r.callback);let s=this.castInput(t,r),o=this.castInput(n,r),c=this.removeEmpty(this.tokenize(s,r)),l=this.removeEmpty(this.tokenize(o,r));return this.diffWithOptionsObj(c,l,r,i)}diffWithOptionsObj(t,n,r,i){var s;let o=a(w=>{if(w=this.postProcess(w,r),i){setTimeout(function(){i(w)},0);return}else return w},"done"),c=n.length,l=t.length,u=1,d=c+l;r.maxEditLength!=null&&(d=Math.min(d,r.maxEditLength));let p=(s=r.timeout)!==null&&s!==void 0?s:1/0,f=Date.now()+p,h=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(h[0],n,t,0,r);if(h[0].oldPos+1>=l&&g+1>=c)return o(this.buildValues(h[0].lastComponent,n,t));let y=-1/0,v=1/0,x=a(()=>{for(let w=Math.max(y,-u);w<=Math.min(v,u);w+=2){let S,k=h[w-1],E=h[w+1];k&&(h[w-1]=void 0);let _=!1;if(E){let j=E.oldPos-w;_=E&&0<=j&&j<c}let I=k&&k.oldPos+1<l;if(!_&&!I){h[w]=void 0;continue}if(!I||_&&k.oldPos<E.oldPos?S=this.addToPath(E,!0,!1,0,r):S=this.addToPath(k,!1,!0,1,r),g=this.extractCommon(S,n,t,w,r),S.oldPos+1>=l&&g+1>=c)return o(this.buildValues(S.lastComponent,n,t))||!0;h[w]=S,S.oldPos+1>=l&&(v=Math.min(v,w-1)),g+1>=c&&(y=Math.max(y,w+1))}u++},"execEditLength");if(i)a(function w(){setTimeout(function(){if(u>d||Date.now()>f)return i(void 0);x()||w()},0)},"exec")();else for(;u<=d&&Date.now()<=f;){let w=x();if(w)return w}}addToPath(t,n,r,i,s){let o=t.lastComponent;return o&&!s.oneChangePerToken&&o.added===n&&o.removed===r?{oldPos:t.oldPos+i,lastComponent:{count:o.count+1,added:n,removed:r,previousComponent:o.previousComponent}}:{oldPos:t.oldPos+i,lastComponent:{count:1,added:n,removed:r,previousComponent:o}}}extractCommon(t,n,r,i,s){let o=n.length,c=r.length,l=t.oldPos,u=l-i,d=0;for(;u+1<o&&l+1<c&&this.equals(r[l+1],n[u+1],s);)u++,l++,d++,s.oneChangePerToken&&(t.lastComponent={count:1,previousComponent:t.lastComponent,added:!1,removed:!1});return d&&!s.oneChangePerToken&&(t.lastComponent={count:d,previousComponent:t.lastComponent,added:!1,removed:!1}),t.oldPos=l,u}equals(t,n,r){return r.comparator?r.comparator(t,n):t===n||!!r.ignoreCase&&t.toLowerCase()===n.toLowerCase()}removeEmpty(t){let n=[];for(let r=0;r<t.length;r++)t[r]&&n.push(t[r]);return n}castInput(t,n){return t}tokenize(t,n){return Array.from(t)}join(t){return t.join("")}postProcess(t,n){return t}get useLongestToken(){return!1}buildValues(t,n,r){let i=[],s;for(;t;)i.push(t),s=t.previousComponent,delete t.previousComponent,t=s;i.reverse();let o=i.length,c=0,l=0,u=0;for(;c<o;c++){let d=i[c];if(d.removed)d.value=this.join(r.slice(u,u+d.count)),u+=d.count;else{if(!d.added&&this.useLongestToken){let p=n.slice(l,l+d.count);p=p.map(function(f,h){let g=r[u+h];return g.length>f.length?g:f}),d.value=this.join(p)}else d.value=this.join(n.slice(l,l+d.count));l+=d.count,d.added||(u+=d.count)}}return i}};var Fne=class extends GI{static{a(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=OHt}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
5738
+ `}a(kDe,"pageStyles");F2();var xne="enabled",Sne=Object.freeze({id:"direct",capabilities:Object.freeze(["bash"]),plan:"free",shell:"just-bash-direct",probe:a(e=>e.LOADER===void 0?"available":"needs-binding","probe")}),zI=Object.freeze({id:"dynamic-worker",capabilities:Object.freeze(["bash","coding"]),plan:"paid",shell:"just-bash-isolated",probe:a(e=>e.LOADER===void 0?"needs-binding":"available","probe")}),kne=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===xne?"available":"needs-binding","probe")}),JBt=Object.freeze([kne,zI,Sne]);function Ene(e,t=JBt){return t.filter(n=>n.probe(e)==="available")}a(Ene,"availableEdgeRuntimeProviders");function _ne(e){let t=a(r=>e.find(i=>i.capabilities.includes(r)),"first"),n=t("bash");if(n===void 0)throw new Error("No available runtime provider serves the bash layer.");return{bash:n.id,container:t("container")?.id??null}}a(_ne,"resolveEdgeRuntimeSelection");function KD(e){let t=Ene(e),{bash:n,container:r}=_ne(t);return t.find(i=>i.id===(r??n)).shell}a(KD,"resolveEdgeRuntimeShell");function YBt(){return"dsh-edge@0.19.0/direct"}a(YBt,"resolveEdgeDeploymentId");function BI(e){return{baseURL:tK(e.DEEPSEEK_BASE_URL),maxTokens:iK(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:u1(e.DEEPSEEK_MODEL),reasoningEffort:nK(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:o3(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:rK(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:by(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(BI,"resolveEdgeDeploymentConfig");function XBt(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(XBt,"edgeDeploymentApiKeyConfigured");function QBt(e){let t=tK(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(QBt,"projectedEdgeBaseURL");function Tne(e,t){return{shell:KD(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:YBt(),apiKeyConfigured:XBt(e),baseURL:QBt(e.DEEPSEEK_BASE_URL),maxTokens:iK(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:u1(e.DEEPSEEK_MODEL),reasoningEffort:nK(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:o3(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:rK(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:by(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(Tne,"resolveEdgeDeploymentProfile");function JD(e){BI(e);let t=Tne(e);return{ok:!0,service:"dsh-edge",storage:t.storage,attachmentStorage:t.attachmentStorage,shell:t.shell,agent:"upstream-react-loop-agent",access:"single-owner-cookie",deploymentId:t.deploymentId,...e.CF_VERSION_METADATA===void 0?{}:{workerVersionId:e.CF_VERSION_METADATA.id},version:i1,upstreamVersion:qxe,status:"ready"}}a(JD,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as mcn}from"node:async_hooks";import{RpcTarget as eWt}from"cloudflare:workers";function tWt(e){let{intervalMs:t,ping:n,onFailure:r}=e,i=!1,s=setInterval(()=>{i||n().catch(o=>{i||(i=!0,clearInterval(s),r(o instanceof Error?o:new Error(String(o))))})},t);return()=>{i||(i=!0,clearInterval(s))}}a(tWt,"startHeartbeat");async function nWt(e,t){let n=AbortSignal.timeout(t.timeoutMs),r=await e.fetchPort(t.port,`http://container${t.path}`,{method:"HEAD",signal:n});if(r.body?.cancel(),!r.ok)throw new Error(`computerd health returned ${r.status}`)}a(nWt,"probeComputerdHealth");var rWt="computer.internal",iWt="/health",Ine="/api",sWt=8080,oWt=3e4,aWt=2e4,cWt=1,lWt=2e3,uWt=250,dWt=2e3;function pWt(e,t){if(t===void 0||e===null)return!1;let n=e.indexOf(" ");if(n===-1||e.slice(0,n).toLowerCase()!=="bearer")return!1;let r=e.slice(n+1).trim();if(r.length!==t.length)return!1;let i=0;for(let s=0;s<t.length;s+=1)i|=r.charCodeAt(s)^t.charCodeAt(s);return i===0}a(pWt,"bearerMatches");var XD=class{static{a(this,"CloudflareContainerBackend")}type="cloudflare-container";id;#e;#t;#r;#n;#i;#s;#a;#c;constructor(e){this.id=e.id??"container-shell",this.#t=e.egress??{mode:"none"},this.#r=this.#t.mode==="http-gateway"?crypto.randomUUID():void 0,this.#e={container:e.container,workspace:e.workspace,containerEnv:e.containerEnv,egressHost:e.egressHost??rWt,containerPort:e.containerPort??sWt,connectTimeoutMs:e.connectTimeoutMs??oWt,heartbeatIntervalMs:e.heartbeatIntervalMs??aWt,restartAttempts:e.restartAttempts??cWt,healthProbeTimeoutMs:e.healthProbeTimeoutMs??lWt,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??uWt,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??dWt}}async connect(){if(this.#c)return this.#c;let e=Date.now()+this.#e.connectTimeoutMs,t=await(await this.#e.container()).getWorkspaceContainer(),n=await t.exitInfo().catch(()=>null),r={PORT:String(this.#e.containerPort),MOUNT_POINT:"/workspace",...this.#e.containerEnv},i,s;try{({runtimeId:i,clientSecret:s}=await t.start({env:r,enableInternet:this.#t.mode==="direct"}))}catch(p){throw new yc(this.#d("start",{attempt:1,maxAttempts:this.#e.restartAttempts+1,restarts:0,lastError:p,priorExit:n}),{cause:p})}try{await t.interceptOutboundHttp(this.#e.egressHost,this.#e.workspace),this.#t.mode==="http-gateway"&&this.#r!==void 0&&await t.interceptAllOutboundHttp(this.#e.workspace,this.#r)}catch(p){throw new yc(this.#d("egress",{attempt:1,maxAttempts:this.#e.restartAttempts+1,restarts:0,lastError:p,priorExit:n}),{cause:p})}this.#n=s,this.#u(),i=await this.#p(t,r,e,n,i),await this.#f(t,e),await this.#v(t,e,s);let o=await this.#h(e),c=T8(o),l,u=new Promise(p=>{let f=!1,h=a(()=>{f||(f=!0,l?.(),p(),this.#c=void 0)},"onClose");o.addEventListener("close",h,{once:!0}),o.addEventListener("error",h,{once:!0}),c.onRpcBroken(h)});this.#e.heartbeatIntervalMs>0&&(l=tWt({intervalMs:this.#e.heartbeatIntervalMs,ping:a(()=>c.sync.watermarks(),"ping"),onFailure:a(()=>{try{o.close()}catch{}},"onFailure")}));let d={rpc:c,runtimeId:i,closed:u,close:a(async()=>{l?.();try{c[Symbol.dispose]?.()}catch{}try{o.close()}catch{}this.#c=void 0},"close")};return this.#c=d,d}async handleFetch(e){if(this.#t.mode==="http-gateway"&&this.#r!==void 0&&e.headers.get("x-workspace-egress-token")===this.#r){let i=new Headers(e.headers),s=i.get(VS),o;try{o=new URL(s??"")}catch{return new Response("invalid egress URL",{status:400})}if(o.protocol!=="http:"&&o.protocol!=="https:")return new Response("invalid egress URL",{status:400});i.delete(iC),i.delete(VS);let c=new Request(e,{headers:i});return this.#t.gateway.fetch(new Request(o,c))}if(new URL(e.url).pathname!==Ine)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${Ine} requires a websocket upgrade`,{status:400});if(!pWt(e.headers.get("authorization"),this.#n))return new Response("unauthorized",{status:401,headers:{"www-authenticate":"Bearer"}});let t=new WebSocketPair,[n,r]=[t[0],t[1]];if(r.accept(),this.#s)this.#s(r);else return r.close(1011,"no pending connect"),new Response("no pending connect",{status:409});return new Response(null,{status:101,webSocket:n})}#u(){this.#i=new Promise((e,t)=>{this.#s=e,this.#a=t}),this.#i.catch(()=>{})}#o(){this.#i=void 0,this.#s=void 0,this.#a=void 0}async#p(e,t,n,r,i){let s=this.#e.restartAttempts+1,o=Math.max(0,n-Date.now()),c=Math.max(250,Math.floor(o/s)),l=0,u=0,d,p=i;for(;l<s;){l++;let f=Math.min(n,Date.now()+c);if(await this.#m(e,f).then(()=>!0,h=>(d=h,!1)))return p;if(l<s)try{({runtimeId:p}=await e.restart({env:t,enableInternet:this.#t.mode==="direct"})),u++}catch(h){throw this.#a?.(h),this.#o(),new yc(this.#d("restart",{attempt:l,maxAttempts:s,restarts:u,lastError:h}),{cause:h})}}throw this.#a?.(new Error("computerd never became healthy")),this.#o(),new yc(this.#d("health",{attempt:l,maxAttempts:s,restarts:u,lastError:d,priorExit:r}),d instanceof Error?{cause:d}:void 0)}async#m(e,t){let n=this.#e.healthRetryInitialDelayMs,r;for(;Date.now()<t;)try{await nWt(e,{port:this.#e.containerPort,path:"/health",timeoutMs:Math.min(this.#e.healthProbeTimeoutMs,Math.max(50,t-Date.now()))});return}catch(i){r=i;let s=t-Date.now();if(s<=0)break;await fWt(Math.min(n,s)),n=Math.min(n*2,this.#e.healthRetryMaxDelayMs)}throw r??new Error("computerd health probe timed out")}#d(e,t){let n=t.priorExit?` priorExit=${JSON.stringify(t.priorExit.reason)}`:"";return`CloudflareContainerBackend(${this.id}): connect failed at stage=${e} port=${this.#e.containerPort} attempt=${t.attempt}/${t.maxAttempts} restarts=${t.restarts} timeoutMs=${this.#e.connectTimeoutMs}${n} lastError=${EDe(t.lastError)}`}async#f(e,t){let n;try{let r=await e.fetchPort(this.#e.containerPort,"http://container/api",{signal:AbortSignal.timeout(Math.min(this.#e.healthProbeTimeoutMs,Math.max(50,t-Date.now())))});n=r.status,await r.text().catch(()=>"")}catch{return}if(n!==401)throw this.#a?.(new Error("container is not enforcing RPC_CLIENT_SECRET")),this.#o(),new yc(`CloudflareContainerBackend(${this.id}) [stage=auth]: container served an unauthenticated request to /api with ${n}, so this workspace would run without authorization. A container or image predating RPC_CLIENT_SECRET has to be recycled.`)}async#v(e,t,n){let r=Math.max(0,t-Date.now()),i;try{i=await e.fetchPort(this.#e.containerPort,"http://container/connect",{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${n}`},body:JSON.stringify({base:`http://${this.#e.egressHost}`,health:iWt,api:Ine,healthTimeoutMs:r})})}catch(s){throw this.#a?.(s),this.#o(),new yc(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${EDe(s)}`,{cause:s})}if(!i.ok){let s=await i.text().catch(()=>""),o=new Error(`/connect ${i.status}`);throw this.#a?.(o),this.#o(),new yc(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect returned ${i.status}: ${s}`,{cause:o})}}async#h(e){let t=this.#i;if(!t)throw new Error("CloudflareContainerBackend: upgrade promise missing");let n=Math.max(0,e-Date.now()),r;try{return await Promise.race([t,new Promise((i,s)=>{r=setTimeout(()=>s(new yc(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#o()}}};function fWt(e){return new Promise(t=>setTimeout(t,e))}a(fWt,"sleep");function EDe(e){return e instanceof Error?e.message:String(e)}a(EDe,"describeError");var _De="computer:container-client-secret",hWt=16;function mWt(){let e=crypto.getRandomValues(new Uint8Array(hWt));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(mWt,"generate");var gWt=class{static{a(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(_De);if(typeof e=="string"&&e.length>0)return e;let t=mWt();return await this.storage.put(_De,t),t}},TDe="computer:container-launch-record";async function IDe(e){return{enableInternet:e.enableInternet,envDigest:await vWt(e.env)}}a(IDe,"launchRecordFor");function yWt(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}a(yWt,"sameLaunch");async function vWt(e){let t=Object.keys(e).sort().map(r=>`${r.length}:${r}=${e[r]?.length??0}:${e[r]??""}`).join(";"),n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")}a(vWt,"digestEnv");var wWt=class{static{a(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(TDe)??null}async set(e){await this.storage.put(TDe,e)}},ADe=new WeakMap;function Rne(e){let t=ADe.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},ADe.set(e,t)),t}a(Rne,"getContainerLifecycle");function YD(e){return Rne(e).exit}a(YD,"containerExitInfo");function CDe(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}a(CDe,"formatExitReason");function RDe(e,t,n){let r=Rne(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>$De(r,i,void 0,n),s=>$De(r,i,s,n))}a(RDe,"installContainerMonitor");async function Ane(e,t){let n=Rne(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}a(Ane,"destroyContainerExpectingExit");async function $De(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=CDe(n),o=Date.now();e.exit={reason:s,exitedAt:o},i?console.info({message:"workspace.container.exited",reason:s,exitedAt:o,expected:!0}):console.warn({message:"workspace.container.exited",reason:s,exitedAt:o,expected:!1});try{await r?.()}catch(c){console.error({message:"workspace.container.exit_cleanup_failed",reason:CDe(c),exitedAt:Date.now()})}}a($De,"recordExit");var Cne="computer:container-runtime-identity",bWt=class{static{a(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(Cne)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(Cne,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(Cne)}},xWt=class extends eWt{static{a(this,"WorkspaceContainerAPI")}#e;#t;#r;#n;#i;constructor(e){if(super(),!e.container)throw new Error("WorkspaceContainerAPI: DO is not container-enabled (check wrangler.jsonc)");this.#e=e.container,this.#t=e,this.#r=new bWt(e.storage),this.#n=new gWt(e.storage),this.#i=new wWt(e.storage)}async start(e){let t=YD(this.#t),n=await this.#n.ensure(),r=await IDe(e);if(t!==null){try{await Ane(this.#t,this.#e)}catch{}return this.#s(e,n,r,"launched")}if(!this.#e.running)return this.#s(e,n,r,"launched");let i=await this.#i.get();if(i===null||!yWt(i,r)){console.warn({message:i===null?"container was started outside WorkspaceContainerAPI; relaunching so the requested environment applies":"running container was launched with a different spec; relaunching",component:"workspace-container",requested:r,actual:i});try{await Ane(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return RDe(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await Ane(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await IDe(e),"launched")}async setInactivityTimeout(e){await this.#e.setInactivityTimeout(e)}async#s(e,t,n,r){let i=await this.#r.markStarted();try{this.#e.start({enableInternet:e.enableInternet,env:{...e.env,RPC_CLIENT_SECRET:t}})}catch(s){throw await this.#r.clear(i),s}return await this.#i.set(n),RDe(this.#t,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:YD(this.#t)}}async exitInfo(){return YD(this.#t)}async interceptAllOutboundHttp(e,t){let n=this.#t.exports.WorkspaceProxy({props:{...e,egressToken:t}});await Promise.all([this.#e.interceptAllOutboundHttp(n),this.#e.interceptOutboundHttps("*",n)])}async interceptOutboundHttp(e,t){let n=this.#t.exports;await this.#e.interceptOutboundHttp(e,n.WorkspaceProxy({props:t}))}fetchPort(e,t,n){let r=YD(this.#t);if(r!==null)throw new yc(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function ODe(e){class t extends e{static{a(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new xWt(this.ctx)}}return t}a(ODe,"withWorkspaceContainer");var SWt={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function PDe(e,t){let n=t.indexOf("."),r=t.indexOf("/"),i=n>=0?n:r;if(i<0)return;let s=t.slice(0,i),o=t.slice(i+1),c=SWt[s]??s,l=e[c];if(l===void 0)return;let u=l[o];return typeof u=="function"?u:void 0}a(PDe,"resolve");function kWt(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}a(kWt,"errorResponse");async function $ne(e,t,n,r,i){let s=PDe(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}a($ne,"callEdgeApi");async function DDe(e,t){let r=new URL(t.url).pathname;if(t.method!=="POST"||!r.startsWith("/api/"))return new Response("not found",{status:404});if(r==="/api/respond")return Response.json({accepted:!1,reason:"not-pending"});let i=r.slice(5);if(PDe(e,i)===void 0)return new Response("not found",{status:404});let s;try{s=await t.json()}catch{return new Response("body is not JSON",{status:400})}let o=typeof s.rpcId=="string"?s.rpcId:"invalid-request",c=s.payload??{};try{let l=await $ne(e,i,o,c,t.signal);return l===void 0?new Response("not found",{status:404}):Response.json({type:"server-response",rpcId:l.rpcId,result:l.result})}catch(l){return kWt(o,{code:"internal",message:String(l),details:{}})}}a(DDe,"dispatchEdgeApi");kr();Zs();kg();import{DurableObject as gcn}from"cloudflare:workers";var QD=class{constructor(t,n=Date.now,r=2){this.sleepAfterMs=t;this.now=n;this.maxConcurrent=r}sleepAfterMs;now;maxConcurrent;static{a(this,"ContainerActivity")}inFlight=0;lastActivity;stopping;waiters=[];async admit(t){let n=this.now();for(;this.stopping!==void 0||this.inFlight>=this.maxConcurrent;){if(t?.throwIfAborted(),this.stopping!==void 0){await EWt(this.stopping,t);continue}await new Promise((r,i)=>{let s=a(()=>{t?.removeEventListener("abort",o),r()},"wake"),o=a(()=>{let c=this.waiters.indexOf(s);c!==-1&&this.waiters.splice(c,1),i(t.reason)},"abort");this.waiters.push(s),t?.addEventListener("abort",o,{once:!0})})}return t?.aborted===!0&&(this.waiters.shift()?.(),t.throwIfAborted()),{release:this.begin(),queuedMs:this.now()-n}}begin(){this.inFlight+=1,this.lastActivity=this.now();let t=!1;return()=>{t||(t=!0,this.inFlight-=1,this.lastActivity=this.now(),this.waiters.shift()?.())}}async stopIfIdle(t){return this.idle()?await this.stop(t):"busy"}async stopNow(t){return this.inFlight===0?await this.stop(t):"busy"}snapshot(){return{runningCommands:this.inFlight,lastActivityAt:this.lastActivity??null}}async stop(t){if(this.stopping!==void 0)return"busy";let n="stopped",r=t().catch(i=>{n="failed",this.lastActivity=this.now(),console.error("dsh-edge container stop failed.",i)});this.stopping=r;try{await r}finally{this.stopping=void 0}return n}deadline(){return this.inFlight>0?this.now()+this.sleepAfterMs():this.lastActivity===void 0?this.now():this.lastActivity+this.sleepAfterMs()}idle(){return this.inFlight===0&&(this.lastActivity===void 0||this.now()>=this.lastActivity+this.sleepAfterMs())}};function EWt(e,t){return t===void 0?e:new Promise((n,r)=>{let i=a(()=>r(t.reason),"abort");t.addEventListener("abort",i,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",i))})}a(EWt,"untilAborted");import{WorkerEntrypoint as WJn}from"cloudflare:workers";var _v=Qc(MDe());var One=a((e,t,n)=>{let r=e instanceof RegExp?LDe(e,n):e,i=t instanceof RegExp?LDe(t,n):t,s=r!==null&&i!=null&&_Wt(r,i,n);return s&&{start:s[0],end:s[1],pre:n.slice(0,s[0]),body:n.slice(s[0]+r.length,s[1]),post:n.slice(s[1]+i.length)}},"balanced"),LDe=a((e,t)=>{let n=t.match(e);return n?n[0]:null},"maybeMatch"),_Wt=a((e,t,n)=>{let r,i,s,o,c,l=n.indexOf(e),u=n.indexOf(t,l+1),d=l;if(l>=0&&u>0){if(e===t)return[l,u];for(r=[],s=n.length;d>=0&&!c;){if(d===l)r.push(d),l=n.indexOf(e,d+1);else if(r.length===1){let p=r.pop();p!==void 0&&(c=[p,u])}else i=r.pop(),i!==void 0&&i<s&&(s=i,o=u),u=n.indexOf(t,d+1);d=l<u&&l>=0?l:u}r.length&&o!==void 0&&(c=[s,o])}return c},"range");var jDe="\0SLASH"+Math.random()+"\0",FDe="\0OPEN"+Math.random()+"\0",Dne="\0CLOSE"+Math.random()+"\0",qDe="\0COMMA"+Math.random()+"\0",UDe="\0PERIOD"+Math.random()+"\0",TWt=new RegExp(jDe,"g"),IWt=new RegExp(FDe,"g"),AWt=new RegExp(Dne,"g"),CWt=new RegExp(qDe,"g"),RWt=new RegExp(UDe,"g"),$Wt=/\\\\/g,OWt=/\\{/g,NWt=/\\}/g,PWt=/\\,/g,DWt=/\\\./g,MWt=1e5,LWt=4e6;function Nne(e){return isNaN(e)?e.charCodeAt(0):parseInt(e,10)}a(Nne,"numeric");function jWt(e){return e.replace($Wt,jDe).replace(OWt,FDe).replace(NWt,Dne).replace(PWt,qDe).replace(DWt,UDe)}a(jWt,"escapeBraces");function FWt(e){return e.replace(TWt,"\\").replace(IWt,"{").replace(AWt,"}").replace(CWt,",").replace(RWt,".")}a(FWt,"unescapeBraces");function zDe(e){if(!e)return[""];let t=[],n=One("{","}",e);if(!n)return e.split(",");let{pre:r,body:i,post:s}=n,o=r.split(",");o[o.length-1]+="{"+i+"}";let c=zDe(s);return s.length&&(o[o.length-1]+=c.shift(),o.push.apply(o,c)),t.push.apply(t,o),t}a(zDe,"parseCommaParts");function BDe(e,t={}){if(!e)return[];let{max:n=MWt,maxLength:r=LWt}=t;return e.slice(0,2)==="{}"&&(e="\\{\\}"+e.slice(2)),Pne(jWt(e),n,r,!0).map(FWt)}a(BDe,"expand");function qWt(e){return"{"+e+"}"}a(qWt,"embrace");function UWt(e){return/^-?0\d/.test(e)}a(UWt,"isPadded");function zWt(e,t){return e<=t}a(zWt,"lte");function BWt(e,t){return e>=t}a(BWt,"gte");function WI(e,t,n,r,i,s){let o=[],c=0;for(let l=0;l<e.length;l++)for(let u=0;u<n.length;u++){if(o.length>=r)return o;let d=e[l]+t+n[u];if(!(s&&!d)){if(c+d.length>i)return o;o.push(d),c+=d.length}}return o}a(WI,"combine");function WWt(e,t,n,r){let i=e.split(/\.\./),s=[];if(i[0]===void 0||i[1]===void 0)return s;let o=Nne(i[0]),c=Nne(i[1]),l=Math.max(i[0].length,i[1].length),u=i.length===3&&i[2]!==void 0?Math.max(Math.abs(Nne(i[2])),1):1,d=zWt;c<o&&(u*=-1,d=BWt);let f=i.some(UWt),h=0;for(let g=o;d(g,c)&&s.length<n;g+=u){let y;if(t)y=String.fromCharCode(g),y==="\\"&&(y="");else if(y=String(g),f){let v=l-y.length;if(v>0){let x=new Array(v+1).join("0");g<0?y="-"+x+y.slice(1):y=x+y}}if(h+y.length>r)break;s.push(y),h+=y.length}return s}a(WWt,"expandSequence");function Pne(e,t,n,r){let i=[""],s=!1,o=!0;for(;;){let c=One("{","}",e);if(!c)return WI(i,e,[""],t,n,s);let l=c.pre;if(/\$$/.test(l)){if(i=WI(i,l+"{"+c.body+"}",[""],t,n,s&&!c.post.length),o=!1,!c.post.length)break;e=c.post;continue}let u=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(c.body),d=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(c.body),p=u||d,f=c.body.indexOf(",")>=0;if(!p&&!f){if(c.post.match(/,(?!,).*\}/)){e=c.pre+"{"+c.body+Dne+c.post,r=!0;continue}return WI(i,l+"{"+c.body+"}"+c.post,[""],t,n,s)}o&&(s=r&&!p,o=!1);let h;if(p)h=WWt(c.body,d,t,n);else{let g=zDe(c.body);if(g.length===1&&g[0]!==void 0&&(g=Pne(g[0],t,n,!1).map(qWt),g.length===1)){if(i=WI(i,l+g[0],[""],t,n,s&&!c.post.length),!c.post.length)break;e=c.post;continue}let y=s&&!c.post.length&&!l;for(let x=0;y&&x<i.length;x++)i[x]&&(y=!1);h=[];let v=0;e:for(let x=0;x<g.length;x++){let w=Pne(g[x],t,n,!1);for(let S=0;S<w.length;S++){let k=w[S];if(!(y&&!k)){if(h.length>=t||v+k.length>n)break e;h.push(k),v+=k.length}}}}if(i=WI(i,l,h,t,n,s&&!c.post.length),!c.post.length)break;e=c.post}return i}a(Pne,"expand_");var HI=a(e=>{if(typeof e!="string")throw new TypeError("invalid pattern");if(e.length>65536)throw new TypeError("pattern is too long")},"assertValidPattern");var HWt={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},VI=a(e=>e.replace(/[[\]\\-]/g,"\\$&"),"braceEscape"),VWt=a(e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"regexpEscape"),WDe=a(e=>e.join(""),"rangesToString"),HDe=a((e,t)=>{let n=t;if(e.charAt(n)!=="[")throw new Error("not in a brace expression");let r=[],i=[],s=n+1,o=!1,c=!1,l=!1,u=!1,d=n,p="";e:for(;s<e.length;){let y=e.charAt(s);if((y==="!"||y==="^")&&s===n+1){u=!0,s++;continue}if(y==="]"&&o&&!l){d=s+1;break}if(o=!0,y==="\\"&&!l){l=!0,s++;continue}if(y==="["&&!l){for(let[v,[x,w,S]]of Object.entries(HWt))if(e.startsWith(v,s)){if(p)return["$.",!1,e.length-n,!0];s+=v.length,S?i.push(x):r.push(x),c=c||w;continue e}}if(l=!1,p){y>p?r.push(VI(p)+"-"+VI(y)):y===p&&r.push(VI(y)),p="",s++;continue}if(e.startsWith("-]",s+1)){r.push(VI(y+"-")),s+=2;continue}if(e.startsWith("-",s+1)){p=y,s+=2;continue}r.push(VI(y)),s++}if(d<s)return["",!1,0,!1];if(!r.length&&!i.length)return["$.",!1,e.length-n,!0];if(i.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!u){let y=r[0].length===2?r[0].slice(-1):r[0];return[VWt(y),!1,d-n,!1]}let f="["+(u?"^":"")+WDe(r)+"]",h="["+(u?"":"^")+WDe(i)+"]";return[r.length&&i.length?"("+f+"|"+h+")":r.length?f:h,c,d-n,!0]},"parseClass");var ky=a((e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!0}={})=>n?t?e.replace(/\[([^/\\])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^/\\])\]/g,"$1$2").replace(/\\([^/])/g,"$1"):t?e.replace(/\[([^/\\{}])\]/g,"$1"):e.replace(/((?!\\).|^)\[([^/\\{}])\]/g,"$1$2").replace(/\\([^/{}])/g,"$1"),"unescape");var $l,GWt=new Set(["!","?","+","*","@"]),Mne=a(e=>GWt.has(e),"isExtglobType"),VDe=a(e=>Mne(e.type),"isExtglobAST"),ZWt=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]),KWt=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]),JWt=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]),GDe=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]),YWt="(?!(?:^|/)\\.\\.?(?:$|/))",tM="(?!\\.)",XWt=new Set(["[","."]),QWt=new Set(["..","."]),eHt=new Set("().*{}+?[]^$\\!"),tHt=a(e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"regExpEscape"),Lne="[^/]",ZDe=Lne+"*?",KDe=Lne+"+?",nHt=0,Z1=class{static{a(this,"AST")}type;#e;#t;#r=!1;#n=[];#i;#s;#a;#c=!1;#u;#o;#p=!1;id=++nHt;get depth(){return(this.#i?.depth??-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){return{"@@type":"AST",id:this.id,type:this.type,root:this.#e.id,parent:this.#i?.id,depth:this.depth,partsLength:this.#n.length,parts:this.#n}}constructor(t,n,r={}){this.type=t,t&&(this.#t=!0),this.#i=n,this.#e=this.#i?this.#i.#e:this,this.#u=this.#e===this?r:this.#e.#u,this.#a=this.#e===this?[]:this.#e.#a,t==="!"&&!this.#e.#c&&this.#a.push(this),this.#s=this.#i?this.#i.#n.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let t of this.#n)if(typeof t!="string"&&(t.type||t.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#o!==void 0?this.#o:this.type?this.#o=this.type+"("+this.#n.map(t=>String(t)).join("|")+")":this.#o=this.#n.map(t=>String(t)).join("")}#m(){if(this!==this.#e)throw new Error("should only call on root");if(this.#c)return this;this.toString(),this.#c=!0;let t;for(;t=this.#a.pop();){if(t.type!=="!")continue;let n=t,r=n.#i;for(;r;){for(let i=n.#s+1;!r.type&&i<r.#n.length;i++)for(let s of t.#n){if(typeof s=="string")throw new Error("string part in extglob AST??");s.copyIn(r.#n[i])}n=r,r=n.#i}}return this}push(...t){for(let n of t)if(n!==""){if(typeof n!="string"&&!(n instanceof $l&&n.#i===this))throw new Error("invalid part: "+n);this.#n.push(n)}}toJSON(){let t=this.type===null?this.#n.slice().map(n=>typeof n=="string"?n:n.toJSON()):[this.type,...this.#n.map(n=>n.toJSON())];return this.isStart()&&!this.type&&t.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#c&&this.#i?.type==="!")&&t.push({}),t}isStart(){if(this.#e===this)return!0;if(!this.#i?.isStart())return!1;if(this.#s===0)return!0;let t=this.#i;for(let n=0;n<this.#s;n++){let r=t.#n[n];if(!(r instanceof $l&&r.type==="!"))return!1}return!0}isEnd(){if(this.#e===this||this.#i?.type==="!")return!0;if(!this.#i?.isEnd())return!1;if(!this.type)return this.#i?.isEnd();let t=this.#i?this.#i.#n.length:0;return this.#s===t-1}copyIn(t){typeof t=="string"?this.push(t):this.push(t.clone(this))}clone(t){let n=new $l(this.type,t);for(let r of this.#n)n.copyIn(r);return n}static#d(t,n,r,i,s){let o=i.maxExtglobRecursion??2,c=!1,l=!1,u=-1,d=!1;if(n.type===null){let y=r,v="";for(;y<t.length;){let x=t.charAt(y++);if(c||x==="\\"){c=!c,v+=x;continue}if(l){y===u+1?(x==="^"||x==="!")&&(d=!0):x==="]"&&!(y===u+2&&d)&&(l=!1),v+=x;continue}else if(x==="["){l=!0,u=y,d=!1,v+=x;continue}if(!i.noext&&Mne(x)&&t.charAt(y)==="("&&s<=o){n.push(v),v="";let S=new $l(x,n);y=$l.#d(t,S,y,i,s+1),n.push(S);continue}v+=x}return n.push(v),y}let p=r+1,f=new $l(null,n),h=[],g="";for(;p<t.length;){let y=t.charAt(p++);if(c||y==="\\"){c=!c,g+=y;continue}if(l){p===u+1?(y==="^"||y==="!")&&(d=!0):y==="]"&&!(p===u+2&&d)&&(l=!1),g+=y;continue}else if(y==="["){l=!0,u=p,d=!1,g+=y;continue}if(!i.noext&&Mne(y)&&t.charAt(p)==="("&&(s<=o||n&&n.#h(y))){let x=n&&n.#h(y)?0:1;f.push(g),g="";let w=new $l(y,f);f.push(w),p=$l.#d(t,w,p,i,s+x);continue}if(y==="|"){f.push(g),g="",h.push(f),f=new $l(null,n);continue}if(y===")")return g===""&&n.#n.length===0&&(n.#p=!0),f.push(g),g="",n.push(...h,f),p;g+=y}return n.type=null,n.#t=void 0,n.#n=[t.substring(r-1)],p}#f(t){return this.#v(t,KWt)}#v(t,n=ZWt){if(!t||typeof t!="object"||t.type!==null||t.#n.length!==1||this.type===null)return!1;let r=t.#n[0];return!r||typeof r!="object"||r.type===null?!1:this.#h(r.type,n)}#h(t,n=JWt){return!!n.get(this.type)?.includes(t)}#O(t,n){let r=t.#n[0],i=new $l(null,r,this.options);i.#n.push(""),r.push(i),this.#w(t,n)}#w(t,n){let r=t.#n[0];this.#n.splice(n,1,...r.#n);for(let i of r.#n)typeof i=="object"&&(i.#i=this);this.#o=void 0}#E(t){return!!GDe.get(this.type)?.has(t)}#_(t){if(!t||typeof t!="object"||t.type!==null||t.#n.length!==1||this.type===null||this.#n.length!==1)return!1;let n=t.#n[0];return!n||typeof n!="object"||n.type===null?!1:this.#E(n.type)}#T(t){let n=GDe.get(this.type),r=t.#n[0],i=n?.get(r.type);if(!i)return!1;this.#n=r.#n;for(let s of this.#n)typeof s=="object"&&(s.#i=this);this.type=i,this.#o=void 0,this.#p=!1}static fromGlob(t,n={}){let r=new $l(null,void 0,n);return $l.#d(t,r,0,n,0),r}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let t=this.toString(),[n,r,i,s]=this.toRegExpSource();if(!(i||this.#t||this.#u.nocase&&!this.#u.nocaseMagicOnly&&t.toUpperCase()!==t.toLowerCase()))return r;let c=(this.#u.nocase?"i":"")+(s?"u":"");return Object.assign(new RegExp(`^${n}$`,c),{_src:n,_glob:t})}get options(){return this.#u}toRegExpSource(t){let n=t??!!this.#u.dot;if(this.#e===this&&(this.#l(),this.#m()),!VDe(this)){let l=this.isStart()&&this.isEnd()&&!this.#n.some(h=>typeof h!="string"),u=this.#n.map(h=>{let[g,y,v,x]=typeof h=="string"?$l.#b(h,this.#t,l):h.toRegExpSource(t);return this.#t=this.#t||v,this.#r=this.#r||x,g}).join(""),d="";if(this.isStart()&&typeof this.#n[0]=="string"&&!(this.#n.length===1&&QWt.has(this.#n[0]))){let g=XWt,y=n&&g.has(u.charAt(0))||u.startsWith("\\.")&&g.has(u.charAt(2))||u.startsWith("\\.\\.")&&g.has(u.charAt(4)),v=!n&&!t&&g.has(u.charAt(0));d=y?YWt:v?tM:""}let p="";return this.isEnd()&&this.#e.#c&&this.#i?.type==="!"&&(p="(?:$|\\/)"),[d+u+p,ky(u),this.#t=!!this.#t,this.#r]}let r=this.type==="*"||this.type==="+",i=this.type==="!"?"(?:(?!(?:":"(?:",s=this.#g(n);if(this.isStart()&&this.isEnd()&&!s&&this.type!=="!"){let l=this.toString(),u=this;return u.#n=[l],u.type=null,u.#t=void 0,[l,ky(this.toString()),!1,!1]}let o=!r||t||n||!tM?"":this.#g(!0);o===s&&(o=""),o&&(s=`(?:${s})(?:${o})*?`);let c="";if(this.type==="!"&&this.#p)c=(this.isStart()&&!n?tM:"")+KDe;else{let l=this.type==="!"?"))"+(this.isStart()&&!n&&!t?tM:"")+ZDe+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;c=i+s+l}return[c,ky(s),this.#t=!!this.#t,this.#r]}#l(){if(VDe(this)){let t=0,n=!1;do{n=!0;for(let r=0;r<this.#n.length;r++){let i=this.#n[r];typeof i=="object"&&(i.#l(),this.#v(i)?(n=!1,this.#w(i,r)):this.#f(i)?(n=!1,this.#O(i,r)):this.#_(i)&&(n=!1,this.#T(i)))}}while(!n&&++t<10)}else for(let t of this.#n)typeof t=="object"&&t.#l();this.#o=void 0}#g(t){return this.#n.map(n=>{if(typeof n=="string")throw new Error("string type in extglob ast??");let[r,i,s,o]=n.toRegExpSource(t);return this.#r=this.#r||o,r}).filter(n=>!(this.isStart()&&this.isEnd())||!!n).join("|")}static#b(t,n,r=!1){let i=!1,s="",o=!1,c=!1;for(let l=0;l<t.length;l++){let u=t.charAt(l);if(i){i=!1,s+=(eHt.has(u)?"\\":"")+u;continue}if(u==="*"){if(c)continue;c=!0,s+=r&&/^[*]+$/.test(t)?KDe:ZDe,n=!0;continue}else c=!1;if(u==="\\"){l===t.length-1?s+="\\\\":i=!0;continue}if(u==="["){let[d,p,f,h]=HDe(t,l);if(f){s+=d,o=o||p,l+=f-1,n=n||h;continue}}if(u==="?"){s+=Lne,n=!0;continue}s+=tHt(u)}return[s,ky(t),!!n,o]}};$l=Z1;var jne=a((e,{windowsPathsNoEscape:t=!1,magicalBraces:n=!1}={})=>n?t?e.replace(/[?*()[\]{}]/g,"[$&]"):e.replace(/[?*()[\]\\{}]/g,"\\$&"):t?e.replace(/[?*()[\]]/g,"[$&]"):e.replace(/[?*()[\]\\]/g,"\\$&"),"escape");var da=a((e,t,n={})=>(HI(t),!n.nocomment&&t.charAt(0)==="#"?!1:new Zx(t,n).match(e)),"minimatch"),rHt=/^\*+([^+@!?*[(]*)$/,iHt=a(e=>t=>!t.startsWith(".")&&t.endsWith(e),"starDotExtTest"),sHt=a(e=>t=>t.endsWith(e),"starDotExtTestDot"),oHt=a(e=>(e=e.toLowerCase(),t=>!t.startsWith(".")&&t.toLowerCase().endsWith(e)),"starDotExtTestNocase"),aHt=a(e=>(e=e.toLowerCase(),t=>t.toLowerCase().endsWith(e)),"starDotExtTestNocaseDot"),cHt=/^\*+\.\*+$/,lHt=a(e=>!e.startsWith(".")&&e.includes("."),"starDotStarTest"),uHt=a(e=>e!=="."&&e!==".."&&e.includes("."),"starDotStarTestDot"),dHt=/^\.\*+$/,pHt=a(e=>e!=="."&&e!==".."&&e.startsWith("."),"dotStarTest"),fHt=/^\*+$/,hHt=a(e=>e.length!==0&&!e.startsWith("."),"starTest"),mHt=a(e=>e.length!==0&&e!=="."&&e!=="..","starTestDot"),gHt=/^\?+([^+@!?*[(]*)?$/,yHt=a(([e,t=""])=>{let n=XDe([e]);return t?(t=t.toLowerCase(),r=>n(r)&&r.toLowerCase().endsWith(t)):n},"qmarksTestNocase"),vHt=a(([e,t=""])=>{let n=QDe([e]);return t?(t=t.toLowerCase(),r=>n(r)&&r.toLowerCase().endsWith(t)):n},"qmarksTestNocaseDot"),wHt=a(([e,t=""])=>{let n=QDe([e]);return t?r=>n(r)&&r.endsWith(t):n},"qmarksTestDot"),bHt=a(([e,t=""])=>{let n=XDe([e]);return t?r=>n(r)&&r.endsWith(t):n},"qmarksTest"),XDe=a(([e])=>{let t=e.length;return n=>n.length===t&&!n.startsWith(".")},"qmarksTestNoExt"),QDe=a(([e])=>{let t=e.length;return n=>n.length===t&&n!=="."&&n!==".."},"qmarksTestNoExtDot"),eMe=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",JDe={win32:{sep:"\\"},posix:{sep:"/"}},xHt=eMe==="win32"?JDe.win32.sep:JDe.posix.sep;da.sep=xHt;var pc=Symbol("globstar **");da.GLOBSTAR=pc;var SHt="[^/]",kHt=SHt+"*?",EHt="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",_Ht="(?:(?!(?:\\/|^)\\.).)*?",THt=a((e,t={})=>n=>da(n,e,t),"filter");da.filter=THt;var ud=a((e,t={})=>Object.assign({},e,t),"ext"),IHt=a(e=>{if(!e||typeof e!="object"||!Object.keys(e).length)return da;let t=da;return Object.assign(a((r,i,s={})=>t(r,i,ud(e,s)),"m"),{Minimatch:class extends t.Minimatch{static{a(this,"Minimatch")}constructor(i,s={}){super(i,ud(e,s))}static defaults(i){return t.defaults(ud(e,i)).Minimatch}},AST:class extends t.AST{static{a(this,"AST")}constructor(i,s,o={}){super(i,s,ud(e,o))}static fromGlob(i,s={}){return t.AST.fromGlob(i,ud(e,s))}},unescape:a((r,i={})=>t.unescape(r,ud(e,i)),"unescape"),escape:a((r,i={})=>t.escape(r,ud(e,i)),"escape"),filter:a((r,i={})=>t.filter(r,ud(e,i)),"filter"),defaults:a(r=>t.defaults(ud(e,r)),"defaults"),makeRe:a((r,i={})=>t.makeRe(r,ud(e,i)),"makeRe"),braceExpand:a((r,i={})=>t.braceExpand(r,ud(e,i)),"braceExpand"),match:a((r,i,s={})=>t.match(r,i,ud(e,s)),"match"),sep:t.sep,GLOBSTAR:pc})},"defaults");da.defaults=IHt;var tMe=a((e,t={})=>(HI(e),t.nobrace||!/\{(?:(?!\{).)*\}/.test(e)?[e]:BDe(e,{max:t.braceExpandMax})),"braceExpand");da.braceExpand=tMe;var AHt=a((e,t={})=>new Zx(e,t).makeRe(),"makeRe");da.makeRe=AHt;var CHt=a((e,t,n={})=>{let r=new Zx(t,n);return e=e.filter(i=>r.match(i)),r.options.nonull&&!e.length&&e.push(t),e},"match");da.match=CHt;var YDe=/[?*]|[+@!]\(.*?\)|\[|\]/,RHt=a(e=>e.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"regExpEscape"),Zx=class{static{a(this,"Minimatch")}options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;maxGlobstarRecursion;regexp;constructor(t,n={}){HI(t),n=n||{},this.options=n,this.maxGlobstarRecursion=n.maxGlobstarRecursion??200,this.pattern=t,this.platform=n.platform||eMe,this.isWindows=this.platform==="win32";let r="allowWindowsEscape";this.windowsPathsNoEscape=!!n.windowsPathsNoEscape||n[r]===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!n.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!n.nonegate,this.comment=!1,this.empty=!1,this.partial=!!n.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=n.windowsNoMagicRoot!==void 0?n.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let t of this.set)for(let n of t)if(typeof n!="string")return!0;return!1}debug(...t){}make(){let t=this.pattern,n=this.options;if(!n.nocomment&&t.charAt(0)==="#"){this.comment=!0;return}if(!t){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],n.debug&&(this.debug=(...s)=>console.error(...s)),this.debug(this.pattern,this.globSet);let r=this.globSet.map(s=>this.slashSplit(s));this.globParts=this.preprocess(r),this.debug(this.pattern,this.globParts);let i=this.globParts.map((s,o,c)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=s[0]===""&&s[1]===""&&(s[2]==="?"||!YDe.test(s[2]))&&!YDe.test(s[3]),u=/^[a-z]:/i.test(s[0]);if(l)return[...s.slice(0,4),...s.slice(4).map(d=>this.parse(d))];if(u)return[s[0],...s.slice(1).map(d=>this.parse(d))]}return s.map(l=>this.parse(l))});if(this.debug(this.pattern,i),this.set=i.filter(s=>s.indexOf(!1)===-1),this.isWindows)for(let s=0;s<this.set.length;s++){let o=this.set[s];o[0]===""&&o[1]===""&&this.globParts[s][2]==="?"&&typeof o[3]=="string"&&/^[a-z]:$/i.test(o[3])&&(o[2]="?")}this.debug(this.pattern,this.set)}preprocess(t){if(this.options.noglobstar)for(let r of t)for(let i=0;i<r.length;i++)r[i]==="**"&&(r[i]="*");let{optimizationLevel:n=1}=this.options;return n>=2?(t=this.firstPhasePreProcess(t),t=this.secondPhasePreProcess(t)):n>=1?t=this.levelOneOptimize(t):t=this.adjascentGlobstarOptimize(t),t}adjascentGlobstarOptimize(t){return t.map(n=>{let r=-1;for(;(r=n.indexOf("**",r+1))!==-1;){let i=r;for(;n[i+1]==="**";)i++;i!==r&&n.splice(r,i-r)}return n})}levelOneOptimize(t){return t.map(n=>(n=n.reduce((r,i)=>{let s=r[r.length-1];return i==="**"&&s==="**"?r:i===".."&&s&&s!==".."&&s!=="."&&s!=="**"?(r.pop(),r):(r.push(i),r)},[]),n.length===0?[""]:n))}levelTwoFileOptimize(t){Array.isArray(t)||(t=this.slashSplit(t));let n=!1;do{if(n=!1,!this.preserveMultipleSlashes){for(let i=1;i<t.length-1;i++){let s=t[i];i===1&&s===""&&t[0]===""||(s==="."||s==="")&&(n=!0,t.splice(i,1),i--)}t[0]==="."&&t.length===2&&(t[1]==="."||t[1]==="")&&(n=!0,t.pop())}let r=0;for(;(r=t.indexOf("..",r+1))!==-1;){let i=t[r-1];i&&i!=="."&&i!==".."&&i!=="**"&&!(this.isWindows&&/^[a-z]:$/i.test(i))&&(n=!0,t.splice(r-1,2),r-=2)}}while(n);return t.length===0?[""]:t}firstPhasePreProcess(t){let n=!1;do{n=!1;for(let r of t){let i=-1;for(;(i=r.indexOf("**",i+1))!==-1;){let o=i;for(;r[o+1]==="**";)o++;o>i&&r.splice(i+1,o-i);let c=r[i+1],l=r[i+2],u=r[i+3];if(c!==".."||!l||l==="."||l===".."||!u||u==="."||u==="..")continue;n=!0,r.splice(i,1);let d=r.slice(0);d[i]="**",t.push(d),i--}if(!this.preserveMultipleSlashes){for(let o=1;o<r.length-1;o++){let c=r[o];o===1&&c===""&&r[0]===""||(c==="."||c==="")&&(n=!0,r.splice(o,1),o--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(n=!0,r.pop())}let s=0;for(;(s=r.indexOf("..",s+1))!==-1;){let o=r[s-1];if(o&&o!=="."&&o!==".."&&o!=="**"){n=!0;let l=s===1&&r[s+1]==="**"?["."]:[];r.splice(s-1,2,...l),r.length===0&&r.push(""),s-=2}}}}while(n);return t}secondPhasePreProcess(t){for(let n=0;n<t.length-1;n++)for(let r=n+1;r<t.length;r++){let i=this.partsMatch(t[n],t[r],!this.preserveMultipleSlashes);if(i){t[n]=[],t[r]=i;break}}return t.filter(n=>n.length)}partsMatch(t,n,r=!1){let i=0,s=0,o=[],c="";for(;i<t.length&&s<n.length;)if(t[i]===n[s])o.push(c==="b"?n[s]:t[i]),i++,s++;else if(r&&t[i]==="**"&&n[s]===t[i+1])o.push(t[i]),i++;else if(r&&n[s]==="**"&&t[i]===n[s+1])o.push(n[s]),s++;else if(t[i]==="*"&&n[s]&&(this.options.dot||!n[s].startsWith("."))&&n[s]!=="**"){if(c==="b")return!1;c="a",o.push(t[i]),i++,s++}else if(n[s]==="*"&&t[i]&&(this.options.dot||!t[i].startsWith("."))&&t[i]!=="**"){if(c==="a")return!1;c="b",o.push(n[s]),i++,s++}else return!1;return t.length===n.length&&o}parseNegate(){if(this.nonegate)return;let t=this.pattern,n=!1,r=0;for(let i=0;i<t.length&&t.charAt(i)==="!";i++)n=!n,r++;r&&(this.pattern=t.slice(r)),this.negate=n}matchOne(t,n,r=!1){let i=0,s=0;if(this.isWindows){let c=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),l=!c&&t[0]===""&&t[1]===""&&t[2]==="?"&&/^[a-z]:$/i.test(t[3]),u=typeof n[0]=="string"&&/^[a-z]:$/i.test(n[0]),d=!u&&n[0]===""&&n[1]===""&&n[2]==="?"&&typeof n[3]=="string"&&/^[a-z]:$/i.test(n[3]),p=l?3:c?0:void 0,f=d?3:u?0:void 0;if(typeof p=="number"&&typeof f=="number"){let[h,g]=[t[p],n[f]];h.toLowerCase()===g.toLowerCase()&&(n[f]=h,s=f,i=p)}}let{optimizationLevel:o=1}=this.options;return o>=2&&(t=this.levelTwoFileOptimize(t)),n.includes(pc)?this.#e(t,n,r,i,s):this.#r(t,n,r,i,s)}#e(t,n,r,i,s){let o=n.indexOf(pc,s),c=n.lastIndexOf(pc),[l,u,d]=r?[n.slice(s,o),n.slice(o+1),[]]:[n.slice(s,o),n.slice(o+1,c),n.slice(c+1)];if(l.length){let w=t.slice(i,i+l.length);if(!this.#r(w,l,r,0,0))return!1;i+=l.length,s+=l.length}let p=0;if(d.length){if(d.length+i>t.length)return!1;let w=t.length-d.length;if(this.#r(t,d,r,w,0))p=d.length;else{if(t[t.length-1]!==""||i+d.length===t.length||(w--,!this.#r(t,d,r,w,0)))return!1;p=d.length+1}}if(!u.length){let w=!!p;for(let S=i;S<t.length-p;S++){let k=String(t[S]);if(w=!0,k==="."||k===".."||!this.options.dot&&k.startsWith("."))return!1}return r||w}let f=[[[],0]],h=f[0],g=0,y=[0];for(let w of u)w===pc?(y.push(g),h=[[],0],f.push(h)):(h[0].push(w),g++);let v=f.length-1,x=t.length-p;for(let w of f)w[1]=x-(y[v--]+w[0].length);return!!this.#t(t,f,i,0,r,0,!!p)}#t(t,n,r,i,s,o,c){let l=n[i];if(!l){for(let p=r;p<t.length;p++){c=!0;let f=t[p];if(f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1}return c}let[u,d]=l;for(;r<=d;){if(this.#r(t.slice(0,r+u.length),u,s,r,0)&&o<this.maxGlobstarRecursion){let h=this.#t(t,n,r+u.length,i+1,s,o+1,c);if(h!==!1)return h}let f=t[r];if(f==="."||f===".."||!this.options.dot&&f.startsWith("."))return!1;r++}return s||null}#r(t,n,r,i,s){let o,c,l,u;for(o=i,c=s,u=t.length,l=n.length;o<u&&c<l;o++,c++){this.debug("matchOne loop");let d=n[c],p=t[o];if(this.debug(n,d,p),d===!1||d===pc)return!1;let f;if(typeof d=="string"?(f=p===d,this.debug("string match",d,p,f)):(f=d.test(p),this.debug("pattern match",d,p,f)),!f)return!1}if(o===u&&c===l)return!0;if(o===u)return r;if(c===l)return o===u-1&&t[o]==="";throw new Error("wtf?")}braceExpand(){return tMe(this.pattern,this.options)}parse(t){HI(t);let n=this.options;if(t==="**")return pc;if(t==="")return"";let r,i=null;(r=t.match(fHt))?i=n.dot?mHt:hHt:(r=t.match(rHt))?i=(n.nocase?n.dot?aHt:oHt:n.dot?sHt:iHt)(r[1]):(r=t.match(gHt))?i=(n.nocase?n.dot?vHt:yHt:n.dot?wHt:bHt)(r):(r=t.match(cHt))?i=n.dot?uHt:lHt:(r=t.match(dHt))&&(i=pHt);let s=Z1.fromGlob(t,this.options).toMMPattern();return i&&typeof s=="object"&&Reflect.defineProperty(s,"test",{value:i}),s}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let t=this.set;if(!t.length)return this.regexp=!1,this.regexp;let n=this.options,r=n.noglobstar?kHt:n.dot?EHt:_Ht,i=new Set(n.nocase?["i"]:[]),s=t.map(l=>{let u=l.map(p=>{if(p instanceof RegExp)for(let f of p.flags.split(""))i.add(f);return typeof p=="string"?RHt(p):p===pc?pc:p._src});u.forEach((p,f)=>{let h=u[f+1],g=u[f-1];p!==pc||g===pc||(g===void 0?h!==void 0&&h!==pc?u[f+1]="(?:\\/|"+r+"\\/)?"+h:u[f]=r:h===void 0?u[f-1]=g+"(?:\\/|\\/"+r+")?":h!==pc&&(u[f-1]=g+"(?:\\/|\\/"+r+"\\/)"+h,u[f+1]=pc))});let d=u.filter(p=>p!==pc);if(this.partial&&d.length>=1){let p=[];for(let f=1;f<=d.length;f++)p.push(d.slice(0,f).join("/"));return"(?:"+p.join("|")+")"}return d.join("/")}).join("|"),[o,c]=t.length>1?["(?:",")"]:["",""];s="^"+o+s+c+"$",this.partial&&(s="^(?:\\/|"+o+s.slice(1,-1)+c+")$"),this.negate&&(s="^(?!"+s+").+$");try{this.regexp=new RegExp(s,[...i].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(t){return this.preserveMultipleSlashes?t.split("/"):this.isWindows&&/^\/\/[^/]+/.test(t)?["",...t.split(/\/+/)]:t.split(/\/+/)}match(t,n=this.partial){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return t==="";if(t==="/"&&n)return!0;let r=this.options;this.isWindows&&(t=t.split("\\").join("/"));let i=this.slashSplit(t);this.debug(this.pattern,"split",i);let s=this.set;this.debug(this.pattern,"set",s);let o=i[i.length-1];if(!o)for(let c=i.length-2;!o&&c>=0;c--)o=i[c];for(let c of s){let l=i;if(r.matchBase&&c.length===1&&(l=[o]),this.matchOne(l,c,n))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(t){return da.defaults(t).Minimatch}};da.AST=Z1;da.Minimatch=Zx;da.escape=jne;da.unescape=ky;import{gunzipSync as DGt}from"node:zlib";var GI=class{static{a(this,"Diff")}diff(t,n,r={}){let i;typeof r=="function"?(i=r,r={}):"callback"in r&&(i=r.callback);let s=this.castInput(t,r),o=this.castInput(n,r),c=this.removeEmpty(this.tokenize(s,r)),l=this.removeEmpty(this.tokenize(o,r));return this.diffWithOptionsObj(c,l,r,i)}diffWithOptionsObj(t,n,r,i){var s;let o=a(w=>{if(w=this.postProcess(w,r),i){setTimeout(function(){i(w)},0);return}else return w},"done"),c=n.length,l=t.length,u=1,d=c+l;r.maxEditLength!=null&&(d=Math.min(d,r.maxEditLength));let p=(s=r.timeout)!==null&&s!==void 0?s:1/0,f=Date.now()+p,h=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(h[0],n,t,0,r);if(h[0].oldPos+1>=l&&g+1>=c)return o(this.buildValues(h[0].lastComponent,n,t));let y=-1/0,v=1/0,x=a(()=>{for(let w=Math.max(y,-u);w<=Math.min(v,u);w+=2){let S,k=h[w-1],E=h[w+1];k&&(h[w-1]=void 0);let _=!1;if(E){let j=E.oldPos-w;_=E&&0<=j&&j<c}let I=k&&k.oldPos+1<l;if(!_&&!I){h[w]=void 0;continue}if(!I||_&&k.oldPos<E.oldPos?S=this.addToPath(E,!0,!1,0,r):S=this.addToPath(k,!1,!0,1,r),g=this.extractCommon(S,n,t,w,r),S.oldPos+1>=l&&g+1>=c)return o(this.buildValues(S.lastComponent,n,t))||!0;h[w]=S,S.oldPos+1>=l&&(v=Math.min(v,w-1)),g+1>=c&&(y=Math.max(y,w+1))}u++},"execEditLength");if(i)a(function w(){setTimeout(function(){if(u>d||Date.now()>f)return i(void 0);x()||w()},0)},"exec")();else for(;u<=d&&Date.now()<=f;){let w=x();if(w)return w}}addToPath(t,n,r,i,s){let o=t.lastComponent;return o&&!s.oneChangePerToken&&o.added===n&&o.removed===r?{oldPos:t.oldPos+i,lastComponent:{count:o.count+1,added:n,removed:r,previousComponent:o.previousComponent}}:{oldPos:t.oldPos+i,lastComponent:{count:1,added:n,removed:r,previousComponent:o}}}extractCommon(t,n,r,i,s){let o=n.length,c=r.length,l=t.oldPos,u=l-i,d=0;for(;u+1<o&&l+1<c&&this.equals(r[l+1],n[u+1],s);)u++,l++,d++,s.oneChangePerToken&&(t.lastComponent={count:1,previousComponent:t.lastComponent,added:!1,removed:!1});return d&&!s.oneChangePerToken&&(t.lastComponent={count:d,previousComponent:t.lastComponent,added:!1,removed:!1}),t.oldPos=l,u}equals(t,n,r){return r.comparator?r.comparator(t,n):t===n||!!r.ignoreCase&&t.toLowerCase()===n.toLowerCase()}removeEmpty(t){let n=[];for(let r=0;r<t.length;r++)t[r]&&n.push(t[r]);return n}castInput(t,n){return t}tokenize(t,n){return Array.from(t)}join(t){return t.join("")}postProcess(t,n){return t}get useLongestToken(){return!1}buildValues(t,n,r){let i=[],s;for(;t;)i.push(t),s=t.previousComponent,delete t.previousComponent,t=s;i.reverse();let o=i.length,c=0,l=0,u=0;for(;c<o;c++){let d=i[c];if(d.removed)d.value=this.join(r.slice(u,u+d.count)),u+=d.count;else{if(!d.added&&this.useLongestToken){let p=n.slice(l,l+d.count);p=p.map(function(f,h){let g=r[u+h];return g.length>f.length?g:f}),d.value=this.join(p)}else d.value=this.join(n.slice(l,l+d.count));l+=d.count,d.added||(u+=d.count)}}return i}};var Fne=class extends GI{static{a(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=OHt}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
5739
5739
  `))&&(t=t.trim()),(!r.newlineIsToken||!n.includes(`
5740
5740
  `))&&(n=n.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
5741
5741
  `)&&(t=t.slice(0,-1)),n.endsWith(`