dsh-edge 0.24.0-alpha.1 → 0.24.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-edge",
3
- "version": "0.24.0-alpha.1",
3
+ "version": "0.24.0",
4
4
  "description": "Your DeepSeek Harness, anywhere — deploy a persistent personal coding agent to Cloudflare Workers in one command",
5
5
  "author": "pawaca",
6
6
  "license": "MIT",
@@ -152,7 +152,7 @@ Known schemas:
152
152
  - `)}`,new Error(Ke)}let wt=`${c}/$ref`,st=Ks(e,je,n,r,i,s,o,wt,l);if(st.valid||Ee.push({instanceLocation:o,keyword:"$ref",keywordLocation:wt,error:"A subschema had errors."},...st.errors),n==="4"||n==="7")return{valid:Ee.length===0,errors:Ee}}if(Array.isArray(g)){let ze=g.length,je=!1;for(let wt=0;wt<ze;wt++)if(d===g[wt]||g[wt]==="integer"&&d==="number"&&e%1===0&&e===e){je=!0;break}je||Ee.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)&&Ee.push({instanceLocation:o,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${d}" is invalid. Expected "${g}".`}):g!==void 0&&d!==g&&Ee.push({instanceLocation:o,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${d}" is invalid. Expected "${g}".`});if(y!==void 0&&(d==="object"||d==="array"?bx(e,y)||Ee.push({instanceLocation:o,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(y)}.`}):e!==y&&Ee.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=>bx(e,ze))||Ee.push({instanceLocation:o,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`}):v.some(ze=>e===ze)||Ee.push({instanceLocation:o,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})),b!==void 0){let ze=`${c}/not`;Ks(e,b,n,r,i,s,o,ze).valid&&Ee.push({instanceLocation:o,keyword:"not",keywordLocation:ze,error:'Instance matched "not" schema.'})}let ut=[];if(S!==void 0){let ze=`${c}/anyOf`,je=Ee.length,wt=!1;for(let st=0;st<S.length;st++){let Ke=S[st],yt=Object.create(l),Oe=Ks(e,Ke,n,r,i,h===!0?s:null,o,`${ze}/${st}`,yt);Ee.push(...Oe.errors),wt=wt||Oe.valid,Oe.valid&&ut.push(yt)}wt?Ee.length=je:Ee.splice(je,0,{instanceLocation:o,keyword:"anyOf",keywordLocation:ze,error:"Instance does not match any subschemas."})}if(k!==void 0){let ze=`${c}/allOf`,je=Ee.length,wt=!0;for(let st=0;st<k.length;st++){let Ke=k[st],yt=Object.create(l),Oe=Ks(e,Ke,n,r,i,h===!0?s:null,o,`${ze}/${st}`,yt);Ee.push(...Oe.errors),wt=wt&&Oe.valid,Oe.valid&&ut.push(yt)}wt?Ee.length=je:Ee.splice(je,0,{instanceLocation:o,keyword:"allOf",keywordLocation:ze,error:"Instance does not match every subschema."})}if(E!==void 0){let ze=`${c}/oneOf`,je=Ee.length,wt=E.filter((st,Ke)=>{let yt=Object.create(l),Oe=Ks(e,st,n,r,i,h===!0?s:null,o,`${ze}/${Ke}`,yt);return Ee.push(...Oe.errors),Oe.valid&&ut.push(yt),Oe.valid}).length;wt===1?Ee.length=je:Ee.splice(je,0,{instanceLocation:o,keyword:"oneOf",keywordLocation:ze,error:`Instance does not match exactly one subschema (${wt} matches).`})}if((d==="object"||d==="array")&&Object.assign(l,...ut),_!==void 0){let ze=`${c}/if`;if(Ks(e,_,n,r,i,s,o,ze,l).valid){if(T!==void 0){let wt=Ks(e,T,n,r,i,s,o,`${c}/then`,l);wt.valid||Ee.push({instanceLocation:o,keyword:"if",keywordLocation:ze,error:'Instance does not match "then" schema.'},...wt.errors)}}else if(P!==void 0){let wt=Ks(e,P,n,r,i,s,o,`${c}/else`,l);wt.valid||Ee.push({instanceLocation:o,keyword:"if",keywordLocation:ze,error:'Instance does not match "else" schema.'},...wt.errors)}}if(d==="object"){if(w!==void 0)for(let st of w)st in e||Ee.push({instanceLocation:o,keyword:"required",keywordLocation:`${c}/required`,error:`Instance does not have required property "${st}".`});let ze=Object.keys(e);if(I!==void 0&&ze.length<I&&Ee.push({instanceLocation:o,keyword:"minProperties",keywordLocation:`${c}/minProperties`,error:`Instance does not have at least ${I} properties.`}),U!==void 0&&ze.length>U&&Ee.push({instanceLocation:o,keyword:"maxProperties",keywordLocation:`${c}/maxProperties`,error:`Instance does not have at least ${U} properties.`}),C!==void 0){let st=`${c}/propertyNames`;for(let Ke in e){let yt=`${o}/${vu(Ke)}`,Oe=Ks(Ke,C,n,r,i,s,yt,st);Oe.valid||Ee.push({instanceLocation:o,keyword:"propertyNames",keywordLocation:st,error:`Property name "${Ke}" does not match schema.`},...Oe.errors)}}if(R!==void 0){let st=`${c}/dependantRequired`;for(let Ke in R)if(Ke in e){let yt=R[Ke];for(let Oe of yt)Oe in e||Ee.push({instanceLocation:o,keyword:"dependentRequired",keywordLocation:st,error:`Instance has "${Ke}" but does not have "${Oe}".`})}}if(O!==void 0)for(let st in O){let Ke=`${c}/dependentSchemas`;if(st in e){let yt=Ks(e,O[st],n,r,i,s,o,`${Ke}/${vu(st)}`,l);yt.valid||Ee.push({instanceLocation:o,keyword:"dependentSchemas",keywordLocation:Ke,error:`Instance has "${st}" but does not match dependant schema.`},...yt.errors)}}if(N!==void 0){let st=`${c}/dependencies`;for(let Ke in N)if(Ke in e){let yt=N[Ke];if(Array.isArray(yt))for(let Oe of yt)Oe in e||Ee.push({instanceLocation:o,keyword:"dependencies",keywordLocation:st,error:`Instance has "${Ke}" but does not have "${Oe}".`});else{let Oe=Ks(e,yt,n,r,i,s,o,`${st}/${vu(Ke)}`);Oe.valid||Ee.push({instanceLocation:o,keyword:"dependencies",keywordLocation:st,error:`Instance has "${Ke}" but does not match dependant schema.`},...Oe.errors)}}}let je=Object.create(null),wt=!1;if(j!==void 0){let st=`${c}/properties`;for(let Ke in j){if(!(Ke in e))continue;let yt=`${o}/${vu(Ke)}`,Oe=Ks(e[Ke],j[Ke],n,r,i,s,yt,`${st}/${vu(Ke)}`);if(Oe.valid)l[Ke]=je[Ke]=!0;else if(wt=i,Ee.push({instanceLocation:o,keyword:"properties",keywordLocation:st,error:`Property "${Ke}" does not match schema.`},...Oe.errors),wt)break}}if(!wt&&$!==void 0){let st=`${c}/patternProperties`;for(let Ke in $){let yt=new RegExp(Ke,"u"),Oe=$[Ke];for(let _t in e){if(!yt.test(_t))continue;let Gt=`${o}/${vu(_t)}`,ht=Ks(e[_t],Oe,n,r,i,s,Gt,`${st}/${vu(Ke)}`);ht.valid?l[_t]=je[_t]=!0:(wt=i,Ee.push({instanceLocation:o,keyword:"patternProperties",keywordLocation:st,error:`Property "${_t}" matches pattern "${Ke}" but does not match associated schema.`},...ht.errors))}}}if(!wt&&W!==void 0){let st=`${c}/additionalProperties`;for(let Ke in e){if(je[Ke])continue;let yt=`${o}/${vu(Ke)}`,Oe=Ks(e[Ke],W,n,r,i,s,yt,st);Oe.valid?l[Ke]=!0:(wt=i,Ee.push({instanceLocation:o,keyword:"additionalProperties",keywordLocation:st,error:`Property "${Ke}" does not match additional properties schema.`},...Oe.errors))}}else if(!wt&&Y!==void 0){let st=`${c}/unevaluatedProperties`;for(let Ke in e)if(!l[Ke]){let yt=`${o}/${vu(Ke)}`,Oe=Ks(e[Ke],Y,n,r,i,s,yt,st);Oe.valid?l[Ke]=!0:Ee.push({instanceLocation:o,keyword:"unevaluatedProperties",keywordLocation:st,error:`Property "${Ke}" does not match unevaluated properties schema.`},...Oe.errors)}}}else if(d==="array"){le!==void 0&&e.length>le&&Ee.push({instanceLocation:o,keyword:"maxItems",keywordLocation:`${c}/maxItems`,error:`Array has too many items (${e.length} > ${le}).`}),we!==void 0&&e.length<we&&Ee.push({instanceLocation:o,keyword:"minItems",keywordLocation:`${c}/minItems`,error:`Array has too few items (${e.length} < ${we}).`});let ze=e.length,je=0,wt=!1;if(D!==void 0){let st=`${c}/prefixItems`,Ke=Math.min(D.length,ze);for(;je<Ke;je++){let yt=Ks(e[je],D[je],n,r,i,s,`${o}/${je}`,`${st}/${je}`);if(l[je]=!0,!yt.valid&&(wt=i,Ee.push({instanceLocation:o,keyword:"prefixItems",keywordLocation:st,error:"Items did not match schema."},...yt.errors),wt))break}}if(G!==void 0){let st=`${c}/items`;if(Array.isArray(G)){let Ke=Math.min(G.length,ze);for(;je<Ke;je++){let yt=Ks(e[je],G[je],n,r,i,s,`${o}/${je}`,`${st}/${je}`);if(l[je]=!0,!yt.valid&&(wt=i,Ee.push({instanceLocation:o,keyword:"items",keywordLocation:st,error:"Items did not match schema."},...yt.errors),wt))break}}else for(;je<ze;je++){let Ke=Ks(e[je],G,n,r,i,s,`${o}/${je}`,st);if(l[je]=!0,!Ke.valid&&(wt=i,Ee.push({instanceLocation:o,keyword:"items",keywordLocation:st,error:"Items did not match schema."},...Ke.errors),wt))break}if(!wt&&X!==void 0){let Ke=`${c}/additionalItems`;for(;je<ze;je++){let yt=Ks(e[je],X,n,r,i,s,`${o}/${je}`,Ke);l[je]=!0,yt.valid||(wt=i,Ee.push({instanceLocation:o,keyword:"additionalItems",keywordLocation:Ke,error:"Items did not match additional items schema."},...yt.errors))}}}if(z!==void 0)if(ze===0&&ne===void 0)Ee.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)Ee.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array has less items (${ze}) than minContains (${ne}).`});else{let st=`${c}/contains`,Ke=Ee.length,yt=0;for(let Oe=0;Oe<ze;Oe++){let _t=Ks(e[Oe],z,n,r,i,s,`${o}/${Oe}`,st);_t.valid?(l[Oe]=!0,yt++):Ee.push(..._t.errors)}yt>=(ne||0)&&(Ee.length=Ke),ne===void 0&&ge===void 0&&yt===0?Ee.splice(Ke,0,{instanceLocation:o,keyword:"contains",keywordLocation:st,error:"Array does not contain item matching schema."}):ne!==void 0&&yt<ne?Ee.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array must contain at least ${ne} items matching schema. Only ${yt} items were found.`}):ge!==void 0&&yt>ge&&Ee.push({instanceLocation:o,keyword:"maxContains",keywordLocation:`${c}/maxContains`,error:`Array may contain at most ${ge} items matching schema. ${yt} items were found.`})}if(!wt&&Q!==void 0){let st=`${c}/unevaluatedItems`;for(je;je<ze;je++){if(l[je])continue;let Ke=Ks(e[je],Q,n,r,i,s,`${o}/${je}`,st);l[je]=!0,Ke.valid||Ee.push({instanceLocation:o,keyword:"unevaluatedItems",keywordLocation:st,error:"Items did not match unevaluated items schema."},...Ke.errors)}}if(Se)for(let st=0;st<ze;st++){let Ke=e[st],yt=typeof Ke=="object"&&Ke!==null;for(let Oe=0;Oe<ze;Oe++){if(st===Oe)continue;let _t=e[Oe];(Ke===_t||yt&&(typeof _t=="object"&&_t!==null)&&bx(Ke,_t))&&(Ee.push({instanceLocation:o,keyword:"uniqueItems",keywordLocation:`${c}/uniqueItems`,error:`Duplicate items at indexes ${st} and ${Oe}.`}),st=Number.MAX_SAFE_INTEGER,Oe=Number.MAX_SAFE_INTEGER)}}}else if(d==="number"){if(n==="4"?(_e!==void 0&&(de===!0&&e<=_e||e<_e)&&Ee.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${de?"or equal to ":""} ${_e}.`}),ue!==void 0&&(ot===!0&&e>=ue||e>ue)&&Ee.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${ot?"or equal to ":""} ${ue}.`})):(_e!==void 0&&e<_e&&Ee.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${_e}.`}),ue!==void 0&&e>ue&&Ee.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${ue}.`}),de!==void 0&&e<=de&&Ee.push({instanceLocation:o,keyword:"exclusiveMinimum",keywordLocation:`${c}/exclusiveMinimum`,error:`${e} is less than ${de}.`}),ot!==void 0&&e>=ot&&Ee.push({instanceLocation:o,keyword:"exclusiveMaximum",keywordLocation:`${c}/exclusiveMaximum`,error:`${e} is greater than or equal to ${ot}.`})),Ve!==void 0){let ze=e%Ve;Math.abs(0-ze)>=11920929e-14&&Math.abs(Ve-ze)>=11920929e-14&&Ee.push({instanceLocation:o,keyword:"multipleOf",keywordLocation:`${c}/multipleOf`,error:`${e} is not a multiple of ${Ve}.`})}}else if(d==="string"){let ze=it===void 0&&Ce===void 0?0:AEe(e);it!==void 0&&ze<it&&Ee.push({instanceLocation:o,keyword:"minLength",keywordLocation:`${c}/minLength`,error:`String is too short (${ze} < ${it}).`}),Ce!==void 0&&ze>Ce&&Ee.push({instanceLocation:o,keyword:"maxLength",keywordLocation:`${c}/maxLength`,error:`String is too long (${ze} > ${Ce}).`}),ke!==void 0&&!new RegExp(ke,"u").test(e)&&Ee.push({instanceLocation:o,keyword:"pattern",keywordLocation:`${c}/pattern`,error:"String does not match pattern."}),M!==void 0&&iY[M]&&!iY[M](e)&&Ee.push({instanceLocation:o,keyword:"format",keywordLocation:`${c}/format`,error:`String does not match format "${M}".`})}return{valid:Ee.length===0,errors:Ee}}var aY=ae(()=>{rY();O9();sY();R9();oY();a(Ks,"validate")});var $9,IEe=ae(()=>{O9();aY();$9=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=ym(t)}validate(t){return Ks(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,n){n&&(t={...t,$id:n}),ym(t,this.lookup)}}});var CEe=ae(()=>{rY();O9();sY();R9();TEe();oY();aY();IEe()});var N9,REe=ae(()=>{CEe();N9=class{static{a(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let n=new $9(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 Do,P9=ae(()=>{"use strict";Do={probeTimeoutMs:3e4,callTimeoutMs:6e4,maxToolsPerServer:128,maxCatalogPages:10,maxCatalogBytes:131072,maxDescriptionLength:512,maxErrorMessageChars:300,maxPublicNameLength:64,maxInstructionsLength:1024,metaToolThreshold:20}});import{createHash as Vxt}from"node:crypto";function Kxt(e){let t=e.replace(/[.*+?^${}()|[\]\\]/gu,n=>n==="*"?"\0":`\\${n}`);return new RegExp(`^${t.replaceAll("\0",".*")}$`)}function OEe(e,t,n){let r=t??"read_only";return r==="allow_all"?"allow":r==="approve_all"?"ask":n===!0?"allow":n===!1?"ask":Gxt.some(i=>Kxt(i).test(e))?"allow":"ask"}function Uf(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,Do.maxErrorMessageChars)}function $Ee(e,t){let n=`mcp__${e}__${t}`,r=n.replace(/[^A-Za-z0-9_-]/gu,"_");if(r===n&&r.length<=Do.maxPublicNameLength)return r;let i=Zxt(e,t),s=Do.maxPublicNameLength-i.length-1;return`${r.slice(0,s)}_${i}`}function Zxt(e,t){return Vxt("sha256").update(`${e}\0${t}`).digest("hex").slice(0,12)}function NEe(e){if(!(e==null||typeof e!="object"))try{let t=JSON.parse(JSON.stringify(e));return ny(t),t}catch{return}}function Xxt(e){return Yxt.has(e)}function PEe(e){return e.type!=="image"||e.data===void 0||e.mimeType===void 0||!Xxt(e.mimeType)||!Jxt.test(e.data)?void 0:{data:Uint8Array.from(atob(e.data),n=>n.charCodeAt(0)),mediaType:e.mimeType}}function MEe(e){return e.some(t=>t.type==="image"&&t.data!==void 0)}function q6(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 Gxt,Yxt,Jxt,M9=ae(()=>{"use strict";js();P9();Gxt=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a(Kxt,"globToRegExp");a(OEe,"evaluateMcpToolPolicy");a(Uf,"scrubMcpErrorMessage");a($Ee,"publicToolName");a(Zxt,"hashSuffix");a(NEe,"supportedOutputSchema");Yxt=new Set(["image/png","image/jpeg"]),Jxt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(Xxt,"isImageMediaType");a(PEe,"decodeImageBlock");a(MEe,"containsImage");a(q6,"mapMcpResultToContentBlocks")});var cY,DEe=ae(()=>{cY={name:"dsh-edge",version:"0.24.0-alpha.1",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.2"},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",yaml:"2.9.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.2","@deepseek-ai/dsh-agent-instructions":"0.2.0-rc.2","@deepseek-ai/dsh-agent-loop":"0.2.0-rc.2","@deepseek-ai/dsh-anonymous-user-id":"0.2.0-rc.2","@deepseek-ai/dsh-api-gateway":"0.2.0-rc.2","@deepseek-ai/dsh-api-job-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-remotes":"0.2.0-rc.2","@deepseek-ai/dsh-api-session-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-settings-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-workspace-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-workspace-files":"0.2.0-rc.2","@deepseek-ai/dsh-attachment":"0.2.0-rc.2","@deepseek-ai/dsh-brand":"0.2.0-rc.2","@deepseek-ai/dsh-client-locale":"0.2.0-rc.2","@deepseek-ai/dsh-client-store":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-chat":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-conversation":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-settings":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-settings-general":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-theme":"0.2.0-rc.2","@deepseek-ai/dsh-command-compact":"0.2.0-rc.2","@deepseek-ai/dsh-command-goal":"0.2.0-rc.2","@deepseek-ai/dsh-commands":"0.2.0-rc.2","@deepseek-ai/dsh-compaction":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-basic":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-image-offload":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-tool-result-pruner":"0.2.0-rc.2","@deepseek-ai/dsh-credentials":"0.2.0-rc.2","@deepseek-ai/dsh-file-reference":"0.2.0-rc.2","@deepseek-ai/dsh-fs":"0.2.0-rc.2","@deepseek-ai/dsh-fs-observation-policy":"0.2.0-rc.2","@deepseek-ai/dsh-goal":"0.2.0-rc.2","@deepseek-ai/dsh-goal-round-driver":"0.2.0-rc.2","@deepseek-ai/dsh-home-paths":"0.2.0-rc.2","@deepseek-ai/dsh-host-directory-picker":"0.2.0-rc.2","@deepseek-ai/dsh-host-plugin-inventory":"0.2.0-rc.2","@deepseek-ai/dsh-invariants":"0.2.0-rc.2","@deepseek-ai/dsh-jobs":"0.2.0-rc.2","@deepseek-ai/dsh-jobs-local":"0.2.0-rc.2","@deepseek-ai/dsh-launch-environment":"0.2.0-rc.2","@deepseek-ai/dsh-llm":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek-api-key":"0.2.0-rc.2","@deepseek-ai/dsh-llm-retry":"0.2.0-rc.2","@deepseek-ai/dsh-message-feedback":"0.2.0-rc.2","@deepseek-ai/dsh-output-retention":"0.2.0-rc.2","@deepseek-ai/dsh-plan-mode":"0.2.0-rc.2","@deepseek-ai/dsh-ptc-runtime":"0.2.0-rc.2","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.0-rc.2","@deepseek-ai/dsh-sandbox":"0.2.0-rc.2","@deepseek-ai/dsh-schedule":"0.2.0-rc.2","@deepseek-ai/dsh-scope":"0.2.0-rc.2","@deepseek-ai/dsh-session":"0.2.0-rc.2","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.0-rc.2","@deepseek-ai/dsh-session-format":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-catalog":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.0-rc.2","@deepseek-ai/dsh-session-persistence":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection-cache":"0.2.0-rc.2","@deepseek-ai/dsh-session-stats":"0.2.0-rc.2","@deepseek-ai/dsh-session-query":"0.2.0-rc.2","@deepseek-ai/dsh-session-reference":"0.2.0-rc.2","@deepseek-ai/dsh-session-title":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-llm":"0.2.0-rc.2","@deepseek-ai/dsh-settings":"0.2.0-rc.2","@deepseek-ai/dsh-skill":"0.2.0-rc.2","@deepseek-ai/dsh-spill":"0.2.0-rc.2","@deepseek-ai/dsh-spill-policy":"0.2.0-rc.2","@deepseek-ai/dsh-storage":"0.2.0-rc.2","@deepseek-ai/dsh-storage-domain":"0.2.0-rc.2","@deepseek-ai/dsh-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-in-process-driver":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-fork-in-process":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-spawn-in-process":"0.2.0-rc.2","@deepseek-ai/dsh-system-prompt":"0.2.0-rc.2","@deepseek-ai/dsh-timeout":"0.2.0-rc.2","@deepseek-ai/dsh-token-meter":"0.2.0-rc.2","@deepseek-ai/dsh-tool-ask-user":"0.2.0-rc.2","@deepseek-ai/dsh-tool-call-timeout-policy":"0.2.0-rc.2","@deepseek-ai/dsh-tool-fs":"0.2.0-rc.2","@deepseek-ai/dsh-tool-fs-search":"0.2.0-rc.2","@deepseek-ai/dsh-tool-goal":"0.2.0-rc.2","@deepseek-ai/dsh-tool-jobs":"0.2.0-rc.2","@deepseek-ai/dsh-tool-skill":"0.2.0-rc.2","@deepseek-ai/dsh-tool-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-tool-subagent-control":"0.2.0-rc.2","@deepseek-ai/dsh-tool-present":"0.2.0-rc.2","@deepseek-ai/dsh-tool-todo":"0.2.0-rc.2","@deepseek-ai/dsh-tool-web":"0.2.0-rc.2","@deepseek-ai/dsh-tool-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-tools":"0.2.0-rc.2","@deepseek-ai/dsh-typert-protocol":"0.2.0-rc.2","@deepseek-ai/dsh-typert-registry":"0.2.0-rc.2","@deepseek-ai/dsh-user-approval":"0.2.0-rc.2","@deepseek-ai/dsh-user-questions":"0.2.0-rc.2","@deepseek-ai/dsh-util-values":"0.2.0-rc.2","@deepseek-ai/dsh-web":"0.2.0-rc.2","@deepseek-ai/dsh-web-fetch-http":"0.2.0-rc.2","@deepseek-ai/dsh-web-search-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-workspace":"0.2.0-rc.2","@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",minimatch:"10.2.6",playwright:"^1.49.0",re2js:"1.3.3",sucrase:"3.35.1",typescript:"^6.0.3",vitest:"^4.1.8",ws:"^8.21.0"}}});var By,LEe,jEe,U6=ae(()=>{"use strict";DEe();By=cY.version,LEe=cY.dshEdge.upstreamVersion,jEe=`npx dsh-edge@${By.includes("-")?"next":"latest"} upgrade`});function r2t(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 i2t(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function vm(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 e2t)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(i2t(i)){let s=r2t(i),o=s??i;for(let c of t2t)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 n2t)if(c.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function s2t(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function FEe(e,t,n){vm(e);let r=new C9(new URL(e),{requestInit:{headers:s2t(t),signal:n},fetch:zy}),i=new A9({name:"dsh-edge",version:By},{capabilities:{},jsonSchemaValidator:o2t});return await i.connect(r),{client:i,close:a(async()=>{await i.close().catch(()=>{})},"close")}}async function qEe(e,t,n){let r=AbortSignal.timeout(Do.probeTimeoutMs),i;try{i=await FEe(t,n,r)}catch(c){throw new Error(Uf(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<Do.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>=Do.maxToolsPerServer)break;let v=$Ee(e,y.name);if(l.has(v))throw new Error(`Server listed tool "${y.name}" more than once`);l.add(v);let w=y.annotations?.readOnlyHint,b=NEe(y.outputSchema);c.push({name:y.name,publicName:v,description:y.description??"",inputSchema:y.inputSchema??{type:"object"},...b!==void 0?{outputSchema:b}:{},...w!==void 0?{annotations:{readOnlyHint:w}}:{}})}if(c.length>=Do.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,Do.maxInstructionsLength):void 0}}finally{await o()}}async function D9(e,t,n,r,i,s){let o=s??Do.callTimeoutMs,c=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),l;try{l=await FEe(e,r,c)}catch(u){throw new Error(Uf(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(Uf(u instanceof Error?u.message:String(u)))}finally{await l.close()}}var e2t,t2t,n2t,o2t,zy,B6=ae(()=>{"use strict";zke();SEe();REe();M9();P9();U6();e2t=[".internal",".local",".localhost"],t2t=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],n2t=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(r2t,"extractMappedIPv4");a(i2t,"isIpAddress");a(vm,"assertSafeUrl");a(s2t,"buildHeaders");o2t=new N9,zy=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(FEe,"connectClient");a(qEe,"probe");a(D9,"callTool")});import{Buffer as a2t}from"node:buffer";function d2t(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&u2t.has(e.code)}function BEe(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&l2t.has(e.code)}function zEe(e,t,n){let r=a2t.from(e,"base64");if(e.length===0&&t==="reject"||r.toString("base64")!==e)throw new pr(n==="INVALID_IMAGE_BASE64"?"Image upload is not canonical base64.":"File upload is not canonical base64.",n);return new Uint8Array(r)}function p2t(e){return zEe(e,"reject","INVALID_IMAGE_BASE64")}function f2t(e){return{data:p2t(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function z6(e,t){return e.saveImages(t.map(f2t))}async function h2t(e,t){return e.saveFile({data:zEe(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function WEe(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 lY(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 UEe,c2t,l2t,u2t,pr,uY,wm=ae(()=>{Gn();UEe=["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"],c2t=[...UEe,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],l2t=new Set(UEe),u2t=new Set(c2t),pr=class extends Error{static{a(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};a(d2t,"isAttachmentError");a(BEe,"isImageAdmissionError");a(zEe,"decodeCanonicalBase64");a(p2t,"decodeBase64");a(f2t,"saveInput");a(z6,"admitEncodedImages");a(h2t,"admitEncodedFile");a(WEe,"requestImageDimensions");a(lY,"longEdgeDimensions");uY=class extends Et{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 pr("Image batch exceeds the configured image-count limit.","TOO_MANY_IMAGES");if(e.reduce((i,s)=>i+s.data.byteLength,0)>n)throw new pr("Image batch exceeds the configured aggregate image-byte limit.","IMAGES_TOO_LARGE");for(let i of e)if(!r.includes(i.mediaType))throw new pr(`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 z6(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 h2t(this,e)}isAttachmentError(e){return d2t(e)}imageHostPath(e){}saveFile(e){return Promise.reject(new pr("The mounted attachment provider cannot store verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}saveFileStream(e){return Promise.reject(new pr("The mounted attachment provider cannot stream verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}async*readFileStream(e,t){t?.throwIfAborted(),await Promise.reject(new pr("The mounted attachment provider cannot read verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}fileHostPath(e){}readImageRequest(e,t,n){return n?.throwIfAborted(),Promise.reject(new pr("The mounted attachment provider cannot derive model-request images.","ATTACHMENT_PROJECTION_UNSUPPORTED"))}}});var j9={};an(j9,{buildAuthorizationUrl:()=>k2t,discoverEndpoints:()=>x2t,exchangeCode:()=>E2t,isTokenExpired:()=>T2t,refreshToken:()=>_2t,registerClient:()=>S2t});function KEe(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 b2t(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 x2t(e){let t=AbortSignal.timeout(L9),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);vm(i.href);let s=await zy(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);vm(d.href);let p=await zy(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 S2t(e,t,n){let r=AbortSignal.timeout(L9);vm(e);let i=await zy(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 k2t(e,t,n,r,i){let s=KEe(32),o=KEe(64),c=await b2t(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 E2t(e,t,n,r,i,s){let o=AbortSignal.timeout(L9),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),vm(e);let l=await zy(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 ZEe(await l.json())}async function _2t(e,t,n,r){let i=AbortSignal.timeout(L9),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),vm(e);let o=await zy(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 ZEe(await o.json())}function ZEe(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 T2t(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var L9,F9=ae(()=>{"use strict";B6();L9=1e4;a(KEe,"randomString");a(b2t,"sha256Base64Url");a(x2t,"discoverEndpoints");a(S2t,"registerClient");a(k2t,"buildAuthorizationUrl");a(E2t,"exchangeCode");a(_2t,"refreshToken");a(ZEe,"parseTokenResponse");a(T2t,"isTokenExpired")});var Bn,r_e,xx=ae(()=>{Gn();mr();Bn=class extends Wr{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},r_e=class extends Et{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new Bn("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function K6(e){return Y9.test(e)}function J9(e){return e.invocation.modelInvocable}function kx(e){return e.invocation.userInvocable}function CY(e){let t=ukt(e);return[`<skill_content name="${dkt(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 Gxt,Yxt,Jxt,M9=ae(()=>{"use strict";js();P9();Gxt=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a(Kxt,"globToRegExp");a(OEe,"evaluateMcpToolPolicy");a(Uf,"scrubMcpErrorMessage");a($Ee,"publicToolName");a(Zxt,"hashSuffix");a(NEe,"supportedOutputSchema");Yxt=new Set(["image/png","image/jpeg"]),Jxt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(Xxt,"isImageMediaType");a(PEe,"decodeImageBlock");a(MEe,"containsImage");a(q6,"mapMcpResultToContentBlocks")});var cY,DEe=ae(()=>{cY={name:"dsh-edge",version:"0.24.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.2"},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",yaml:"2.9.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.2","@deepseek-ai/dsh-agent-instructions":"0.2.0-rc.2","@deepseek-ai/dsh-agent-loop":"0.2.0-rc.2","@deepseek-ai/dsh-anonymous-user-id":"0.2.0-rc.2","@deepseek-ai/dsh-api-gateway":"0.2.0-rc.2","@deepseek-ai/dsh-api-job-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-remotes":"0.2.0-rc.2","@deepseek-ai/dsh-api-session-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-settings-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-workspace-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-workspace-files":"0.2.0-rc.2","@deepseek-ai/dsh-attachment":"0.2.0-rc.2","@deepseek-ai/dsh-brand":"0.2.0-rc.2","@deepseek-ai/dsh-client-locale":"0.2.0-rc.2","@deepseek-ai/dsh-client-store":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-chat":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-conversation":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-settings":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-settings-general":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-theme":"0.2.0-rc.2","@deepseek-ai/dsh-command-compact":"0.2.0-rc.2","@deepseek-ai/dsh-command-goal":"0.2.0-rc.2","@deepseek-ai/dsh-commands":"0.2.0-rc.2","@deepseek-ai/dsh-compaction":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-basic":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-image-offload":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-tool-result-pruner":"0.2.0-rc.2","@deepseek-ai/dsh-credentials":"0.2.0-rc.2","@deepseek-ai/dsh-file-reference":"0.2.0-rc.2","@deepseek-ai/dsh-fs":"0.2.0-rc.2","@deepseek-ai/dsh-fs-observation-policy":"0.2.0-rc.2","@deepseek-ai/dsh-goal":"0.2.0-rc.2","@deepseek-ai/dsh-goal-round-driver":"0.2.0-rc.2","@deepseek-ai/dsh-home-paths":"0.2.0-rc.2","@deepseek-ai/dsh-host-directory-picker":"0.2.0-rc.2","@deepseek-ai/dsh-host-plugin-inventory":"0.2.0-rc.2","@deepseek-ai/dsh-invariants":"0.2.0-rc.2","@deepseek-ai/dsh-jobs":"0.2.0-rc.2","@deepseek-ai/dsh-jobs-local":"0.2.0-rc.2","@deepseek-ai/dsh-launch-environment":"0.2.0-rc.2","@deepseek-ai/dsh-llm":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek-api-key":"0.2.0-rc.2","@deepseek-ai/dsh-llm-retry":"0.2.0-rc.2","@deepseek-ai/dsh-message-feedback":"0.2.0-rc.2","@deepseek-ai/dsh-output-retention":"0.2.0-rc.2","@deepseek-ai/dsh-plan-mode":"0.2.0-rc.2","@deepseek-ai/dsh-ptc-runtime":"0.2.0-rc.2","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.0-rc.2","@deepseek-ai/dsh-sandbox":"0.2.0-rc.2","@deepseek-ai/dsh-schedule":"0.2.0-rc.2","@deepseek-ai/dsh-scope":"0.2.0-rc.2","@deepseek-ai/dsh-session":"0.2.0-rc.2","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.0-rc.2","@deepseek-ai/dsh-session-format":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-catalog":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.0-rc.2","@deepseek-ai/dsh-session-persistence":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection-cache":"0.2.0-rc.2","@deepseek-ai/dsh-session-stats":"0.2.0-rc.2","@deepseek-ai/dsh-session-query":"0.2.0-rc.2","@deepseek-ai/dsh-session-reference":"0.2.0-rc.2","@deepseek-ai/dsh-session-title":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-llm":"0.2.0-rc.2","@deepseek-ai/dsh-settings":"0.2.0-rc.2","@deepseek-ai/dsh-skill":"0.2.0-rc.2","@deepseek-ai/dsh-spill":"0.2.0-rc.2","@deepseek-ai/dsh-spill-policy":"0.2.0-rc.2","@deepseek-ai/dsh-storage":"0.2.0-rc.2","@deepseek-ai/dsh-storage-domain":"0.2.0-rc.2","@deepseek-ai/dsh-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-in-process-driver":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-fork-in-process":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-spawn-in-process":"0.2.0-rc.2","@deepseek-ai/dsh-system-prompt":"0.2.0-rc.2","@deepseek-ai/dsh-timeout":"0.2.0-rc.2","@deepseek-ai/dsh-token-meter":"0.2.0-rc.2","@deepseek-ai/dsh-tool-ask-user":"0.2.0-rc.2","@deepseek-ai/dsh-tool-call-timeout-policy":"0.2.0-rc.2","@deepseek-ai/dsh-tool-fs":"0.2.0-rc.2","@deepseek-ai/dsh-tool-fs-search":"0.2.0-rc.2","@deepseek-ai/dsh-tool-goal":"0.2.0-rc.2","@deepseek-ai/dsh-tool-jobs":"0.2.0-rc.2","@deepseek-ai/dsh-tool-skill":"0.2.0-rc.2","@deepseek-ai/dsh-tool-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-tool-subagent-control":"0.2.0-rc.2","@deepseek-ai/dsh-tool-present":"0.2.0-rc.2","@deepseek-ai/dsh-tool-todo":"0.2.0-rc.2","@deepseek-ai/dsh-tool-web":"0.2.0-rc.2","@deepseek-ai/dsh-tool-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-tools":"0.2.0-rc.2","@deepseek-ai/dsh-typert-protocol":"0.2.0-rc.2","@deepseek-ai/dsh-typert-registry":"0.2.0-rc.2","@deepseek-ai/dsh-user-approval":"0.2.0-rc.2","@deepseek-ai/dsh-user-questions":"0.2.0-rc.2","@deepseek-ai/dsh-util-values":"0.2.0-rc.2","@deepseek-ai/dsh-web":"0.2.0-rc.2","@deepseek-ai/dsh-web-fetch-http":"0.2.0-rc.2","@deepseek-ai/dsh-web-search-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-workspace":"0.2.0-rc.2","@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",minimatch:"10.2.6",playwright:"^1.49.0",re2js:"1.3.3",sucrase:"3.35.1",typescript:"^6.0.3",vitest:"^4.1.8",ws:"^8.21.0"}}});var By,LEe,jEe,U6=ae(()=>{"use strict";DEe();By=cY.version,LEe=cY.dshEdge.upstreamVersion,jEe=`npx dsh-edge@${By.includes("-")?"next":"latest"} upgrade`});function r2t(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 i2t(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function vm(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 e2t)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(i2t(i)){let s=r2t(i),o=s??i;for(let c of t2t)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 n2t)if(c.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function s2t(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function FEe(e,t,n){vm(e);let r=new C9(new URL(e),{requestInit:{headers:s2t(t),signal:n},fetch:zy}),i=new A9({name:"dsh-edge",version:By},{capabilities:{},jsonSchemaValidator:o2t});return await i.connect(r),{client:i,close:a(async()=>{await i.close().catch(()=>{})},"close")}}async function qEe(e,t,n){let r=AbortSignal.timeout(Do.probeTimeoutMs),i;try{i=await FEe(t,n,r)}catch(c){throw new Error(Uf(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<Do.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>=Do.maxToolsPerServer)break;let v=$Ee(e,y.name);if(l.has(v))throw new Error(`Server listed tool "${y.name}" more than once`);l.add(v);let w=y.annotations?.readOnlyHint,b=NEe(y.outputSchema);c.push({name:y.name,publicName:v,description:y.description??"",inputSchema:y.inputSchema??{type:"object"},...b!==void 0?{outputSchema:b}:{},...w!==void 0?{annotations:{readOnlyHint:w}}:{}})}if(c.length>=Do.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,Do.maxInstructionsLength):void 0}}finally{await o()}}async function D9(e,t,n,r,i,s){let o=s??Do.callTimeoutMs,c=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),l;try{l=await FEe(e,r,c)}catch(u){throw new Error(Uf(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(Uf(u instanceof Error?u.message:String(u)))}finally{await l.close()}}var e2t,t2t,n2t,o2t,zy,B6=ae(()=>{"use strict";zke();SEe();REe();M9();P9();U6();e2t=[".internal",".local",".localhost"],t2t=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],n2t=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(r2t,"extractMappedIPv4");a(i2t,"isIpAddress");a(vm,"assertSafeUrl");a(s2t,"buildHeaders");o2t=new N9,zy=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(FEe,"connectClient");a(qEe,"probe");a(D9,"callTool")});import{Buffer as a2t}from"node:buffer";function d2t(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&u2t.has(e.code)}function BEe(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&l2t.has(e.code)}function zEe(e,t,n){let r=a2t.from(e,"base64");if(e.length===0&&t==="reject"||r.toString("base64")!==e)throw new pr(n==="INVALID_IMAGE_BASE64"?"Image upload is not canonical base64.":"File upload is not canonical base64.",n);return new Uint8Array(r)}function p2t(e){return zEe(e,"reject","INVALID_IMAGE_BASE64")}function f2t(e){return{data:p2t(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function z6(e,t){return e.saveImages(t.map(f2t))}async function h2t(e,t){return e.saveFile({data:zEe(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function WEe(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 lY(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 UEe,c2t,l2t,u2t,pr,uY,wm=ae(()=>{Gn();UEe=["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"],c2t=[...UEe,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],l2t=new Set(UEe),u2t=new Set(c2t),pr=class extends Error{static{a(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};a(d2t,"isAttachmentError");a(BEe,"isImageAdmissionError");a(zEe,"decodeCanonicalBase64");a(p2t,"decodeBase64");a(f2t,"saveInput");a(z6,"admitEncodedImages");a(h2t,"admitEncodedFile");a(WEe,"requestImageDimensions");a(lY,"longEdgeDimensions");uY=class extends Et{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 pr("Image batch exceeds the configured image-count limit.","TOO_MANY_IMAGES");if(e.reduce((i,s)=>i+s.data.byteLength,0)>n)throw new pr("Image batch exceeds the configured aggregate image-byte limit.","IMAGES_TOO_LARGE");for(let i of e)if(!r.includes(i.mediaType))throw new pr(`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 z6(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 h2t(this,e)}isAttachmentError(e){return d2t(e)}imageHostPath(e){}saveFile(e){return Promise.reject(new pr("The mounted attachment provider cannot store verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}saveFileStream(e){return Promise.reject(new pr("The mounted attachment provider cannot stream verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}async*readFileStream(e,t){t?.throwIfAborted(),await Promise.reject(new pr("The mounted attachment provider cannot read verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}fileHostPath(e){}readImageRequest(e,t,n){return n?.throwIfAborted(),Promise.reject(new pr("The mounted attachment provider cannot derive model-request images.","ATTACHMENT_PROJECTION_UNSUPPORTED"))}}});var j9={};an(j9,{buildAuthorizationUrl:()=>k2t,discoverEndpoints:()=>x2t,exchangeCode:()=>E2t,isTokenExpired:()=>T2t,refreshToken:()=>_2t,registerClient:()=>S2t});function KEe(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 b2t(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 x2t(e){let t=AbortSignal.timeout(L9),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);vm(i.href);let s=await zy(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);vm(d.href);let p=await zy(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 S2t(e,t,n){let r=AbortSignal.timeout(L9);vm(e);let i=await zy(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 k2t(e,t,n,r,i){let s=KEe(32),o=KEe(64),c=await b2t(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 E2t(e,t,n,r,i,s){let o=AbortSignal.timeout(L9),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),vm(e);let l=await zy(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 ZEe(await l.json())}async function _2t(e,t,n,r){let i=AbortSignal.timeout(L9),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),vm(e);let o=await zy(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 ZEe(await o.json())}function ZEe(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 T2t(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var L9,F9=ae(()=>{"use strict";B6();L9=1e4;a(KEe,"randomString");a(b2t,"sha256Base64Url");a(x2t,"discoverEndpoints");a(S2t,"registerClient");a(k2t,"buildAuthorizationUrl");a(E2t,"exchangeCode");a(_2t,"refreshToken");a(ZEe,"parseTokenResponse");a(T2t,"isTokenExpired")});var Bn,r_e,xx=ae(()=>{Gn();mr();Bn=class extends Wr{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},r_e=class extends Et{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new Bn("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function K6(e){return Y9.test(e)}function J9(e){return e.invocation.modelInvocable}function kx(e){return e.invocation.userInvocable}function CY(e){let t=ukt(e);return[`<skill_content name="${dkt(e.name)}">`,"<skill_resources>",...t,"</skill_resources>","","<skill_instructions>",e.content,"</skill_instructions>","</skill_content>"].join(`
156
156
  `)}function ukt(e){let t=e.resourceBase;if(t===void 0)return[`Resources for this skill are managed by provider "${Sx(e.provider)}".`,"Load referenced resources only as needed."];switch(t.kind){case"directory":return[`Base directory for this skill: ${Sx(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: ${Sx(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: ${Sx(t.description)}`,"Load referenced resources only as needed."];default:return Qr(t,"SkillResourceBase.kind")}}function dkt(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;")}function Sx(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function fkt(e,t){if(Array.isArray(e))return{candidates:e,complete:!0};if(e===null||typeof e!="object")throw E_e(t);let n=e;if(!Array.isArray(n.candidates)||typeof n.complete!="boolean")throw E_e(t);return n}function E_e(e){return new TypeError(`skill provider "${e}" list() must return an array or { candidates, complete } observation`)}function mkt(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:lkt,locator:e,...e.path!==void 0?{path:e.path}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}function gkt(e,t){if(typeof e.name!="string")throw new TypeError(`skill provider "${t}" returned a non-string skill name`);if(!Y9.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(RY(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 ykt(e){if(!Y9.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`);RY(e.invocation,`runtime skill "${e.name}"`)}function vkt(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(!Y9.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(RY(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 wkt(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 RY(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 bkt(e,t){return I_e(e.name,t.name)}function I_e(e,t){return e<t?-1:e>t?1:0}function xkt(e,t){return e.candidate.rank-t.candidate.rank||e.providerOrder-t.providerOrder||e.localOrder-t.localOrder}function Skt(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 __e(e,t){return t===void 0?e:(G6(t),new Promise((n,r)=>{let i=a(()=>{t.removeEventListener("abort",s)},"cleanup"),s=a(()=>{i(),r(Z9(t.reason))},"onAbort");t.addEventListener("abort",s,{once:!0}),e.then(o=>{i(),n(o)},o=>{i(),r(Z9(o))})}))}function G6(e){if(e?.aborted===!0)throw Z9(e.reason)}function Z9(e){try{if(e instanceof Error)return e}catch{}return new Error(K9(e))}function K9(e){try{return String(e)}catch{return"[unrenderable thrown value]"}}var Y9,k_e,ckt,G9,lkt,T_e,pkt,A_e,hkt,Hy=ae(()=>{Gn();Hi();fc();pn();Y9=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,k_e=128,ckt=2,G9="runtime",lkt=250,T_e=600;a(K6,"isSkillName");a(J9,"isModelInvocable");a(kx,"isUserInvocable");a(CY,"renderSkillContent");a(ukt,"renderResourceHint");a(dkt,"escapeAttr");a(Sx,"escapeText");pkt=class{static{a(this,"SkillLayer")}providers;runtime=new Map;constructor(e){this.providers=new kf(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}},A_e=class extends Et{static{a(this,"SkillRegistry")}static Config=F.object({collectCacheMaxEntries:F.number().default(k_e)});collectCacheMaxEntries;layers=new Ef(e=>new pkt(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??k_e,Skt("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===G9)throw new Error(`"${G9}" 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){ykt(e);let t=Fa(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??G9};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=>wkt(n.candidate)).sort(bkt),complete:t.cacheable}}async get(e,t={}){if(!K6(e))return;let n=await this.collect(t);G6(t.signal);let r=n.entries.get(e);if(r===void 0)return;let i=await __e(r.provider.get(r.candidate,t),t.signal);if(i!==void 0){if(vkt(i),i.name!==r.candidate.name){this.invalidateEntry(r);return}return i}}async collect(e){G6(e.signal);let t=1;for(;;){let n=this.revision,r=this.collectCacheKey(e.cwd,yE(e.scope),n),i=this.collectCache.get(r);if(i!==void 0)return{entries:i,cacheable:!0};let s=await this.collectFresh(e);if(G6(e.signal),n!==this.revision){if(t<ckt){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(xkt);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){G6(t.signal);let n=[],r=!0,i=0;for(let s of[...e.runtime.values()].sort((o,c)=>I_e(o.name,c.name)))n.push({candidate:mkt(s),provider:hkt,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 __e(s.list(t),t.signal)}catch(d){if(t.signal?.aborted===!0)throw Z9(t.signal.reason);r=!1,this.ctx.logger.warn(`skill provider "${s.name}" skipped: ${K9(d)}`)}if(l===void 0)continue;let u=fkt(l,s.name);u.complete||(r=!1);for(let d of u.candidates)gkt(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: ${K9(n)}`)})}catch(t){this.ctx.logger.warn(`skills/change listener threw: ${K9(t)}`)}}};a(fkt,"normalizeProviderObservation");a(E_e,"invalidProviderObservation");hkt={name:G9,list(){return Promise.resolve([])},get(e){return Promise.resolve(e.locator)}};a(mkt,"runtimeCandidate");a(gkt,"validateCandidate");a(ykt,"validateRuntimeSkill");a(vkt,"validateDefinition");a(wkt,"toSummary");a(RY,"validateInvocation");a(bkt,"compareSkillSummary");a(I_e,"compareCodePoints");a(xkt,"compareIndexedCandidates");a(Skt,"assertPositiveInteger");a(__e,"waitWithAbort");a(G6,"throwIfAborted");a(Z9,"toError");a(K9,"errorMessage")});var md,Tx=ae(()=>{md=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 xm,Z6e,gJ=ae(()=>{Gn();xm=class extends Error{static{a(this,"DirectoryPickerError")}code;path;constructor(e,t,n){super(n),this.code=e,this.path=t,this.name="DirectoryPickerError"}},Z6e=class extends Et{static{a(this,"DirectoryPicker")}constructor(e){super(e,"directoryPicker")}}});var _3e=be((Zzn,S5)=>{var E3e=E3e||function(e){return Buffer.from(e).toString("base64")};function gAt(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=[],w=0,b=7,S=new Array(64),k=new Array(64),E=new Array(64),_=new Array(256),T=new Array(2048),P,M=[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],j=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],$=[0,1,2,3,4,5,6,7,8,9,10,11],W=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],Y=[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],I=[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 O(oe){for(var Le=[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],Ee=0;Ee<64;Ee++){var ut=r((Le[Ee]*oe+50)/100);ut<1?ut=1:ut>255&&(ut=255),i[M[Ee]]=ut}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],je=0;je<64;je++){var wt=r((ze[je]*oe+50)/100);wt<1?wt=1:wt>255&&(wt=255),s[M[je]]=wt}for(var st=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379],Ke=0,yt=0;yt<8;yt++)for(var Oe=0;Oe<8;Oe++)o[Ke]=1/(i[M[Ke]]*st[yt]*st[Oe]*8),c[Ke]=1/(s[M[Ke]]*st[yt]*st[Oe]*8),Ke++}a(O,"initQuantTables");function N(oe,Le){for(var Ee=0,ut=0,ze=new Array,je=1;je<=16;je++){for(var wt=1;wt<=oe[je];wt++)ze[Le[ut]]=[],ze[Le[ut]][0]=Ee,ze[Le[ut]][1]=je,ut++,Ee++;Ee*=2}return ze}a(N,"computeHuffmanTbl");function D(){l=N(j,$),u=N(I,U),d=N(W,Y),p=N(C,R)}a(D,"initHuffmanTbl");function G(){for(var oe=1,Le=2,Ee=1;Ee<=15;Ee++){for(var ut=oe;ut<Le;ut++)h[32767+ut]=Ee,f[32767+ut]=[],f[32767+ut][1]=Ee,f[32767+ut][0]=ut;for(var ze=-(Le-1);ze<=-oe;ze++)h[32767+ze]=Ee,f[32767+ze]=[],f[32767+ze][1]=Ee,f[32767+ze][0]=Le-1+ze;oe<<=1,Le<<=1}}a(G,"initCategoryNumber");function X(){for(var oe=0;oe<256;oe++)T[oe]=19595*oe,T[oe+256>>0]=38470*oe,T[oe+512>>0]=7471*oe+32768,T[oe+768>>0]=-11059*oe,T[oe+1024>>0]=-21709*oe,T[oe+1280>>0]=32768*oe+8421375,T[oe+1536>>0]=-27439*oe,T[oe+1792>>0]=-5329*oe}a(X,"initRGBYUVTable");function Q(oe){for(var Le=oe[0],Ee=oe[1]-1;Ee>=0;)Le&1<<Ee&&(w|=1<<b),Ee--,b--,b<0&&(w==255?(z(255),z(0)):z(w),b=7,w=0)}a(Q,"writeBits");function z(oe){v.push(oe)}a(z,"writeByte");function ne(oe){z(oe>>8&255),z(oe&255)}a(ne,"writeWord");function ge(oe,Le){var Ee,ut,ze,je,wt,st,Ke,yt,Oe=0,_t,Gt=8,ht=64;for(_t=0;_t<Gt;++_t){Ee=oe[Oe],ut=oe[Oe+1],ze=oe[Oe+2],je=oe[Oe+3],wt=oe[Oe+4],st=oe[Oe+5],Ke=oe[Oe+6],yt=oe[Oe+7];var bn=Ee+yt,Vt=Ee-yt,Ut=ut+Ke,ce=ut-Ke,Pe=ze+st,Ge=ze-st,ct=je+wt,$t=je-wt,Xe=bn+ct,ln=bn-ct,rn=Ut+Pe,xn=Ut-Pe;oe[Oe]=Xe+rn,oe[Oe+4]=Xe-rn;var jt=(xn+ln)*.707106781;oe[Oe+2]=ln+jt,oe[Oe+6]=ln-jt,Xe=$t+Ge,rn=Ge+ce,xn=ce+Vt;var jr=(Xe-xn)*.382683433,Br=.5411961*Xe+jr,gs=1.306562965*xn+jr,Ni=rn*.707106781,hr=Vt+Ni,ys=Vt-Ni;oe[Oe+5]=ys+Br,oe[Oe+3]=ys-Br,oe[Oe+1]=hr+gs,oe[Oe+7]=hr-gs,Oe+=8}for(Oe=0,_t=0;_t<Gt;++_t){Ee=oe[Oe],ut=oe[Oe+8],ze=oe[Oe+16],je=oe[Oe+24],wt=oe[Oe+32],st=oe[Oe+40],Ke=oe[Oe+48],yt=oe[Oe+56];var Vs=Ee+yt,fo=Ee-yt,Co=ut+Ke,Bt=ut-Ke,Fn=ze+st,Ro=ze-st,Ca=je+wt,Ko=je-wt,Zo=Vs+Ca,ia=Vs-Ca,Ra=Co+Fn,sc=Co-Fn;oe[Oe]=Zo+Ra,oe[Oe+32]=Zo-Ra;var ru=(sc+ia)*.707106781;oe[Oe+16]=ia+ru,oe[Oe+48]=ia-ru,Zo=Ko+Ro,Ra=Ro+Bt,sc=Bt+fo;var pl=(Zo-sc)*.382683433,zd=.5411961*Zo+pl,Wd=1.306562965*sc+pl,Hd=Ra*.707106781,Vd=fo+Hd,$h=fo-Hd;oe[Oe+40]=$h+zd,oe[Oe+24]=$h-zd,oe[Oe+8]=Vd+Wd,oe[Oe+56]=Vd-Wd,Oe++}var sf;for(_t=0;_t<ht;++_t)sf=oe[_t]*Le[_t],g[_t]=sf>0?sf+.5|0:sf-.5|0;return g}a(ge,"fDCTQuant");function we(){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(we,"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 Le=0;Le<oe.length;Le++)z(oe[Le])}}a(le,"writeAPP1");function Se(oe,Le){ne(65472),ne(17),z(8),ne(Le),ne(oe),z(3),z(1),z(17),z(0),z(2),z(17),z(1),z(3),z(17),z(1)}a(Se,"writeSOF0");function _e(){ne(65499),ne(132),z(0);for(var oe=0;oe<64;oe++)z(i[oe]);z(1);for(var Le=0;Le<64;Le++)z(s[Le])}a(_e,"writeDQT");function ue(){ne(65476),ne(418),z(0);for(var oe=0;oe<16;oe++)z(j[oe+1]);for(var Le=0;Le<=11;Le++)z($[Le]);z(16);for(var Ee=0;Ee<16;Ee++)z(W[Ee+1]);for(var ut=0;ut<=161;ut++)z(Y[ut]);z(1);for(var ze=0;ze<16;ze++)z(I[ze+1]);for(var je=0;je<=11;je++)z(U[je]);z(17);for(var wt=0;wt<16;wt++)z(C[wt+1]);for(var st=0;st<=161;st++)z(R[st])}a(ue,"writeDHT");function de(oe){typeof oe>"u"||oe.constructor!==Array||oe.forEach(Le=>{if(typeof Le=="string"){ne(65534);var Ee=Le.length;ne(Ee+2);var ut;for(ut=0;ut<Ee;ut++)z(Le.charCodeAt(ut))}})}a(de,"writeCOM");function ot(){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(ot,"writeSOS");function Ve(oe,Le,Ee,ut,ze){for(var je=ze[0],wt=ze[240],st,Ke=16,yt=63,Oe=64,_t=ge(oe,Le),Gt=0;Gt<Oe;++Gt)y[M[Gt]]=_t[Gt];var ht=y[0]-Ee;Ee=y[0],ht==0?Q(ut[0]):(st=32767+ht,Q(ut[h[st]]),Q(f[st]));for(var bn=63;bn>0&&y[bn]==0;bn--);if(bn==0)return Q(je),Ee;for(var Vt=1,Ut;Vt<=bn;){for(var ce=Vt;y[Vt]==0&&Vt<=bn;++Vt);var Pe=Vt-ce;if(Pe>=Ke){Ut=Pe>>4;for(var Ge=1;Ge<=Ut;++Ge)Q(wt);Pe=Pe&15}st=32767+y[Vt],Q(ze[(Pe<<4)+h[st]]),Q(f[st]),Vt++}return bn!=yt&&Q(je),Ee}a(Ve,"processDU");function it(){for(var oe=String.fromCharCode,Le=0;Le<256;Le++)_[Le]=oe(Le)}a(it,"initCharLookupTable"),this.encode=function(oe,Le){var Ee=new Date().getTime();Le&&Ce(Le),v=new Array,w=0,b=7,ne(65496),we(),de(oe.comments),le(oe.exifBuffer),_e(),Se(oe.width,oe.height),ue(),ot();var ut=0,ze=0,je=0;w=0,b=7,this.encode.displayName="_encode_";for(var wt=oe.data,st=oe.width,Ke=oe.height,yt=st*4,Oe=st*3,_t,Gt=0,ht,bn,Vt,Ut,ce,Pe,Ge,ct;Gt<Ke;){for(_t=0;_t<yt;){for(Ut=yt*Gt+_t,ce=Ut,Pe=-1,Ge=0,ct=0;ct<64;ct++)Ge=ct>>3,Pe=(ct&7)*4,ce=Ut+Ge*yt+Pe,Gt+Ge>=Ke&&(ce-=yt*(Gt+1+Ge-Ke)),_t+Pe>=yt&&(ce-=_t+Pe-yt+4),ht=wt[ce++],bn=wt[ce++],Vt=wt[ce++],S[ct]=(T[ht]+T[bn+256>>0]+T[Vt+512>>0]>>16)-128,k[ct]=(T[ht+768>>0]+T[bn+1024>>0]+T[Vt+1280>>0]>>16)-128,E[ct]=(T[ht+1280>>0]+T[bn+1536>>0]+T[Vt+1792>>0]>>16)-128;ut=Ve(S,o,ut,l,d),ze=Ve(k,c,ze,u,p),je=Ve(E,c,je,u,p),_t+=32}Gt+=8}if(b>=0){var $t=[];$t[1]=b+1,$t[0]=(1<<b+1)-1,Q($t)}if(ne(65497),typeof S5>"u")return new Uint8Array(v);return Buffer.from(v);var Xe,ln};function Ce(oe){if(oe<=0&&(oe=1),oe>100&&(oe=100),P!=oe){var Le=0;oe<50?Le=Math.floor(5e3/oe):Le=Math.floor(200-oe*2),O(Le),P=oe}}a(Ce,"setQuality");function ke(){var oe=new Date().getTime();e||(e=50),it(),D(),G(),X(),Ce(e);var Le=new Date().getTime()-oe}a(ke,"init"),ke()}a(gAt,"JPEGEncoder");typeof S5<"u"?S5.exports=k3e:typeof window<"u"&&(window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=k3e);function k3e(e,t){typeof t>"u"&&(t=50);var n=new gAt(t),r=n.encode(e,t);return{data:r,width:e.width,height:e.height}}a(k3e,"encode")});var A3e=be((Jzn,WX)=>{var zX=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(b,S){for(var k=0,E=[],_,T,P=16;P>0&&!b[P-1];)P--;E.push({children:[],index:0});var M=E[0],j;for(_=0;_<P;_++){for(T=0;T<b[_];T++){for(M=E.pop(),M.children[M.index]=S[k];M.index>0;){if(E.length===0)throw new Error("Could not recreate Huffman Table");M=E.pop()}for(M.index++,E.push(M);E.length<=_;)E.push(j={children:[],index:0}),M.children[M.index]=j.children,M=j;k++}_+1<P&&(E.push(j={children:[],index:0}),M.children[M.index]=j.children,M=j)}return E[0].children}a(p,"buildHuffmanTable");function f(b,S,k,E,_,T,P,M,j,$){var W=k.precision,Y=k.samplesPerLine,I=k.scanLines,U=k.mcusPerLine,C=k.progressive,R=k.maxH,O=k.maxV,N=S,D=0,G=0;function X(){if(G>0)return G--,D>>G&1;if(D=b[S++],D==255){var Oe=b[S++];if(Oe)throw new Error("unexpected marker: "+(D<<8|Oe).toString(16))}return G=7,D>>>7}a(X,"readBit");function Q(Oe){for(var _t=Oe,Gt;(Gt=X())!==null;){if(_t=_t[Gt],typeof _t=="number")return _t;if(typeof _t!="object")throw new Error("invalid huffman sequence")}return null}a(Q,"decodeHuffman");function z(Oe){for(var _t=0;Oe>0;){var Gt=X();if(Gt===null)return;_t=_t<<1|Gt,Oe--}return _t}a(z,"receive");function ne(Oe){var _t=z(Oe);return _t>=1<<Oe-1?_t:_t+(-1<<Oe)+1}a(ne,"receiveAndExtend");function ge(Oe,_t){var Gt=Q(Oe.huffmanTableDC),ht=Gt===0?0:ne(Gt);_t[0]=Oe.pred+=ht;for(var bn=1;bn<64;){var Vt=Q(Oe.huffmanTableAC),Ut=Vt&15,ce=Vt>>4;if(Ut===0){if(ce<15)break;bn+=16;continue}bn+=ce;var Pe=t[bn];_t[Pe]=ne(Ut),bn++}}a(ge,"decodeBaseline");function we(Oe,_t){var Gt=Q(Oe.huffmanTableDC),ht=Gt===0?0:ne(Gt)<<j;_t[0]=Oe.pred+=ht}a(we,"decodeDCFirst");function le(Oe,_t){_t[0]|=X()<<j}a(le,"decodeDCSuccessive");var Se=0;function _e(Oe,_t){if(Se>0){Se--;return}for(var Gt=T,ht=P;Gt<=ht;){var bn=Q(Oe.huffmanTableAC),Vt=bn&15,Ut=bn>>4;if(Vt===0){if(Ut<15){Se=z(Ut)+(1<<Ut)-1;break}Gt+=16;continue}Gt+=Ut;var ce=t[Gt];_t[ce]=ne(Vt)*(1<<j),Gt++}}a(_e,"decodeACFirst");var ue=0,de;function ot(Oe,_t){for(var Gt=T,ht=P,bn=0;Gt<=ht;){var Vt=t[Gt],Ut=_t[Vt]<0?-1:1;switch(ue){case 0:var ce=Q(Oe.huffmanTableAC),Pe=ce&15,bn=ce>>4;if(Pe===0)bn<15?(Se=z(bn)+(1<<bn),ue=4):(bn=16,ue=1);else{if(Pe!==1)throw new Error("invalid ACn encoding");de=ne(Pe),ue=bn?2:3}continue;case 1:case 2:_t[Vt]?_t[Vt]+=(X()<<j)*Ut:(bn--,bn===0&&(ue=ue==2?3:0));break;case 3:_t[Vt]?_t[Vt]+=(X()<<j)*Ut:(_t[Vt]=de<<j,ue=0);break;case 4:_t[Vt]&&(_t[Vt]+=(X()<<j)*Ut);break}Gt++}ue===4&&(Se--,Se===0&&(ue=0))}a(ot,"decodeACSuccessive");function Ve(Oe,_t,Gt,ht,bn){var Vt=Gt/U|0,Ut=Gt%U,ce=Vt*Oe.v+ht,Pe=Ut*Oe.h+bn;Oe.blocks[ce]===void 0&&$.tolerantDecoding||_t(Oe,Oe.blocks[ce][Pe])}a(Ve,"decodeMcu");function it(Oe,_t,Gt){var ht=Gt/Oe.blocksPerLine|0,bn=Gt%Oe.blocksPerLine;Oe.blocks[ht]===void 0&&$.tolerantDecoding||_t(Oe,Oe.blocks[ht][bn])}a(it,"decodeBlock");var Ce=E.length,ke,oe,Le,Ee,ut,ze;C?T===0?ze=M===0?we:le:ze=M===0?_e:ot:ze=ge;var je=0,wt,st;Ce==1?st=E[0].blocksPerLine*E[0].blocksPerColumn:st=U*k.mcusPerColumn,_||(_=st);for(var Ke,yt;je<st;){for(oe=0;oe<Ce;oe++)E[oe].pred=0;if(Se=0,Ce==1)for(ke=E[0],ut=0;ut<_;ut++)it(ke,ze,je),je++;else for(ut=0;ut<_;ut++){for(oe=0;oe<Ce;oe++)for(ke=E[oe],Ke=ke.h,yt=ke.v,Le=0;Le<yt;Le++)for(Ee=0;Ee<Ke;Ee++)Ve(ke,ze,je,Le,Ee);if(je++,je===st)break}if(je===st)do{if(b[S]===255&&b[S+1]!==0)break;S+=1}while(S<b.length-2);if(G=0,wt=b[S]<<8|b[S+1],wt<65280)throw new Error("marker was not found");if(wt>=65488&&wt<=65495)S+=2;else break}return S-N}a(f,"decodeScan");function h(b,S){var k=[],E=S.blocksPerLine,_=S.blocksPerColumn,T=E<<3,P=new Int32Array(64),M=new Uint8Array(64);function j(N,D,G){var X=S.quantizationTable,Q,z,ne,ge,we,le,Se,_e,ue,de=G,ot;for(ot=0;ot<64;ot++)de[ot]=N[ot]*X[ot];for(ot=0;ot<8;++ot){var Ve=8*ot;if(de[1+Ve]==0&&de[2+Ve]==0&&de[3+Ve]==0&&de[4+Ve]==0&&de[5+Ve]==0&&de[6+Ve]==0&&de[7+Ve]==0){ue=l*de[0+Ve]+512>>10,de[0+Ve]=ue,de[1+Ve]=ue,de[2+Ve]=ue,de[3+Ve]=ue,de[4+Ve]=ue,de[5+Ve]=ue,de[6+Ve]=ue,de[7+Ve]=ue;continue}Q=l*de[0+Ve]+128>>8,z=l*de[4+Ve]+128>>8,ne=de[2+Ve],ge=de[6+Ve],we=u*(de[1+Ve]-de[7+Ve])+128>>8,_e=u*(de[1+Ve]+de[7+Ve])+128>>8,le=de[3+Ve]<<4,Se=de[5+Ve]<<4,ue=Q-z+1>>1,Q=Q+z+1>>1,z=ue,ue=ne*c+ge*o+128>>8,ne=ne*o-ge*c+128>>8,ge=ue,ue=we-Se+1>>1,we=we+Se+1>>1,Se=ue,ue=_e+le+1>>1,le=_e-le+1>>1,_e=ue,ue=Q-ge+1>>1,Q=Q+ge+1>>1,ge=ue,ue=z-ne+1>>1,z=z+ne+1>>1,ne=ue,ue=we*s+_e*i+2048>>12,we=we*i-_e*s+2048>>12,_e=ue,ue=le*r+Se*n+2048>>12,le=le*n-Se*r+2048>>12,Se=ue,de[0+Ve]=Q+_e,de[7+Ve]=Q-_e,de[1+Ve]=z+Se,de[6+Ve]=z-Se,de[2+Ve]=ne+le,de[5+Ve]=ne-le,de[3+Ve]=ge+we,de[4+Ve]=ge-we}for(ot=0;ot<8;++ot){var it=ot;if(de[8+it]==0&&de[16+it]==0&&de[24+it]==0&&de[32+it]==0&&de[40+it]==0&&de[48+it]==0&&de[56+it]==0){ue=l*G[ot+0]+8192>>14,de[0+it]=ue,de[8+it]=ue,de[16+it]=ue,de[24+it]=ue,de[32+it]=ue,de[40+it]=ue,de[48+it]=ue,de[56+it]=ue;continue}Q=l*de[0+it]+2048>>12,z=l*de[32+it]+2048>>12,ne=de[16+it],ge=de[48+it],we=u*(de[8+it]-de[56+it])+2048>>12,_e=u*(de[8+it]+de[56+it])+2048>>12,le=de[24+it],Se=de[40+it],ue=Q-z+1>>1,Q=Q+z+1>>1,z=ue,ue=ne*c+ge*o+2048>>12,ne=ne*o-ge*c+2048>>12,ge=ue,ue=we-Se+1>>1,we=we+Se+1>>1,Se=ue,ue=_e+le+1>>1,le=_e-le+1>>1,_e=ue,ue=Q-ge+1>>1,Q=Q+ge+1>>1,ge=ue,ue=z-ne+1>>1,z=z+ne+1>>1,ne=ue,ue=we*s+_e*i+2048>>12,we=we*i-_e*s+2048>>12,_e=ue,ue=le*r+Se*n+2048>>12,le=le*n-Se*r+2048>>12,Se=ue,de[0+it]=Q+_e,de[56+it]=Q-_e,de[8+it]=z+Se,de[48+it]=z-Se,de[16+it]=ne+le,de[40+it]=ne-le,de[24+it]=ge+we,de[32+it]=ge-we}for(ot=0;ot<64;++ot){var Ce=128+(de[ot]+8>>4);D[ot]=Ce<0?0:Ce>255?255:Ce}}a(j,"quantizeAndInverse"),w(T*_*8);for(var $,W,Y=0;Y<_;Y++){var I=Y<<3;for($=0;$<8;$++)k.push(new Uint8Array(T));for(var U=0;U<E;U++){j(S.blocks[Y][U],M,P);var C=0,R=U<<3;for(W=0;W<8;W++){var O=k[I+W];for($=0;$<8;$++)O[R+$]=M[C++]}}}return k}a(h,"buildComponentData");function g(b){return b<0?0:b>255?255:b}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 T(){var ce=S[E]<<8|S[E+1];return E+=2,ce}a(T,"readUint16");function P(){var ce=T(),Pe=S.subarray(E,E+ce-2);return E+=Pe.length,Pe}a(P,"readDataBlock");function M(ce){var Pe=1,Ge=1,ct,$t;for($t in ce.components)ce.components.hasOwnProperty($t)&&(ct=ce.components[$t],Pe<ct.h&&(Pe=ct.h),Ge<ct.v&&(Ge=ct.v));var Xe=Math.ceil(ce.samplesPerLine/8/Pe),ln=Math.ceil(ce.scanLines/8/Ge);for($t in ce.components)if(ce.components.hasOwnProperty($t)){ct=ce.components[$t];var rn=Math.ceil(Math.ceil(ce.samplesPerLine/8)*ct.h/Pe),xn=Math.ceil(Math.ceil(ce.scanLines/8)*ct.v/Ge),jt=Xe*ct.h,jr=ln*ct.v,Br=jr*jt,gs=[];w(Br*256);for(var Ni=0;Ni<jr;Ni++){for(var hr=[],ys=0;ys<jt;ys++)hr.push(new Int32Array(64));gs.push(hr)}ct.blocksPerLine=rn,ct.blocksPerColumn=xn,ct.blocks=gs}ce.maxH=Pe,ce.maxV=Ge,ce.mcusPerLine=Xe,ce.mcusPerColumn=ln}a(M,"prepareComponents");var j=null,$=null,W=null,Y,I,U=[],C=[],R=[],O=[],N=T(),D=-1;if(this.comments=[],N!=65496)throw new Error("SOI not found");for(N=T();N!=65497;){var G,X,Q;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=P();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&&(j={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&&($={version:z[6],flags0:z[7]<<8|z[8],flags1:z[9]<<8|z[10],transformCode:z[11]});break;case 65499:for(var ge=T(),we=ge+E-2;E<we;){var le=S[E++];w(256);var Se=new Int32Array(64);if(le>>4===0)for(X=0;X<64;X++){var _e=t[X];Se[_e]=S[E++]}else if(le>>4===1)for(X=0;X<64;X++){var _e=t[X];Se[_e]=T()}else throw new Error("DQT: invalid table spec");U[le&15]=Se}break;case 65472:case 65473:case 65474:T(),Y={},Y.extended=N===65473,Y.progressive=N===65474,Y.precision=S[E++],Y.scanLines=T(),Y.samplesPerLine=T(),Y.components={},Y.componentsOrder=[];var ue=Y.scanLines*Y.samplesPerLine;if(ue>k){var de=Math.ceil((ue-k)/1e6);throw new Error(`maxResolutionInMP limit exceeded by ${de}MP`)}var ot=S[E++],Ve,it=0,Ce=0;for(G=0;G<ot;G++){Ve=S[E];var ke=S[E+1]>>4,oe=S[E+1]&15,Le=S[E+2];if(ke<=0||oe<=0)throw new Error("Invalid sampling factor, expected values above 0");Y.componentsOrder.push(Ve),Y.components[Ve]={h:ke,v:oe,quantizationIdx:Le},E+=3}M(Y),C.push(Y);break;case 65476:var Ee=T();for(G=2;G<Ee;){var ut=S[E++],ze=new Uint8Array(16),je=0;for(X=0;X<16;X++,E++)je+=ze[X]=S[E];w(16+je);var wt=new Uint8Array(je);for(X=0;X<je;X++,E++)wt[X]=S[E];G+=17+je,(ut>>4===0?O:R)[ut&15]=p(ze,wt)}break;case 65501:T(),I=T();break;case 65500:T(),T();break;case 65498:var st=T(),Ke=S[E++],yt=[],Oe;for(G=0;G<Ke;G++){Oe=Y.components[S[E++]];var _t=S[E++];Oe.huffmanTableDC=O[_t>>4],Oe.huffmanTableAC=R[_t&15],yt.push(Oe)}var Gt=S[E++],ht=S[E++],bn=S[E++],Vt=f(S,E,Y,yt,I,Gt,ht,bn>>4,bn&15,this.opts);E+=Vt;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(D!==-1)throw new Error(`first unknown JPEG marker at offset ${D.toString(16)}, second unknown JPEG marker ${N.toString(16)} at offset ${(E-1).toString(16)}`);D=E-1;let ce=T();if(S[E+ce-2]===255){E+=ce-2;break}}throw new Error("unknown JPEG marker "+N.toString(16))}N=T()}if(C.length!=1)throw new Error("only single frame JPEGs supported");for(var G=0;G<C.length;G++){var Ut=C[G].components;for(var X in Ut)Ut[X].quantizationTable=U[Ut[X].quantizationIdx],delete Ut[X].quantizationIdx}this.width=Y.samplesPerLine,this.height=Y.scanLines,this.jfif=j,this.adobe=$,this.components=[];for(var G=0;G<Y.componentsOrder.length;G++){var Oe=Y.components[Y.componentsOrder[G]];this.components.push({lines:h(Y,Oe),scaleX:Oe.h/Y.maxH,scaleY:Oe.v/Y.maxV})}},"parse"),getData:a(function(S,k){var E=this.width/S,_=this.height/k,T,P,M,j,$,W,Y,I,U,C,R=0,O,N,D,G,X,Q,z,ne,ge,we,le,Se=S*k*this.components.length;w(Se);var _e=new Uint8Array(Se);switch(this.components.length){case 1:for(T=this.components[0],C=0;C<k;C++)for($=T.lines[0|C*T.scaleY*_],U=0;U<S;U++)O=$[0|U*T.scaleX*E],_e[R++]=O;break;case 2:for(T=this.components[0],P=this.components[1],C=0;C<k;C++)for($=T.lines[0|C*T.scaleY*_],W=P.lines[0|C*P.scaleY*_],U=0;U<S;U++)O=$[0|U*T.scaleX*E],_e[R++]=O,O=W[0|U*P.scaleX*E],_e[R++]=O;break;case 3:for(le=!0,this.adobe&&this.adobe.transformCode?le=!0:typeof this.opts.colorTransform<"u"&&(le=!!this.opts.colorTransform),T=this.components[0],P=this.components[1],M=this.components[2],C=0;C<k;C++)for($=T.lines[0|C*T.scaleY*_],W=P.lines[0|C*P.scaleY*_],Y=M.lines[0|C*M.scaleY*_],U=0;U<S;U++)le?(O=$[0|U*T.scaleX*E],N=W[0|U*P.scaleX*E],D=Y[0|U*M.scaleX*E],ne=g(O+1.402*(D-128)),ge=g(O-.3441363*(N-128)-.71413636*(D-128)),we=g(O+1.772*(N-128))):(ne=$[0|U*T.scaleX*E],ge=W[0|U*P.scaleX*E],we=Y[0|U*M.scaleX*E]),_e[R++]=ne,_e[R++]=ge,_e[R++]=we;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),T=this.components[0],P=this.components[1],M=this.components[2],j=this.components[3],C=0;C<k;C++)for($=T.lines[0|C*T.scaleY*_],W=P.lines[0|C*P.scaleY*_],Y=M.lines[0|C*M.scaleY*_],I=j.lines[0|C*j.scaleY*_],U=0;U<S;U++)le?(O=$[0|U*T.scaleX*E],N=W[0|U*P.scaleX*E],D=Y[0|U*M.scaleX*E],G=I[0|U*j.scaleX*E],X=255-g(O+1.402*(D-128)),Q=255-g(O-.3441363*(N-128)-.71413636*(D-128)),z=255-g(O+1.772*(N-128))):(X=$[0|U*T.scaleX*E],Q=W[0|U*P.scaleX*E],z=Y[0|U*M.scaleX*E],G=I[0|U*j.scaleX*E]),_e[R++]=255-X,_e[R++]=255-Q,_e[R++]=255-z,_e[R++]=255-G;break;default:throw new Error("Unsupported color mode")}return _e},"getData"),copyToImageData:a(function(S,k){var E=S.width,_=S.height,T=S.data,P=this.getData(E,_),M=0,j=0,$,W,Y,I,U,C,R,O,N;switch(this.components.length){case 1:for(W=0;W<_;W++)for($=0;$<E;$++)Y=P[M++],T[j++]=Y,T[j++]=Y,T[j++]=Y,k&&(T[j++]=255);break;case 3:for(W=0;W<_;W++)for($=0;$<E;$++)R=P[M++],O=P[M++],N=P[M++],T[j++]=R,T[j++]=O,T[j++]=N,k&&(T[j++]=255);break;case 4:for(W=0;W<_;W++)for($=0;$<E;$++)U=P[M++],C=P[M++],Y=P[M++],I=P[M++],R=255-g(U*(1-I/255)+I),O=255-g(C*(1-I/255)+I),N=255-g(Y*(1-I/255)+I),T[j++]=R,T[j++]=O,T[j++]=N,k&&(T[j++]=255);break;default:throw new Error("Unsupported color mode")}},"copyToImageData")};var y=0,v=0;function w(b=0){var S=y+b;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(w,"requestMemoryAllocation"),d.resetMaxMemoryUsage=function(b){y=0,v=b},d.getBytesAllocated=function(){return y},d.requestMemoryAllocation=w,d}),"jpegImage")();typeof WX<"u"?WX.exports=T3e:typeof window<"u"&&(window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=T3e);function T3e(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 zX;s.opts=r,zX.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),s.parse(i);var o=r.formatAsRGBA?4:3,c=s.width*s.height*o;try{zX.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(T3e,"decode")});var C3e=be((Qzn,I3e)=>{var yAt=_3e(),vAt=A3e();I3e.exports={encode:yAt,decode:vAt}});function u7e(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 gn({...e,content:s})}var d7e=ae(()=>{Hi();a(u7e,"offloadMessageImages")});function p7e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function f7e(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0&&!Object.is(e,-0)}var B5,BQ=ae(()=>{d7e();a(p7e,"isRecord");a(f7e,"isIndex");B5={type:"image/offload",project(e,t){let n=e.data;if(!p7e(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(!p7e(s)||Object.keys(s).length!==2||!f7e(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(!f7e(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,u7e(u,s.imageIndexes))}return r}}});var rO,$Ie=ae(()=>{BQ();rO=[B5]});async function FIe(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,...eI(o)]}}function Eee(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 Mr(`session source headers conflict for session "${e.id}"`,"SESSION_QUERY_SOURCE_CONFLICT")}function iO(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 _ee(e){return{header:e.header,events:e.snapshotEvents()}}function sO(e,t){return e.map(n=>t.get(n))}async function Tee(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 Mr(`session persistence listing failed: ${Cee(n)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:n})}}async function NIe(e,t,n){try{return await FIe(e,t,n)}catch(r){throw n?.aborted&&n.throwIfAborted(),r instanceof Error&&r.name==="SessionPersistenceCorruptionError"?new Mr(`stored session "${t}" is corrupt: ${Cee(r)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:r}):new Mr(`failed to read stored session "${t}": ${Cee(r)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:r})}}function PIe(e){return{header:structuredClone(e.header),inheritedEventCount:e.inheritedEventCount,events:e.snapshotEvents().map(t=>structuredClone(t))}}function _9t(e,t){return t.header.createdAt-e.header.createdAt||e.header.id.localeCompare(t.header.id)}function oO(e){return new Mr(`session "${e}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND")}function Cee(e){return e instanceof Error?e.message:"unknown error"}function i4(e){if(e?.aborted===!0)throw new Mr("session observation was aborted","SESSION_QUERY_ABORTED",{cause:e.reason})}function MIe(e,t){return DIe(t,"SessionPersistenceNotFoundError")?Ree(e,t):DIe(t,"SessionPersistenceCorruptionError")?new Mr(`stored session "${e}" is corrupt: ${t.message}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:t}):new Mr(`failed to observe session "${e}": ${aO(t)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:t})}function Ree(e,t){return new Mr(`session "${e}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND",t===void 0?void 0:{cause:t})}function aO(e){return e instanceof Error?e.message:"unknown error"}function DIe(e,t){return e instanceof Error&&e.name===t}function A9t(e){switch(e.type){case"user/message":return Aee(e.data.content);case"assistant/message":return Aee(e.data.message.content);case"tool/call":return s4([e.data.name,e.data.arguments]);case"tool/result":return s4([Aee(e.data.message.content),e.data.error?.name??"",e.data.error?.code??""]);case"todo/write":return s4(e.data.todos.flatMap(t=>[t.status,t.content]));case"turn/end":return I9t(e.data.reason);case"turn/start":case"step/start":case"step/end":case"assistant/attempt":case"request/header":return"";default:return""}}function I9t(e){switch(e.kind){case"error":return s4(["error",e.error.message]);case"aborted":return"aborted";case"max-tokens":case"interrupted":return e.kind;case"completed":return"";default:return""}}function Aee(e){return s4(e.flatMap(C9t))}function C9t(e){switch(e.type){case"text":return[e.text];case"reasoning":return[];case"tool-call":return[e.name,e.arguments];default:return[]}}function s4(e){return e.map(t=>t.trim()).filter(Boolean).join(`
157
157
  `)}function $ee(e,t){let n=R9t(t),r=[];for(let i of t){let s=A9t(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 R9t(e){let t;try{t=cF(e,rO)}catch(r){throw new Mr(`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 Nee(e,t=[]){let n=t.map($9t);return e.filter(r=>n.every(i=>i(r)))}function dO(e,t=[]){let n=t.map(N9t);return e.filter(r=>n.every(i=>i(r)))}function Pee(e){return qIe(e),e.map(t=>{switch(t.kind){case"id":return{kind:t.kind,values:lO(t.kind,t.values)};case"cwd":return{kind:t.kind,values:LIe(t.kind,t.values)};case"created-at":return UIe(t.kind,t);case"parent":return{kind:t.kind,values:LIe(t.kind,t.values)};case"availability":{let n=lO(t.kind,t.values);return hO(t.kind,n,["live","persisted"]),{kind:t.kind,values:n}}default:return fO(t)}})}function pO(e){return qIe(e),e.map(t=>{switch(t.kind){case"seq":case"time":return UIe(t.kind,t);case"type":return{kind:t.kind,values:lO(t.kind,t.values)};case"surface":{let n=lO(t.kind,t.values);return hO(t.kind,n,["current","shadowed","log-only"]),{kind:t.kind,values:n}}case"text":if(typeof t.text!="string")throw u2("text filter text must be a string");return{kind:t.kind,text:t.text};default:return fO(t)}})}function O9t(e){let t=e.trim();if(t.length===0)throw new Mr("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 $9t(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=uO(e.kind,e);return n=>Oee(n.header.createdAt,t)}case"parent":return t=>e.values.includes(t.header.parentSession??null);case"availability":return hO(e.kind,e.values,["live","persisted"]),t=>e.values.some(n=>n==="live"?t.live:t.persisted);default:return fO(e)}}function N9t(e){switch(e.kind){case"seq":{let t=uO(e.kind,e);return n=>Oee(n.seq,t)}case"time":{let t=uO(e.kind,e);return n=>Oee(n.time,t)}case"type":return t=>e.values.includes(t.type);case"surface":return hO(e.kind,e.values,["current","shadowed","log-only"]),t=>e.values.includes(t.surface);case"text":{let t=O9t(e.text);return n=>t.test(n.text)}default:return fO(e)}}function lO(e,t){if(!BIe(t)||t.some(n=>typeof n!="string"))throw u2(`${e} filter values must be an array of strings`);return[...t]}function qIe(e){if(!Array.isArray(e))throw u2("filters must be an array")}function LIe(e,t){if(!BIe(t)||t.some(n=>n!==null&&typeof n!="string"))throw u2(`${e} filter values must be an array of strings or null`);return[...t]}function UIe(e,t){let n={kind:e,...t.from===void 0?{}:{from:t.from},...t.to===void 0?{}:{to:t.to}};return uO(e,n),n}function fO(e){let t=e.kind;throw u2(`unknown filter kind ${typeof t=="string"?`"${t}"`:"(missing)"}`)}function hO(e,t,n){for(let r of t)if(!n.includes(r))throw new Mr(`session ${e} filter contains unknown value "${r}"`,"SESSION_QUERY_INVALID_FILTER")}function uO(e,t){if(t.from!==void 0&&!Number.isFinite(t.from))throw Iee(e,"from must be finite");if(t.to!==void 0&&!Number.isFinite(t.to))throw Iee(e,"to must be finite");if(t.from!==void 0&&t.to!==void 0&&t.from>t.to)throw Iee(e,"from must be less than or equal to to");return t}function Oee(e,t){return(t.from===void 0||e>=t.from)&&(t.to===void 0||e<=t.to)}function Iee(e,t){return u2(`${e} filter ${t}`)}function u2(e){return new Mr(`session ${e}`,"SESSION_QUERY_INVALID_FILTER")}function BIe(e){return Array.isArray(e)}function P9t(e,t){return Mee(e,t).records}function M9t(e,t){return Mee(e,t).currentSeqs.map(n=>{let r=t[n];if(r===void 0||r.seq!==n||!Mg(r))throw new Mr(`invalid session surface: current node ${n} is not a surface event`,"SESSION_QUERY_INVALID_SURFACE");return bE(r)})}function D9t(e,t,n){let r=t[n];if(r===void 0||r.seq!==n)throw new Mr(`session "${e}" has no event at seq ${n}`,"SESSION_QUERY_EVENT_NOT_FOUND");let i=Mee(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||jIe(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:[...jIe(r)],derivedEventSeqs:c}}function L9t(e,t){let n=new Map(e.map(p=>[p.header.id,p])),r=n.get(t);if(r===void 0)throw new Mr(`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 Mr(`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=j9t(l,t),d={target:cO(r),ancestors:i.map(cO),descendants:u};return o!==void 0?{...d,complete:!1,unresolvedParentId:o}:{...d,complete:!0,root:cO(i.at(-1)??r)}}function Mee(e,t){let n;try{n=cF(t,rO)}catch(o){throw new Mr(`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 jIe(e){return e.sourceEventSeqs??[]}function j9t(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:cO(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 cO(e){return{...e,header:structuredClone(e.header)}}var Mr,E9t,T9t,zIe,Dee=ae(()=>{$Ie();Gn();Ls();t1();mr();Mr=class extends Wr{static{a(this,"SessionQueryError")}constructor(e,t,n){super(e,t,n)}};a(FIe,"readColdSessionLog");a(Eee,"assertSessionHeadersCompatible");E9t=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 Tee(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&&Eee(i.header,s.header),r.set(i.id,{header:structuredClone(i.header),live:!0,persisted:s!==void 0})}return[...r.values()].sort(_9t)}async load(e,t){t?.throwIfAborted();let n=this._ctx.sessions.get(e);if(n!==void 0){let l=PIe(n);return t?.throwIfAborted(),l}let r=this._persistence;if(r===void 0)throw oO(e);let i=(await Tee(r,t)).find(l=>l.id===e);if(t?.throwIfAborted(),i===void 0)throw oO(e);let s=await NIe(r,e,t);t?.throwIfAborted();let o=this._ctx.sessions.get(e);if(o!==void 0){let l=PIe(o);return t?.throwIfAborted(),l}Eee(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,iO(g,_ee(y),t,n))}if(s.length===0)return sO(r,i);let o=this._persistence;if(o===void 0){for(let g of s)i.set(g,{sessionId:g,status:"rejected",reason:oO(g)});return sO(r,i)}let c;try{c=await Tee(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 sO(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:oO(g)}:iO(g,_ee(v),t,n));return}try{n?.throwIfAborted();let v=await NIe(o,g,n);n?.throwIfAborted();let w=this._ctx.sessions.get(g);if(w!==void 0){i.set(g,iO(g,_ee(w),t,n));return}Eee(v.header,y),i.set(g,iO(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(),sO(r,i)}};a(iO,"projectSource");a(_ee,"sourceLive");a(sO,"orderedResults");a(Tee,"listPersisted");a(NIe,"inspectPersisted");a(PIe,"snapshotLive");a(_9t,"compareSessions");a(oO,"notFound$1");a(Cee,"errorMessage$1");T9t=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(;;){i4(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 Ree(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);i4(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 Mr(`stored session "${e}" is corrupt: ${aO(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 Mr(`failed to project session "${e}": ${aO(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 i4(n),MIe(t,i)}if(i4(n),r===void 0)throw Ree(t);if(r.header.id!==t)throw new Mr(`session persistence returned "${r.header.id}" for "${t}"`,"SESSION_QUERY_SOURCE_CONFLICT");return r}async loadSource(e,t,n){try{return await FIe(e,t,n)}catch(r){throw i4(n),MIe(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 Mr(`failed to project session "${e.id}": ${aO(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(In(0),n),r},cursor:n===0?-1:un(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,In(0)):n.hydratePrepared(e.session,e.events)}};a(i4,"throwIfObservationAborted");a(MIe,"mapPersistenceFailure");a(Ree,"notFound");a(aO,"errorMessage");a(DIe,"hasErrorName");a(A9t,"extractSessionEventText");a(I9t,"turnEndText");a(Aee,"contentText");a(C9t,"blockText");a(s4,"joinText");a($ee,"buildSessionEventSearchDocuments");a(R9t,"classifySurface");a(Nee,"filterSessionResults");a(dO,"filterSessionEventDocuments");a(Pee,"materializeSessionResultFilters");a(pO,"materializeSessionEventResultFilters");a(O9t,"compileSessionTextFilter");a($9t,"sessionPredicate");a(N9t,"eventPredicate");a(lO,"copyStrings");a(qIe,"assertArray");a(LIe,"copyNullableStrings");a(UIe,"copyRange");a(fO,"unknownFilter");a(hO,"assertAllowedValues");a(uO,"validateRange");a(Oee,"matchesRange");a(Iee,"invalidRange");a(u2,"invalidFilter");a(BIe,"isRuntimeArray");a(P9t,"eventRecords");a(M9t,"currentSurfaceEvents");a(D9t,"traceEvent");a(L9t,"traceSession");a(Mee,"analyzeEventLog");a(jIe,"eventSources");a(j9t,"buildDescendants");a(cO,"cloneRecord");zIe=class extends Et{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 Mr("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 Mr("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 Mr("session-query: preparedSessionCacheSize must be a positive safe integer","SESSION_QUERY_INVALID_CONFIG");this._corpus=new E9t(e,n),this._observations=new T9t(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 X0.create(e,t.events,t.header,t.inheritedEventCount,rO),{session:structuredClone(t.header),inheritedEventCount:t.inheritedEventCount,events:t.events.map(bE)}}async filterSessions(e,t){let n=Pee(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=e1(n.events);return{session:structuredClone(n.header),...r===void 0?{}:{title:r}}},t)}async listEvents(e){return P9t(e,(await this._corpus.load(e)).events)}async filterEvents(e,t){let n=pO(t);return this._filterEvents(e,n)}async _filterSessions(e,t){return Nee(await this._corpus.listSessions(t),e)}async _filterEvents(e,t){return dO($ee(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:M9t(e,t.events)}}async traceSession(e,t){let n=await this._corpus.listSessions(t);return t?.throwIfAborted(),L9t(n,e)}async traceEvent(e,t){let n=await this._corpus.load(e.sessionId,t);return t?.throwIfAborted(),{session:n.header,...D9t(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 Mr(`session "${e}" has no event at seq ${t}`,"SESSION_QUERY_EVENT_NOT_FOUND");let c=un(Math.max(0,t-n)),l=un(Math.min(s.events.length-1,t+r)),u=bE(o),d=s.events.slice(c,l+1).map(p=>p===o?u:bE(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 Mr(`${e} must be an integer between 0 and ${this._readWindowMax}`,"SESSION_QUERY_INVALID_WINDOW");return t}}});var d2=be((eKn,t8e)=>{"use strict";t8e.exports=lv;lv.CAPTURING_PHASE=1;lv.AT_TARGET=2;lv.BUBBLING_PHASE=3;function lv(e,t){if(this.type="",this.target=null,this.currentTarget=null,this.eventPhase=lv.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(lv,"Event");lv.prototype=Object.create(Object.prototype,{constructor:{value:lv},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 zee=be((nKn,r8e)=>{"use strict";var n8e=d2();r8e.exports=Bee;function Bee(){n8e.call(this),this.view=null,this.detail=0}a(Bee,"UIEvent");Bee.prototype=Object.create(n8e.prototype,{constructor:{value:Bee},initUIEvent:{value:a(function(e,t,n,r,i){this.initEvent(e,t,n),this.view=r,this.detail=i},"value")}})});var Hee=be((iKn,s8e)=>{"use strict";var i8e=zee();s8e.exports=Wee;function Wee(){i8e.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(Wee,"MouseEvent");Wee.prototype=Object.create(i8e.prototype,{constructor:{value:Wee},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 bO=be((oKn,a8e)=>{"use strict";a8e.exports=wO;var tRt=1,nRt=3,rRt=4,iRt=5,sRt=7,oRt=8,aRt=9,cRt=11,lRt=12,uRt=13,dRt=14,pRt=15,fRt=17,hRt=18,mRt=19,gRt=20,yRt=21,vRt=22,wRt=23,bRt=24,xRt=25,SRt=[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"],kRt=[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."],o8e={INDEX_SIZE_ERR:tRt,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:nRt,WRONG_DOCUMENT_ERR:rRt,INVALID_CHARACTER_ERR:iRt,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:sRt,NOT_FOUND_ERR:oRt,NOT_SUPPORTED_ERR:aRt,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:cRt,SYNTAX_ERR:lRt,INVALID_MODIFICATION_ERR:uRt,NAMESPACE_ERR:dRt,INVALID_ACCESS_ERR:pRt,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:fRt,SECURITY_ERR:hRt,NETWORK_ERR:mRt,ABORT_ERR:gRt,URL_MISMATCH_ERR:yRt,QUOTA_EXCEEDED_ERR:vRt,TIMEOUT_ERR:wRt,INVALID_NODE_TYPE_ERR:bRt,DATA_CLONE_ERR:xRt};function wO(e){Error.call(this),Error.captureStackTrace(this,this.constructor),this.code=e,this.message=kRt[e],this.name=SRt[e]}a(wO,"DOMException");wO.prototype.__proto__=Error.prototype;for(vO in o8e)Vee={value:o8e[vO]},Object.defineProperty(wO,vO,Vee),Object.defineProperty(wO.prototype,vO,Vee);var Vee,vO});var xO=be(c8e=>{c8e.isApiWritable=!globalThis.__domino_frozen__});var xo=be(Fi=>{"use strict";var bo=bO(),jo=bo,ERt=xO().isApiWritable;Fi.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"};Fi.IndexSizeError=function(){throw new bo(jo.INDEX_SIZE_ERR)};Fi.HierarchyRequestError=function(){throw new bo(jo.HIERARCHY_REQUEST_ERR)};Fi.WrongDocumentError=function(){throw new bo(jo.WRONG_DOCUMENT_ERR)};Fi.InvalidCharacterError=function(){throw new bo(jo.INVALID_CHARACTER_ERR)};Fi.NoModificationAllowedError=function(){throw new bo(jo.NO_MODIFICATION_ALLOWED_ERR)};Fi.NotFoundError=function(){throw new bo(jo.NOT_FOUND_ERR)};Fi.NotSupportedError=function(){throw new bo(jo.NOT_SUPPORTED_ERR)};Fi.InvalidStateError=function(){throw new bo(jo.INVALID_STATE_ERR)};Fi.SyntaxError=function(){throw new bo(jo.SYNTAX_ERR)};Fi.InvalidModificationError=function(){throw new bo(jo.INVALID_MODIFICATION_ERR)};Fi.NamespaceError=function(){throw new bo(jo.NAMESPACE_ERR)};Fi.InvalidAccessError=function(){throw new bo(jo.INVALID_ACCESS_ERR)};Fi.TypeMismatchError=function(){throw new bo(jo.TYPE_MISMATCH_ERR)};Fi.SecurityError=function(){throw new bo(jo.SECURITY_ERR)};Fi.NetworkError=function(){throw new bo(jo.NETWORK_ERR)};Fi.AbortError=function(){throw new bo(jo.ABORT_ERR)};Fi.UrlMismatchError=function(){throw new bo(jo.URL_MISMATCH_ERR)};Fi.QuotaExceededError=function(){throw new bo(jo.QUOTA_EXCEEDED_ERR)};Fi.TimeoutError=function(){throw new bo(jo.TIMEOUT_ERR)};Fi.InvalidNodeTypeError=function(){throw new bo(jo.INVALID_NODE_TYPE_ERR)};Fi.DataCloneError=function(){throw new bo(jo.DATA_CLONE_ERR)};Fi.nyi=function(){throw new Error("NotYetImplemented")};Fi.shouldOverride=function(){throw new Error("Abstract function; should be overriding in subclass.")};Fi.assert=function(e,t){if(!e)throw new Error("Assertion failed: "+(t||"")+`
158
158
  `+new Error().stack)};Fi.expose=function(e,t){for(var n in e)Object.defineProperty(t.prototype,n,{value:e[n],writable:ERt})};Fi.merge=function(e,t){for(var n in t)e[n]=t[n]};Fi.documentOrder=function(e,t){return 3-(e.compareDocumentPosition(t)&6)};Fi.toASCIILowerCase=function(e){return e.replace(/[A-Z]+/g,function(t){return t.toLowerCase()})};Fi.toASCIIUpperCase=function(e){return e.replace(/[a-z]+/g,function(t){return t.toUpperCase()})}});var Gee=be((uKn,u8e)=>{"use strict";var uv=d2(),_Rt=Hee(),TRt=xo();u8e.exports=l8e;function l8e(){}a(l8e,"EventTarget");l8e.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!==uv.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 w=0,b=v.length;w<b;w++){if(d._immediatePropagationStopped)return;var S=v[w];if(!(f===uv.CAPTURING_PHASE&&!S.capture||f===uv.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)&&TRt.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=uv.CAPTURING_PHASE;for(var o=i.length-1;o>=0&&(r(i[o],t),!t._propagationStopped);o--);if(t._propagationStopped||(t.eventPhase=uv.AT_TARGET,r(this,t)),t.bubbles&&!t._propagationStopped){t.eventPhase=uv.BUBBLING_PHASE;for(var c=0,l=i.length;c<l&&(r(i[c],t),!t._propagationStopped);c++);}if(t._dispatching=!1,t.eventPhase=uv.AT_TARGET,t.currentTarget=null,n&&!t.defaultPrevented&&t instanceof _Rt)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 Kee=be((pKn,d8e)=>{"use strict";var Rm=xo(),bd=d8e.exports={valid:a(function(e){return Rm.assert(e,"list falsy"),Rm.assert(e._previousSibling,"previous falsy"),Rm.assert(e._nextSibling,"next falsy"),!0},"valid"),insertBefore:a(function(e,t){Rm.assert(bd.valid(e)&&bd.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,Rm.assert(bd.valid(e)&&bd.valid(t))},"insertBefore"),replace:a(function(e,t){Rm.assert(bd.valid(e)&&(t===null||bd.valid(t))),t!==null&&bd.insertBefore(t,e),bd.remove(e),Rm.assert(bd.valid(e)&&(t===null||bd.valid(t)))},"replace"),remove:a(function(e){Rm.assert(bd.valid(e));var t=e._previousSibling;if(t!==e){var n=e._nextSibling;t._nextSibling=n,n._previousSibling=t,e._previousSibling=e._nextSibling=e,Rm.assert(bd.valid(e))}},"remove")}});var Zee=be((hKn,w8e)=>{"use strict";w8e.exports={serializeOne:NRt,\u0275escapeMatchingClosingTag:g8e,\u0275escapeClosingCommentTag:y8e,\u0275escapeProcessingInstructionContent:v8e};var m8e=xo(),dv=m8e.NAMESPACE,p8e={STYLE:!0,SCRIPT:!0,XMP:!0,IFRAME:!0,NOEMBED:!0,NOFRAMES:!0,PLAINTEXT:!0},ARt={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},IRt={},f8e=/[&<>\u00A0]/g,h8e=/[&"<>\u00A0]/g;function CRt(e){return f8e.test(e)?e.replace(f8e,t=>{switch(t){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case"\xA0":return"&nbsp;"}}):e}a(CRt,"escape");function RRt(e){return h8e.test(e)?e.replace(h8e,t=>{switch(t){case"<":return"&lt;";case">":return"&gt;";case"&":return"&amp;";case'"':return"&quot;";case"\xA0":return"&nbsp;"}}):e}a(RRt,"escapeAttr");function ORt(e){var t=e.namespaceURI;return t?t===dv.XML?"xml:"+e.localName:t===dv.XLINK?"xlink:"+e.localName:t===dv.XMLNS?e.localName==="xmlns"?"xmlns":"xmlns:"+e.localName:e.name:e.localName}a(ORt,"attrname");function g8e(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(g8e,"escapeMatchingClosingTag");var $Rt=/--!?>/;function y8e(e){return $Rt.test(e)?e.replace(/(--\!?)>/g,"$1&gt;"):e}a(y8e,"escapeClosingCommentTag");function v8e(e){return e.includes(">")?e.replaceAll(">","&gt;"):e}a(v8e,"escapeProcessingInstructionContent");function NRt(e,t){var n="";switch(e.nodeType){case 1:var r=e.namespaceURI,i=r===dv.HTML,s=i||r===dv.SVG||r===dv.MATHML?e.localName:e.tagName;n+="<"+s;for(var o=0,c=e._numattrs;o<c;o++){var l=e._attr(o);n+=" "+ORt(l),l.value!==void 0&&(n+='="'+RRt(l.value)+'"')}if(n+=">",!(i&&ARt[s])){var u=e.serialize();p8e[s.toUpperCase()]&&(u=g8e(u,s)),i&&IRt[s]&&u.charAt(0)===`
@@ -5928,7 +5928,7 @@ The web search request used endpoint ${JSON.stringify(e)}. Search endpoint confi
5928
5928
  .error { padding: .75rem; border-radius: .5rem; background: #461d2b; color: #ffd6df; }
5929
5929
  .hint { margin: 1.5rem 0 0; font-size: .875rem; }
5930
5930
  code { padding: .1rem .3rem; border-radius: .3rem; background: #0c1222; color: #edf2ff; }
5931
- `}a(vje,"pageStyles");U6();var foe="enabled",hoe=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")}),v3=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")}),moe=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===foe?"available":"needs-binding","probe")}),Ttn=Object.freeze([moe,v3,hoe]);function goe(e,t=Ttn){return t.filter(n=>n.probe(e)==="available")}a(goe,"availableEdgeRuntimeProviders");function yoe(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(yoe,"resolveEdgeRuntimeSelection");function XN(e){let t=goe(e),{bash:n,container:r}=yoe(t);return t.find(i=>i.id===(r??n)).shell}a(XN,"resolveEdgeRuntimeShell");function Atn(){return"dsh-edge@0.24.0-alpha.1/direct"}a(Atn,"resolveEdgeDeploymentId");function Pv(e){return{baseURL:wX(e.DEEPSEEK_BASE_URL),maxTokens:SX(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Xy(e.DEEPSEEK_MODEL),reasoningEffort:bX(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:I4(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:xX(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:s0(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(Pv,"resolveEdgeDeploymentConfig");function Itn(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(Itn,"edgeDeploymentApiKeyConfigured");function Ctn(e){let t=wX(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(Ctn,"projectedEdgeBaseURL");function voe(e,t){return{shell:XN(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:Atn(),apiKeyConfigured:Itn(e),baseURL:Ctn(e.DEEPSEEK_BASE_URL),maxTokens:SX(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Xy(e.DEEPSEEK_MODEL),reasoningEffort:bX(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:I4(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:xX(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:s0(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(voe,"resolveEdgeDeploymentProfile");function QN(e){Pv(e);let t=voe(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:By,upstreamVersion:LEe,status:"ready"}}a(QN,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as F0n}from"node:async_hooks";import{RpcTarget as Rtn}from"cloudflare:workers";function Otn(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(Otn,"startHeartbeat");async function $tn(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($tn,"probeComputerdHealth");var Ntn="computer.internal",Ptn="/health",woe="/api",Mtn=8080,Dtn=3e4,Ltn=2e4,jtn=1,Ftn=2e3,qtn=250,Utn=2e3;function Btn(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(Btn,"bearerMatches");var tP=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??Ntn,containerPort:e.containerPort??Mtn,connectTimeoutMs:e.connectTimeoutMs??Dtn,heartbeatIntervalMs:e.heartbeatIntervalMs??Ltn,restartAttempts:e.restartAttempts??jtn,healthProbeTimeoutMs:e.healthProbeTimeoutMs??Ftn,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??qtn,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??Utn}}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 Nc(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 Nc(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=ID(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=Otn({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(RA),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!==woe)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${woe} requires a websocket upgrade`,{status:400});if(!Btn(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 Nc(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 Nc(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 $tn(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 ztn(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=${wje(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 Nc(`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:Ptn,api:woe,healthTimeoutMs:r})})}catch(s){throw this.#a?.(s),this.#o(),new Nc(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${wje(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 Nc(`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 Nc(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#o()}}};function ztn(e){return new Promise(t=>setTimeout(t,e))}a(ztn,"sleep");function wje(e){return e instanceof Error?e.message:String(e)}a(wje,"describeError");var bje="computer:container-client-secret",Wtn=16;function Htn(){let e=crypto.getRandomValues(new Uint8Array(Wtn));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(Htn,"generate");var Vtn=class{static{a(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(bje);if(typeof e=="string"&&e.length>0)return e;let t=Htn();return await this.storage.put(bje,t),t}},xje="computer:container-launch-record";async function Sje(e){return{enableInternet:e.enableInternet,envDigest:await Ktn(e.env)}}a(Sje,"launchRecordFor");function Gtn(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}a(Gtn,"sameLaunch");async function Ktn(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(Ktn,"digestEnv");var Ztn=class{static{a(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(xje)??null}async set(e){await this.storage.put(xje,e)}},kje=new WeakMap;function Soe(e){let t=kje.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},kje.set(e,t)),t}a(Soe,"getContainerLifecycle");function eP(e){return Soe(e).exit}a(eP,"containerExitInfo");function Eje(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}a(Eje,"formatExitReason");function _je(e,t,n){let r=Soe(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>Tje(r,i,void 0,n),s=>Tje(r,i,s,n))}a(_je,"installContainerMonitor");async function boe(e,t){let n=Soe(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}a(boe,"destroyContainerExpectingExit");async function Tje(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=Eje(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:Eje(c),exitedAt:Date.now()})}}a(Tje,"recordExit");var xoe="computer:container-runtime-identity",Ytn=class{static{a(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(xoe)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(xoe,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(xoe)}},Jtn=class extends Rtn{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 Ytn(e.storage),this.#n=new Vtn(e.storage),this.#i=new Ztn(e.storage)}async start(e){let t=eP(this.#t),n=await this.#n.ensure(),r=await Sje(e);if(t!==null){try{await boe(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||!Gtn(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 boe(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return _je(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await boe(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await Sje(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),_je(this.#t,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:eP(this.#t)}}async exitInfo(){return eP(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=eP(this.#t);if(r!==null)throw new Nc(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function Aje(e){class t extends e{static{a(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new Jtn(this.ctx)}}return t}a(Aje,"withWorkspaceContainer");var Xtn={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function Cje(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=Xtn[s]??s,l=e[c];if(l===void 0)return;let u=l[o];return typeof u=="function"?u:void 0}a(Cje,"resolve");function Qtn(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}a(Qtn,"errorResponse");async function koe(e,t,n,r,i){let s=Cje(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}a(koe,"callEdgeApi");async function Rje(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(Cje(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 koe(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 Qtn(o,{code:"internal",message:String(l),details:{}})}}a(Rje,"dispatchEdgeApi");mr();Ls();t1();import{DurableObject as q0n}from"cloudflare:workers";var nP=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 enn(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 enn(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(enn,"untilAborted");import{WorkerEntrypoint as Ccr}from"cloudflare:workers";var dw=ml(Oje());import{gunzipSync as sin}from"node:zlib";var w3=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(b=>{if(b=this.postProcess(b,r),i){setTimeout(function(){i(b)},0);return}else return b},"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,w=a(()=>{for(let b=Math.max(y,-u);b<=Math.min(v,u);b+=2){let S,k=h[b-1],E=h[b+1];k&&(h[b-1]=void 0);let _=!1;if(E){let P=E.oldPos-b;_=E&&0<=P&&P<c}let T=k&&k.oldPos+1<l;if(!_&&!T){h[b]=void 0;continue}if(!T||_&&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,b,r),S.oldPos+1>=l&&g+1>=c)return o(this.buildValues(S.lastComponent,n,t))||!0;h[b]=S,S.oldPos+1>=l&&(v=Math.min(v,b-1)),g+1>=c&&(y=Math.max(y,b+1))}u++},"execEditLength");if(i)a(function b(){setTimeout(function(){if(u>d||Date.now()>f)return i(void 0);w()||b()},0)},"exec")();else for(;u<=d&&Date.now()<=f;){let b=w();if(b)return b}}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 Eoe=class extends w3{static{a(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=nnn}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
5931
+ `}a(vje,"pageStyles");U6();var foe="enabled",hoe=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")}),v3=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")}),moe=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===foe?"available":"needs-binding","probe")}),Ttn=Object.freeze([moe,v3,hoe]);function goe(e,t=Ttn){return t.filter(n=>n.probe(e)==="available")}a(goe,"availableEdgeRuntimeProviders");function yoe(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(yoe,"resolveEdgeRuntimeSelection");function XN(e){let t=goe(e),{bash:n,container:r}=yoe(t);return t.find(i=>i.id===(r??n)).shell}a(XN,"resolveEdgeRuntimeShell");function Atn(){return"dsh-edge@0.24.0/direct"}a(Atn,"resolveEdgeDeploymentId");function Pv(e){return{baseURL:wX(e.DEEPSEEK_BASE_URL),maxTokens:SX(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Xy(e.DEEPSEEK_MODEL),reasoningEffort:bX(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:I4(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:xX(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:s0(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(Pv,"resolveEdgeDeploymentConfig");function Itn(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(Itn,"edgeDeploymentApiKeyConfigured");function Ctn(e){let t=wX(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(Ctn,"projectedEdgeBaseURL");function voe(e,t){return{shell:XN(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:Atn(),apiKeyConfigured:Itn(e),baseURL:Ctn(e.DEEPSEEK_BASE_URL),maxTokens:SX(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Xy(e.DEEPSEEK_MODEL),reasoningEffort:bX(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:I4(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:xX(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:s0(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(voe,"resolveEdgeDeploymentProfile");function QN(e){Pv(e);let t=voe(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:By,upstreamVersion:LEe,status:"ready"}}a(QN,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as F0n}from"node:async_hooks";import{RpcTarget as Rtn}from"cloudflare:workers";function Otn(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(Otn,"startHeartbeat");async function $tn(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($tn,"probeComputerdHealth");var Ntn="computer.internal",Ptn="/health",woe="/api",Mtn=8080,Dtn=3e4,Ltn=2e4,jtn=1,Ftn=2e3,qtn=250,Utn=2e3;function Btn(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(Btn,"bearerMatches");var tP=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??Ntn,containerPort:e.containerPort??Mtn,connectTimeoutMs:e.connectTimeoutMs??Dtn,heartbeatIntervalMs:e.heartbeatIntervalMs??Ltn,restartAttempts:e.restartAttempts??jtn,healthProbeTimeoutMs:e.healthProbeTimeoutMs??Ftn,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??qtn,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??Utn}}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 Nc(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 Nc(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=ID(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=Otn({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(RA),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!==woe)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${woe} requires a websocket upgrade`,{status:400});if(!Btn(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 Nc(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 Nc(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 $tn(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 ztn(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=${wje(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 Nc(`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:Ptn,api:woe,healthTimeoutMs:r})})}catch(s){throw this.#a?.(s),this.#o(),new Nc(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${wje(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 Nc(`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 Nc(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#o()}}};function ztn(e){return new Promise(t=>setTimeout(t,e))}a(ztn,"sleep");function wje(e){return e instanceof Error?e.message:String(e)}a(wje,"describeError");var bje="computer:container-client-secret",Wtn=16;function Htn(){let e=crypto.getRandomValues(new Uint8Array(Wtn));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(Htn,"generate");var Vtn=class{static{a(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(bje);if(typeof e=="string"&&e.length>0)return e;let t=Htn();return await this.storage.put(bje,t),t}},xje="computer:container-launch-record";async function Sje(e){return{enableInternet:e.enableInternet,envDigest:await Ktn(e.env)}}a(Sje,"launchRecordFor");function Gtn(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}a(Gtn,"sameLaunch");async function Ktn(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(Ktn,"digestEnv");var Ztn=class{static{a(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(xje)??null}async set(e){await this.storage.put(xje,e)}},kje=new WeakMap;function Soe(e){let t=kje.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},kje.set(e,t)),t}a(Soe,"getContainerLifecycle");function eP(e){return Soe(e).exit}a(eP,"containerExitInfo");function Eje(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}a(Eje,"formatExitReason");function _je(e,t,n){let r=Soe(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>Tje(r,i,void 0,n),s=>Tje(r,i,s,n))}a(_je,"installContainerMonitor");async function boe(e,t){let n=Soe(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}a(boe,"destroyContainerExpectingExit");async function Tje(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=Eje(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:Eje(c),exitedAt:Date.now()})}}a(Tje,"recordExit");var xoe="computer:container-runtime-identity",Ytn=class{static{a(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(xoe)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(xoe,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(xoe)}},Jtn=class extends Rtn{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 Ytn(e.storage),this.#n=new Vtn(e.storage),this.#i=new Ztn(e.storage)}async start(e){let t=eP(this.#t),n=await this.#n.ensure(),r=await Sje(e);if(t!==null){try{await boe(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||!Gtn(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 boe(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return _je(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await boe(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await Sje(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),_je(this.#t,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:eP(this.#t)}}async exitInfo(){return eP(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=eP(this.#t);if(r!==null)throw new Nc(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function Aje(e){class t extends e{static{a(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new Jtn(this.ctx)}}return t}a(Aje,"withWorkspaceContainer");var Xtn={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function Cje(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=Xtn[s]??s,l=e[c];if(l===void 0)return;let u=l[o];return typeof u=="function"?u:void 0}a(Cje,"resolve");function Qtn(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}a(Qtn,"errorResponse");async function koe(e,t,n,r,i){let s=Cje(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}a(koe,"callEdgeApi");async function Rje(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(Cje(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 koe(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 Qtn(o,{code:"internal",message:String(l),details:{}})}}a(Rje,"dispatchEdgeApi");mr();Ls();t1();import{DurableObject as q0n}from"cloudflare:workers";var nP=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 enn(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 enn(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(enn,"untilAborted");import{WorkerEntrypoint as Ccr}from"cloudflare:workers";var dw=ml(Oje());import{gunzipSync as sin}from"node:zlib";var w3=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(b=>{if(b=this.postProcess(b,r),i){setTimeout(function(){i(b)},0);return}else return b},"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,w=a(()=>{for(let b=Math.max(y,-u);b<=Math.min(v,u);b+=2){let S,k=h[b-1],E=h[b+1];k&&(h[b-1]=void 0);let _=!1;if(E){let P=E.oldPos-b;_=E&&0<=P&&P<c}let T=k&&k.oldPos+1<l;if(!_&&!T){h[b]=void 0;continue}if(!T||_&&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,b,r),S.oldPos+1>=l&&g+1>=c)return o(this.buildValues(S.lastComponent,n,t))||!0;h[b]=S,S.oldPos+1>=l&&(v=Math.min(v,b-1)),g+1>=c&&(y=Math.max(y,b+1))}u++},"execEditLength");if(i)a(function b(){setTimeout(function(){if(u>d||Date.now()>f)return i(void 0);w()||b()},0)},"exec")();else for(;u<=d&&Date.now()<=f;){let b=w();if(b)return b}}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 Eoe=class extends w3{static{a(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=nnn}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
5932
5932
  `))&&(t=t.trim()),(!r.newlineIsToken||!n.includes(`
5933
5933
  `))&&(n=n.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
5934
5934
  `)&&(t=t.slice(0,-1)),n.endsWith(`
@@ -152,7 +152,7 @@ Known schemas:
152
152
  - `)}`,new Error(Ge)}let yt=`${l}/$ref`,it=As(e,Le,n,r,i,s,a,yt,c);if(it.valid||ke.push({instanceLocation:a,keyword:"$ref",keywordLocation:yt,error:"A subschema had errors."},...it.errors),n==="4"||n==="7")return{valid:ke.length===0,errors:ke}}if(Array.isArray(g)){let Be=g.length,Le=!1;for(let yt=0;yt<Be;yt++)if(d===g[yt]||g[yt]==="integer"&&d==="number"&&e%1===0&&e===e){Le=!0;break}Le||ke.push({instanceLocation:a,keyword:"type",keywordLocation:`${l}/type`,error:`Instance type "${d}" is invalid. Expected "${g.join('", "')}".`})}else g==="integer"?(d!=="number"||e%1||e!==e)&&ke.push({instanceLocation:a,keyword:"type",keywordLocation:`${l}/type`,error:`Instance type "${d}" is invalid. Expected "${g}".`}):g!==void 0&&d!==g&&ke.push({instanceLocation:a,keyword:"type",keywordLocation:`${l}/type`,error:`Instance type "${d}" is invalid. Expected "${g}".`});if(y!==void 0&&(d==="object"||d==="array"?M3(e,y)||ke.push({instanceLocation:a,keyword:"const",keywordLocation:`${l}/const`,error:`Instance does not match ${JSON.stringify(y)}.`}):e!==y&&ke.push({instanceLocation:a,keyword:"const",keywordLocation:`${l}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})),v!==void 0&&(d==="object"||d==="array"?v.some(Be=>M3(e,Be))||ke.push({instanceLocation:a,keyword:"enum",keywordLocation:`${l}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`}):v.some(Be=>e===Be)||ke.push({instanceLocation:a,keyword:"enum",keywordLocation:`${l}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})),S!==void 0){let Be=`${l}/not`;As(e,S,n,r,i,s,a,Be).valid&&ke.push({instanceLocation:a,keyword:"not",keywordLocation:Be,error:'Instance matched "not" schema.'})}let lt=[];if(k!==void 0){let Be=`${l}/anyOf`,Le=ke.length,yt=!1;for(let it=0;it<k.length;it++){let Ge=k[it],mt=Object.create(c),Re=As(e,Ge,n,r,i,h===!0?s:null,a,`${Be}/${it}`,mt);ke.push(...Re.errors),yt=yt||Re.valid,Re.valid&&lt.push(mt)}yt?ke.length=Le:ke.splice(Le,0,{instanceLocation:a,keyword:"anyOf",keywordLocation:Be,error:"Instance does not match any subschemas."})}if(x!==void 0){let Be=`${l}/allOf`,Le=ke.length,yt=!0;for(let it=0;it<x.length;it++){let Ge=x[it],mt=Object.create(c),Re=As(e,Ge,n,r,i,h===!0?s:null,a,`${Be}/${it}`,mt);ke.push(...Re.errors),yt=yt&&Re.valid,Re.valid&&lt.push(mt)}yt?ke.length=Le:ke.splice(Le,0,{instanceLocation:a,keyword:"allOf",keywordLocation:Be,error:"Instance does not match every subschema."})}if(E!==void 0){let Be=`${l}/oneOf`,Le=ke.length,yt=E.filter((it,Ge)=>{let mt=Object.create(c),Re=As(e,it,n,r,i,h===!0?s:null,a,`${Be}/${Ge}`,mt);return ke.push(...Re.errors),Re.valid&&lt.push(mt),Re.valid}).length;yt===1?ke.length=Le:ke.splice(Le,0,{instanceLocation:a,keyword:"oneOf",keywordLocation:Be,error:`Instance does not match exactly one subschema (${yt} matches).`})}if((d==="object"||d==="array")&&Object.assign(c,...lt),T!==void 0){let Be=`${l}/if`;if(As(e,T,n,r,i,s,a,Be,c).valid){if(R!==void 0){let yt=As(e,R,n,r,i,s,a,`${l}/then`,c);yt.valid||ke.push({instanceLocation:a,keyword:"if",keywordLocation:Be,error:'Instance does not match "then" schema.'},...yt.errors)}}else if(U!==void 0){let yt=As(e,U,n,r,i,s,a,`${l}/else`,c);yt.valid||ke.push({instanceLocation:a,keyword:"if",keywordLocation:Be,error:'Instance does not match "else" schema.'},...yt.errors)}}if(d==="object"){if(b!==void 0)for(let it of b)it in e||ke.push({instanceLocation:a,keyword:"required",keywordLocation:`${l}/required`,error:`Instance does not have required property "${it}".`});let Be=Object.keys(e);if(I!==void 0&&Be.length<I&&ke.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${l}/minProperties`,error:`Instance does not have at least ${I} properties.`}),z!==void 0&&Be.length>z&&ke.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${l}/maxProperties`,error:`Instance does not have at least ${z} properties.`}),A!==void 0){let it=`${l}/propertyNames`;for(let Ge in e){let mt=`${a}/${Oc(Ge)}`,Re=As(Ge,A,n,r,i,s,mt,it);Re.valid||ke.push({instanceLocation:a,keyword:"propertyNames",keywordLocation:it,error:`Property name "${Ge}" does not match schema.`},...Re.errors)}}if(C!==void 0){let it=`${l}/dependantRequired`;for(let Ge in C)if(Ge in e){let mt=C[Ge];for(let Re of mt)Re in e||ke.push({instanceLocation:a,keyword:"dependentRequired",keywordLocation:it,error:`Instance has "${Ge}" but does not have "${Re}".`})}}if(N!==void 0)for(let it in N){let Ge=`${l}/dependentSchemas`;if(it in e){let mt=As(e,N[it],n,r,i,s,a,`${Ge}/${Oc(it)}`,c);mt.valid||ke.push({instanceLocation:a,keyword:"dependentSchemas",keywordLocation:Ge,error:`Instance has "${it}" but does not match dependant schema.`},...mt.errors)}}if(D!==void 0){let it=`${l}/dependencies`;for(let Ge in D)if(Ge in e){let mt=D[Ge];if(Array.isArray(mt))for(let Re of mt)Re in e||ke.push({instanceLocation:a,keyword:"dependencies",keywordLocation:it,error:`Instance has "${Ge}" but does not have "${Re}".`});else{let Re=As(e,mt,n,r,i,s,a,`${it}/${Oc(Ge)}`);Re.valid||ke.push({instanceLocation:a,keyword:"dependencies",keywordLocation:it,error:`Instance has "${Ge}" but does not match dependant schema.`},...Re.errors)}}}let Le=Object.create(null),yt=!1;if(B!==void 0){let it=`${l}/properties`;for(let Ge in B){if(!(Ge in e))continue;let mt=`${a}/${Oc(Ge)}`,Re=As(e[Ge],B[Ge],n,r,i,s,mt,`${it}/${Oc(Ge)}`);if(Re.valid)c[Ge]=Le[Ge]=!0;else if(yt=i,ke.push({instanceLocation:a,keyword:"properties",keywordLocation:it,error:`Property "${Ge}" does not match schema.`},...Re.errors),yt)break}}if(!yt&&$!==void 0){let it=`${l}/patternProperties`;for(let Ge in $){let mt=new RegExp(Ge,"u"),Re=$[Ge];for(let kt in e){if(!mt.test(kt))continue;let zt=`${a}/${Oc(kt)}`,pt=As(e[kt],Re,n,r,i,s,zt,`${it}/${Oc(Ge)}`);pt.valid?c[kt]=Le[kt]=!0:(yt=i,ke.push({instanceLocation:a,keyword:"patternProperties",keywordLocation:it,error:`Property "${kt}" matches pattern "${Ge}" but does not match associated schema.`},...pt.errors))}}}if(!yt&&V!==void 0){let it=`${l}/additionalProperties`;for(let Ge in e){if(Le[Ge])continue;let mt=`${a}/${Oc(Ge)}`,Re=As(e[Ge],V,n,r,i,s,mt,it);Re.valid?c[Ge]=!0:(yt=i,ke.push({instanceLocation:a,keyword:"additionalProperties",keywordLocation:it,error:`Property "${Ge}" does not match additional properties schema.`},...Re.errors))}}else if(!yt&&X!==void 0){let it=`${l}/unevaluatedProperties`;for(let Ge in e)if(!c[Ge]){let mt=`${a}/${Oc(Ge)}`,Re=As(e[Ge],X,n,r,i,s,mt,it);Re.valid?c[Ge]=!0:ke.push({instanceLocation:a,keyword:"unevaluatedProperties",keywordLocation:it,error:`Property "${Ge}" does not match unevaluated properties schema.`},...Re.errors)}}}else if(d==="array"){le!==void 0&&e.length>le&&ke.push({instanceLocation:a,keyword:"maxItems",keywordLocation:`${l}/maxItems`,error:`Array has too many items (${e.length} > ${le}).`}),ve!==void 0&&e.length<ve&&ke.push({instanceLocation:a,keyword:"minItems",keywordLocation:`${l}/minItems`,error:`Array has too few items (${e.length} < ${ve}).`});let Be=e.length,Le=0,yt=!1;if(P!==void 0){let it=`${l}/prefixItems`,Ge=Math.min(P.length,Be);for(;Le<Ge;Le++){let mt=As(e[Le],P[Le],n,r,i,s,`${a}/${Le}`,`${it}/${Le}`);if(c[Le]=!0,!mt.valid&&(yt=i,ke.push({instanceLocation:a,keyword:"prefixItems",keywordLocation:it,error:"Items did not match schema."},...mt.errors),yt))break}}if(G!==void 0){let it=`${l}/items`;if(Array.isArray(G)){let Ge=Math.min(G.length,Be);for(;Le<Ge;Le++){let mt=As(e[Le],G[Le],n,r,i,s,`${a}/${Le}`,`${it}/${Le}`);if(c[Le]=!0,!mt.valid&&(yt=i,ke.push({instanceLocation:a,keyword:"items",keywordLocation:it,error:"Items did not match schema."},...mt.errors),yt))break}}else for(;Le<Be;Le++){let Ge=As(e[Le],G,n,r,i,s,`${a}/${Le}`,it);if(c[Le]=!0,!Ge.valid&&(yt=i,ke.push({instanceLocation:a,keyword:"items",keywordLocation:it,error:"Items did not match schema."},...Ge.errors),yt))break}if(!yt&&J!==void 0){let Ge=`${l}/additionalItems`;for(;Le<Be;Le++){let mt=As(e[Le],J,n,r,i,s,`${a}/${Le}`,Ge);c[Le]=!0,mt.valid||(yt=i,ke.push({instanceLocation:a,keyword:"additionalItems",keywordLocation:Ge,error:"Items did not match additional items schema."},...mt.errors))}}}if(F!==void 0)if(Be===0&&ee===void 0)ke.push({instanceLocation:a,keyword:"contains",keywordLocation:`${l}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(ee!==void 0&&Be<ee)ke.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${l}/minContains`,error:`Array has less items (${Be}) than minContains (${ee}).`});else{let it=`${l}/contains`,Ge=ke.length,mt=0;for(let Re=0;Re<Be;Re++){let kt=As(e[Re],F,n,r,i,s,`${a}/${Re}`,it);kt.valid?(c[Re]=!0,mt++):ke.push(...kt.errors)}mt>=(ee||0)&&(ke.length=Ge),ee===void 0&&ge===void 0&&mt===0?ke.splice(Ge,0,{instanceLocation:a,keyword:"contains",keywordLocation:it,error:"Array does not contain item matching schema."}):ee!==void 0&&mt<ee?ke.push({instanceLocation:a,keyword:"minContains",keywordLocation:`${l}/minContains`,error:`Array must contain at least ${ee} items matching schema. Only ${mt} items were found.`}):ge!==void 0&&mt>ge&&ke.push({instanceLocation:a,keyword:"maxContains",keywordLocation:`${l}/maxContains`,error:`Array may contain at most ${ge} items matching schema. ${mt} items were found.`})}if(!yt&&K!==void 0){let it=`${l}/unevaluatedItems`;for(Le;Le<Be;Le++){if(c[Le])continue;let Ge=As(e[Le],K,n,r,i,s,`${a}/${Le}`,it);c[Le]=!0,Ge.valid||ke.push({instanceLocation:a,keyword:"unevaluatedItems",keywordLocation:it,error:"Items did not match unevaluated items schema."},...Ge.errors)}}if(xe)for(let it=0;it<Be;it++){let Ge=e[it],mt=typeof Ge=="object"&&Ge!==null;for(let Re=0;Re<Be;Re++){if(it===Re)continue;let kt=e[Re];(Ge===kt||mt&&(typeof kt=="object"&&kt!==null)&&M3(Ge,kt))&&(ke.push({instanceLocation:a,keyword:"uniqueItems",keywordLocation:`${l}/uniqueItems`,error:`Duplicate items at indexes ${it} and ${Re}.`}),it=Number.MAX_SAFE_INTEGER,Re=Number.MAX_SAFE_INTEGER)}}}else if(d==="number"){if(n==="4"?(Ee!==void 0&&(ue===!0&&e<=Ee||e<Ee)&&ke.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${l}/minimum`,error:`${e} is less than ${ue?"or equal to ":""} ${Ee}.`}),ce!==void 0&&(st===!0&&e>=ce||e>ce)&&ke.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${l}/maximum`,error:`${e} is greater than ${st?"or equal to ":""} ${ce}.`})):(Ee!==void 0&&e<Ee&&ke.push({instanceLocation:a,keyword:"minimum",keywordLocation:`${l}/minimum`,error:`${e} is less than ${Ee}.`}),ce!==void 0&&e>ce&&ke.push({instanceLocation:a,keyword:"maximum",keywordLocation:`${l}/maximum`,error:`${e} is greater than ${ce}.`}),ue!==void 0&&e<=ue&&ke.push({instanceLocation:a,keyword:"exclusiveMinimum",keywordLocation:`${l}/exclusiveMinimum`,error:`${e} is less than ${ue}.`}),st!==void 0&&e>=st&&ke.push({instanceLocation:a,keyword:"exclusiveMaximum",keywordLocation:`${l}/exclusiveMaximum`,error:`${e} is greater than or equal to ${st}.`})),He!==void 0){let Be=e%He;Math.abs(0-Be)>=11920929e-14&&Math.abs(He-Be)>=11920929e-14&&ke.push({instanceLocation:a,keyword:"multipleOf",keywordLocation:`${l}/multipleOf`,error:`${e} is not a multiple of ${He}.`})}}else if(d==="string"){let Be=rt===void 0&&Ie===void 0?0:Eve(e);rt!==void 0&&Be<rt&&ke.push({instanceLocation:a,keyword:"minLength",keywordLocation:`${l}/minLength`,error:`String is too short (${Be} < ${rt}).`}),Ie!==void 0&&Be>Ie&&ke.push({instanceLocation:a,keyword:"maxLength",keywordLocation:`${l}/maxLength`,error:`String is too long (${Be} > ${Ie}).`}),Se!==void 0&&!new RegExp(Se,"u").test(e)&&ke.push({instanceLocation:a,keyword:"pattern",keywordLocation:`${l}/pattern`,error:"String does not match pattern."}),H!==void 0&&FV[H]&&!FV[H](e)&&ke.push({instanceLocation:a,keyword:"format",keywordLocation:`${l}/format`,error:`String does not match format "${H}".`})}return{valid:ke.length===0,errors:ke}}var BV=se(()=>{jV();rA();UV();nA();qV();o(As,"validate")});var iA,_ve=se(()=>{rA();BV();iA=class{static{o(this,"Validator")}schema;draft;shortCircuit;lookup;constructor(t,n="2019-09",r=!0){this.schema=t,this.draft=n,this.shortCircuit=r,this.lookup=lh(t)}validate(t){return As(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,n){n&&(t={...t,$id:n}),lh(t,this.lookup)}}});var Tve=se(()=>{jV();rA();UV();nA();kve();qV();BV();_ve()});var sA,Ave=se(()=>{Tve();sA=class{static{o(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let n=new iA(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 ua,aA=se(()=>{"use strict";ua={probeTimeoutMs:3e4,callTimeoutMs:6e4,maxToolsPerServer:128,maxCatalogPages:10,maxCatalogBytes:131072,maxDescriptionLength:512,maxErrorMessageChars:300,maxPublicNameLength:64,maxInstructionsLength:1024,metaToolThreshold:20}});import{createHash as wht}from"node:crypto";function xht(e){let t=e.replace(/[.*+?^${}()|[\]\\]/gu,n=>n==="*"?"\0":`\\${n}`);return new RegExp(`^${t.replaceAll("\0",".*")}$`)}function Ive(e,t,n){let r=t??"read_only";return r==="allow_all"?"allow":r==="approve_all"?"ask":n===!0?"allow":n===!1?"ask":bht.some(i=>xht(i).test(e))?"allow":"ask"}function jp(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,ua.maxErrorMessageChars)}function Cve(e,t){let n=`mcp__${e}__${t}`,r=n.replace(/[^A-Za-z0-9_-]/gu,"_");if(r===n&&r.length<=ua.maxPublicNameLength)return r;let i=Sht(e,t),s=ua.maxPublicNameLength-i.length-1;return`${r.slice(0,s)}_${i}`}function Sht(e,t){return wht("sha256").update(`${e}\0${t}`).digest("hex").slice(0,12)}function Rve(e){if(!(e==null||typeof e!="object"))try{let t=JSON.parse(JSON.stringify(e));return Ng(t),t}catch{return}}function _ht(e){return kht.has(e)}function Ove(e){return e.type!=="image"||e.data===void 0||e.mimeType===void 0||!_ht(e.mimeType)||!Eht.test(e.data)?void 0:{data:Uint8Array.from(atob(e.data),n=>n.charCodeAt(0)),mediaType:e.mimeType}}function Nve(e){return e.some(t=>t.type==="image"&&t.data!==void 0)}function OS(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 bht,kht,Eht,oA=se(()=>{"use strict";vs();aA();bht=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];o(xht,"globToRegExp");o(Ive,"evaluateMcpToolPolicy");o(jp,"scrubMcpErrorMessage");o(Cve,"publicToolName");o(Sht,"hashSuffix");o(Rve,"supportedOutputSchema");kht=new Set(["image/png","image/jpeg"]),Eht=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;o(_ht,"isImageMediaType");o(Ove,"decodeImageBlock");o(Nve,"containsImage");o(OS,"mapMcpResultToContentBlocks")});var zV,$ve=se(()=>{zV={name:"dsh-edge",version:"0.24.0-alpha.1",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.2"},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",yaml:"2.9.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.2","@deepseek-ai/dsh-agent-instructions":"0.2.0-rc.2","@deepseek-ai/dsh-agent-loop":"0.2.0-rc.2","@deepseek-ai/dsh-anonymous-user-id":"0.2.0-rc.2","@deepseek-ai/dsh-api-gateway":"0.2.0-rc.2","@deepseek-ai/dsh-api-job-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-remotes":"0.2.0-rc.2","@deepseek-ai/dsh-api-session-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-settings-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-workspace-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-workspace-files":"0.2.0-rc.2","@deepseek-ai/dsh-attachment":"0.2.0-rc.2","@deepseek-ai/dsh-brand":"0.2.0-rc.2","@deepseek-ai/dsh-client-locale":"0.2.0-rc.2","@deepseek-ai/dsh-client-store":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-chat":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-conversation":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-settings":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-settings-general":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-theme":"0.2.0-rc.2","@deepseek-ai/dsh-command-compact":"0.2.0-rc.2","@deepseek-ai/dsh-command-goal":"0.2.0-rc.2","@deepseek-ai/dsh-commands":"0.2.0-rc.2","@deepseek-ai/dsh-compaction":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-basic":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-image-offload":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-tool-result-pruner":"0.2.0-rc.2","@deepseek-ai/dsh-credentials":"0.2.0-rc.2","@deepseek-ai/dsh-file-reference":"0.2.0-rc.2","@deepseek-ai/dsh-fs":"0.2.0-rc.2","@deepseek-ai/dsh-fs-observation-policy":"0.2.0-rc.2","@deepseek-ai/dsh-goal":"0.2.0-rc.2","@deepseek-ai/dsh-goal-round-driver":"0.2.0-rc.2","@deepseek-ai/dsh-home-paths":"0.2.0-rc.2","@deepseek-ai/dsh-host-directory-picker":"0.2.0-rc.2","@deepseek-ai/dsh-host-plugin-inventory":"0.2.0-rc.2","@deepseek-ai/dsh-invariants":"0.2.0-rc.2","@deepseek-ai/dsh-jobs":"0.2.0-rc.2","@deepseek-ai/dsh-jobs-local":"0.2.0-rc.2","@deepseek-ai/dsh-launch-environment":"0.2.0-rc.2","@deepseek-ai/dsh-llm":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek-api-key":"0.2.0-rc.2","@deepseek-ai/dsh-llm-retry":"0.2.0-rc.2","@deepseek-ai/dsh-message-feedback":"0.2.0-rc.2","@deepseek-ai/dsh-output-retention":"0.2.0-rc.2","@deepseek-ai/dsh-plan-mode":"0.2.0-rc.2","@deepseek-ai/dsh-ptc-runtime":"0.2.0-rc.2","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.0-rc.2","@deepseek-ai/dsh-sandbox":"0.2.0-rc.2","@deepseek-ai/dsh-schedule":"0.2.0-rc.2","@deepseek-ai/dsh-scope":"0.2.0-rc.2","@deepseek-ai/dsh-session":"0.2.0-rc.2","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.0-rc.2","@deepseek-ai/dsh-session-format":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-catalog":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.0-rc.2","@deepseek-ai/dsh-session-persistence":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection-cache":"0.2.0-rc.2","@deepseek-ai/dsh-session-stats":"0.2.0-rc.2","@deepseek-ai/dsh-session-query":"0.2.0-rc.2","@deepseek-ai/dsh-session-reference":"0.2.0-rc.2","@deepseek-ai/dsh-session-title":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-llm":"0.2.0-rc.2","@deepseek-ai/dsh-settings":"0.2.0-rc.2","@deepseek-ai/dsh-skill":"0.2.0-rc.2","@deepseek-ai/dsh-spill":"0.2.0-rc.2","@deepseek-ai/dsh-spill-policy":"0.2.0-rc.2","@deepseek-ai/dsh-storage":"0.2.0-rc.2","@deepseek-ai/dsh-storage-domain":"0.2.0-rc.2","@deepseek-ai/dsh-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-in-process-driver":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-fork-in-process":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-spawn-in-process":"0.2.0-rc.2","@deepseek-ai/dsh-system-prompt":"0.2.0-rc.2","@deepseek-ai/dsh-timeout":"0.2.0-rc.2","@deepseek-ai/dsh-token-meter":"0.2.0-rc.2","@deepseek-ai/dsh-tool-ask-user":"0.2.0-rc.2","@deepseek-ai/dsh-tool-call-timeout-policy":"0.2.0-rc.2","@deepseek-ai/dsh-tool-fs":"0.2.0-rc.2","@deepseek-ai/dsh-tool-fs-search":"0.2.0-rc.2","@deepseek-ai/dsh-tool-goal":"0.2.0-rc.2","@deepseek-ai/dsh-tool-jobs":"0.2.0-rc.2","@deepseek-ai/dsh-tool-skill":"0.2.0-rc.2","@deepseek-ai/dsh-tool-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-tool-subagent-control":"0.2.0-rc.2","@deepseek-ai/dsh-tool-present":"0.2.0-rc.2","@deepseek-ai/dsh-tool-todo":"0.2.0-rc.2","@deepseek-ai/dsh-tool-web":"0.2.0-rc.2","@deepseek-ai/dsh-tool-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-tools":"0.2.0-rc.2","@deepseek-ai/dsh-typert-protocol":"0.2.0-rc.2","@deepseek-ai/dsh-typert-registry":"0.2.0-rc.2","@deepseek-ai/dsh-user-approval":"0.2.0-rc.2","@deepseek-ai/dsh-user-questions":"0.2.0-rc.2","@deepseek-ai/dsh-util-values":"0.2.0-rc.2","@deepseek-ai/dsh-web":"0.2.0-rc.2","@deepseek-ai/dsh-web-fetch-http":"0.2.0-rc.2","@deepseek-ai/dsh-web-search-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-workspace":"0.2.0-rc.2","@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",minimatch:"10.2.6",playwright:"^1.49.0",re2js:"1.3.3",sucrase:"3.35.1",typescript:"^6.0.3",vitest:"^4.1.8",ws:"^8.21.0"}}});var v0,Pve,Dve,NS=se(()=>{"use strict";$ve();v0=zV.version,Pve=zV.dshEdge.upstreamVersion,Dve=`npx dsh-edge@${v0.includes("-")?"next":"latest"} upgrade`});function Rht(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 Oht(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function ch(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 Aht)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(Oht(i)){let s=Rht(i),a=s??i;for(let l of Iht)if(l.test(a))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`);if(s===void 0){for(let l of Cht)if(l.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function Nht(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function Mve(e,t,n){ch(e);let r=new tA(new URL(e),{requestInit:{headers:Nht(t),signal:n},fetch:w0}),i=new Q8({name:"dsh-edge",version:v0},{capabilities:{},jsonSchemaValidator:$ht});return await i.connect(r),{client:i,close:o(async()=>{await i.close().catch(()=>{})},"close")}}async function Lve(e,t,n){let r=AbortSignal.timeout(ua.probeTimeoutMs),i;try{i=await Mve(t,n,r)}catch(l){throw new Error(jp(l instanceof Error?l.message:String(l)))}let{client:s,close:a}=i;try{let l=[],c=new Set,u=new Set,d;for(let h=0;h<ua.maxCatalogPages;h++){let g=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let y of g.tools){if(l.length>=ua.maxToolsPerServer)break;let v=Cve(e,y.name);if(c.has(v))throw new Error(`Server listed tool "${y.name}" more than once`);c.add(v);let b=y.annotations?.readOnlyHint,S=Rve(y.outputSchema);l.push({name:y.name,publicName:v,description:y.description??"",inputSchema:y.inputSchema??{type:"object"},...S!==void 0?{outputSchema:S}:{},...b!==void 0?{annotations:{readOnlyHint:b}}:{}})}if(l.length>=ua.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?.(),m=s.getInstructions?.();return{tools:l,serverInfo:p?{name:p.name,version:p.version}:void 0,instructions:typeof m=="string"&&m.length>0?m.slice(0,ua.maxInstructionsLength):void 0}}finally{await a()}}async function lA(e,t,n,r,i,s){let a=s??ua.callTimeoutMs,l=i?AbortSignal.any([i,AbortSignal.timeout(a)]):AbortSignal.timeout(a),c;try{c=await Mve(e,r,l)}catch(u){throw new Error(jp(u instanceof Error?u.message:String(u)))}try{let u=await c.client.callTool({name:t,arguments:n},void 0,{signal:l});return{content:u.content??[],structuredContent:u.structuredContent,isError:u.isError===!0}}catch(u){throw new Error(jp(u instanceof Error?u.message:String(u)))}finally{await c.close()}}var Aht,Iht,Cht,$ht,w0,$S=se(()=>{"use strict";U3e();wve();Ave();oA();aA();NS();Aht=[".internal",".local",".localhost"],Iht=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],Cht=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];o(Rht,"extractMappedIPv4");o(Oht,"isIpAddress");o(ch,"assertSafeUrl");o(Nht,"buildHeaders");$ht=new sA,w0=o(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");o(Mve,"connectClient");o(Lve,"probe");o(lA,"callTool")});import{Buffer as Pht}from"node:buffer";function jht(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Lht.has(e.code)}function Fve(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Mht.has(e.code)}function Uve(e,t,n){let r=Pht.from(e,"base64");if(e.length===0&&t==="reject"||r.toString("base64")!==e)throw new lr(n==="INVALID_IMAGE_BASE64"?"Image upload is not canonical base64.":"File upload is not canonical base64.",n);return new Uint8Array(r)}function Fht(e){return Uve(e,"reject","INVALID_IMAGE_BASE64")}function Uht(e){return{data:Fht(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function PS(e,t){return e.saveImages(t.map(Uht))}async function qht(e,t){return e.saveFile({data:Uve(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function qve(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 a=Math.max(1,Math.floor(e*r)),l=Math.max(1,Math.round(a*t/e));for(;a*l>n&&a>1;)a-=1,l=Math.max(1,Math.round(a*t/e));return{width:a,height:l}}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 WV(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 jve,Dht,Mht,Lht,lr,HV,uh=se(()=>{zn();jve=["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"],Dht=[...jve,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],Mht=new Set(jve),Lht=new Set(Dht),lr=class extends Error{static{o(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};o(jht,"isAttachmentError");o(Fve,"isImageAdmissionError");o(Uve,"decodeCanonicalBase64");o(Fht,"decodeBase64");o(Uht,"saveInput");o(PS,"admitEncodedImages");o(qht,"admitEncodedFile");o(qve,"requestImageDimensions");o(WV,"longEdgeDimensions");HV=class extends St{static{o(this,"AttachmentStore")}constructor(e){super(e,"attachments")}validateImageBatch(e){let{maxImagesPerMessage:t,maxMessageImageBytes:n,mediaTypes:r}=this.imageLimits;if(e.length>t)throw new lr("Image batch exceeds the configured image-count limit.","TOO_MANY_IMAGES");if(e.reduce((i,s)=>i+s.data.byteLength,0)>n)throw new lr("Image batch exceeds the configured aggregate image-byte limit.","IMAGES_TOO_LARGE");for(let i of e)if(!r.includes(i.mediaType))throw new lr(`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 PS(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 qht(this,e)}isAttachmentError(e){return jht(e)}imageHostPath(e){}saveFile(e){return Promise.reject(new lr("The mounted attachment provider cannot store verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}saveFileStream(e){return Promise.reject(new lr("The mounted attachment provider cannot stream verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}async*readFileStream(e,t){t?.throwIfAborted(),await Promise.reject(new lr("The mounted attachment provider cannot read verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}fileHostPath(e){}readImageRequest(e,t,n){return n?.throwIfAborted(),Promise.reject(new lr("The mounted attachment provider cannot derive model-request images.","ATTACHMENT_PROJECTION_UNSUPPORTED"))}}});var uA={};nn(uA,{buildAuthorizationUrl:()=>Jht,discoverEndpoints:()=>Zht,exchangeCode:()=>Yht,isTokenExpired:()=>Qht,refreshToken:()=>Xht,registerClient:()=>Kht});function Hve(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 Ght(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 Zht(e){let t=AbortSignal.timeout(cA),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);ch(i.href);let s=await w0(i.href,{signal:t});if(!s.ok)throw new Error(`PRM discovery failed: HTTP ${s.status}`);let l=(await s.json()).authorization_servers?.[0];if(typeof l!="string")throw new Error("No authorization server in PRM");let c=new URL(l),u=c.pathname==="/"?"/.well-known/oauth-authorization-server":`/.well-known/oauth-authorization-server${c.pathname}`,d=new URL(u,c.origin);ch(d.href);let p=await w0(d.href,{signal:t});if(!p.ok)throw new Error(`AS metadata failed: HTTP ${p.status}`);let m=await p.json();if(typeof m.authorization_endpoint!="string"||typeof m.token_endpoint!="string")throw new Error("Missing required endpoints in AS metadata");return{authorization:m.authorization_endpoint,token:m.token_endpoint,registration:m.registration_endpoint}}async function Kht(e,t,n){let r=AbortSignal.timeout(cA);ch(e);let i=await w0(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 Jht(e,t,n,r,i){let s=Hve(32),a=Hve(64),l=await Ght(a),c=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:l,code_challenge_method:"S256",resource:i}))c.searchParams.set(u,d);return{authorizationUrl:c.href,pendingFlow:{state:s,codeVerifier:a,redirectUri:n,serverName:r,serverUrl:i,stagedClient:t,createdAt:Date.now()}}}async function Yht(e,t,n,r,i,s){let a=AbortSignal.timeout(cA),l=new URLSearchParams({grant_type:"authorization_code",code:n,redirect_uri:i,client_id:t.clientId,code_verifier:r});s!==void 0&&l.set("resource",s),t.clientSecret!==void 0&&l.set("client_secret",t.clientSecret),ch(e);let c=await w0(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:l.toString(),signal:a});if(!c.ok)throw new Error(`Token exchange failed: HTTP ${c.status}`);return Vve(await c.json())}async function Xht(e,t,n,r){let i=AbortSignal.timeout(cA),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),ch(e);let a=await w0(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:s.toString(),signal:i});if(!a.ok)throw new Error(`Token refresh failed: HTTP ${a.status}`);return Vve(await a.json())}function Vve(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 Qht(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var cA,dA=se(()=>{"use strict";$S();cA=1e4;o(Hve,"randomString");o(Ght,"sha256Base64Url");o(Zht,"discoverEndpoints");o(Kht,"registerClient");o(Jht,"buildAuthorizationUrl");o(Yht,"exchangeCode");o(Xht,"refreshToken");o(Vve,"parseTokenResponse");o(Qht,"isTokenExpired")});var jn,ewe,L3=se(()=>{zn();dr();jn=class extends jr{static{o(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},ewe=class extends St{static{o(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new jn("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function FS(e){return SA.test(e)}function kA(e){return e.invocation.modelInvocable}function F3(e){return e.invocation.userInvocable}function uG(e){let t=L1t(e);return[`<skill_content name="${j1t(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 bht,kht,Eht,oA=se(()=>{"use strict";vs();aA();bht=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];o(xht,"globToRegExp");o(Ive,"evaluateMcpToolPolicy");o(jp,"scrubMcpErrorMessage");o(Cve,"publicToolName");o(Sht,"hashSuffix");o(Rve,"supportedOutputSchema");kht=new Set(["image/png","image/jpeg"]),Eht=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;o(_ht,"isImageMediaType");o(Ove,"decodeImageBlock");o(Nve,"containsImage");o(OS,"mapMcpResultToContentBlocks")});var zV,$ve=se(()=>{zV={name:"dsh-edge",version:"0.24.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.2"},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",yaml:"2.9.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.2","@deepseek-ai/dsh-agent-instructions":"0.2.0-rc.2","@deepseek-ai/dsh-agent-loop":"0.2.0-rc.2","@deepseek-ai/dsh-anonymous-user-id":"0.2.0-rc.2","@deepseek-ai/dsh-api-gateway":"0.2.0-rc.2","@deepseek-ai/dsh-api-job-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-remotes":"0.2.0-rc.2","@deepseek-ai/dsh-api-session-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-settings-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-workspace-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-workspace-files":"0.2.0-rc.2","@deepseek-ai/dsh-attachment":"0.2.0-rc.2","@deepseek-ai/dsh-brand":"0.2.0-rc.2","@deepseek-ai/dsh-client-locale":"0.2.0-rc.2","@deepseek-ai/dsh-client-store":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-chat":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-conversation":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-settings":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-settings-general":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-theme":"0.2.0-rc.2","@deepseek-ai/dsh-command-compact":"0.2.0-rc.2","@deepseek-ai/dsh-command-goal":"0.2.0-rc.2","@deepseek-ai/dsh-commands":"0.2.0-rc.2","@deepseek-ai/dsh-compaction":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-basic":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-image-offload":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-tool-result-pruner":"0.2.0-rc.2","@deepseek-ai/dsh-credentials":"0.2.0-rc.2","@deepseek-ai/dsh-file-reference":"0.2.0-rc.2","@deepseek-ai/dsh-fs":"0.2.0-rc.2","@deepseek-ai/dsh-fs-observation-policy":"0.2.0-rc.2","@deepseek-ai/dsh-goal":"0.2.0-rc.2","@deepseek-ai/dsh-goal-round-driver":"0.2.0-rc.2","@deepseek-ai/dsh-home-paths":"0.2.0-rc.2","@deepseek-ai/dsh-host-directory-picker":"0.2.0-rc.2","@deepseek-ai/dsh-host-plugin-inventory":"0.2.0-rc.2","@deepseek-ai/dsh-invariants":"0.2.0-rc.2","@deepseek-ai/dsh-jobs":"0.2.0-rc.2","@deepseek-ai/dsh-jobs-local":"0.2.0-rc.2","@deepseek-ai/dsh-launch-environment":"0.2.0-rc.2","@deepseek-ai/dsh-llm":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek-api-key":"0.2.0-rc.2","@deepseek-ai/dsh-llm-retry":"0.2.0-rc.2","@deepseek-ai/dsh-message-feedback":"0.2.0-rc.2","@deepseek-ai/dsh-output-retention":"0.2.0-rc.2","@deepseek-ai/dsh-plan-mode":"0.2.0-rc.2","@deepseek-ai/dsh-ptc-runtime":"0.2.0-rc.2","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.0-rc.2","@deepseek-ai/dsh-sandbox":"0.2.0-rc.2","@deepseek-ai/dsh-schedule":"0.2.0-rc.2","@deepseek-ai/dsh-scope":"0.2.0-rc.2","@deepseek-ai/dsh-session":"0.2.0-rc.2","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.0-rc.2","@deepseek-ai/dsh-session-format":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-catalog":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.0-rc.2","@deepseek-ai/dsh-session-persistence":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection-cache":"0.2.0-rc.2","@deepseek-ai/dsh-session-stats":"0.2.0-rc.2","@deepseek-ai/dsh-session-query":"0.2.0-rc.2","@deepseek-ai/dsh-session-reference":"0.2.0-rc.2","@deepseek-ai/dsh-session-title":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-llm":"0.2.0-rc.2","@deepseek-ai/dsh-settings":"0.2.0-rc.2","@deepseek-ai/dsh-skill":"0.2.0-rc.2","@deepseek-ai/dsh-spill":"0.2.0-rc.2","@deepseek-ai/dsh-spill-policy":"0.2.0-rc.2","@deepseek-ai/dsh-storage":"0.2.0-rc.2","@deepseek-ai/dsh-storage-domain":"0.2.0-rc.2","@deepseek-ai/dsh-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-in-process-driver":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-fork-in-process":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-spawn-in-process":"0.2.0-rc.2","@deepseek-ai/dsh-system-prompt":"0.2.0-rc.2","@deepseek-ai/dsh-timeout":"0.2.0-rc.2","@deepseek-ai/dsh-token-meter":"0.2.0-rc.2","@deepseek-ai/dsh-tool-ask-user":"0.2.0-rc.2","@deepseek-ai/dsh-tool-call-timeout-policy":"0.2.0-rc.2","@deepseek-ai/dsh-tool-fs":"0.2.0-rc.2","@deepseek-ai/dsh-tool-fs-search":"0.2.0-rc.2","@deepseek-ai/dsh-tool-goal":"0.2.0-rc.2","@deepseek-ai/dsh-tool-jobs":"0.2.0-rc.2","@deepseek-ai/dsh-tool-skill":"0.2.0-rc.2","@deepseek-ai/dsh-tool-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-tool-subagent-control":"0.2.0-rc.2","@deepseek-ai/dsh-tool-present":"0.2.0-rc.2","@deepseek-ai/dsh-tool-todo":"0.2.0-rc.2","@deepseek-ai/dsh-tool-web":"0.2.0-rc.2","@deepseek-ai/dsh-tool-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-tools":"0.2.0-rc.2","@deepseek-ai/dsh-typert-protocol":"0.2.0-rc.2","@deepseek-ai/dsh-typert-registry":"0.2.0-rc.2","@deepseek-ai/dsh-user-approval":"0.2.0-rc.2","@deepseek-ai/dsh-user-questions":"0.2.0-rc.2","@deepseek-ai/dsh-util-values":"0.2.0-rc.2","@deepseek-ai/dsh-web":"0.2.0-rc.2","@deepseek-ai/dsh-web-fetch-http":"0.2.0-rc.2","@deepseek-ai/dsh-web-search-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-workspace":"0.2.0-rc.2","@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",minimatch:"10.2.6",playwright:"^1.49.0",re2js:"1.3.3",sucrase:"3.35.1",typescript:"^6.0.3",vitest:"^4.1.8",ws:"^8.21.0"}}});var v0,Pve,Dve,NS=se(()=>{"use strict";$ve();v0=zV.version,Pve=zV.dshEdge.upstreamVersion,Dve=`npx dsh-edge@${v0.includes("-")?"next":"latest"} upgrade`});function Rht(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 Oht(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function ch(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 Aht)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(Oht(i)){let s=Rht(i),a=s??i;for(let l of Iht)if(l.test(a))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`);if(s===void 0){for(let l of Cht)if(l.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function Nht(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function Mve(e,t,n){ch(e);let r=new tA(new URL(e),{requestInit:{headers:Nht(t),signal:n},fetch:w0}),i=new Q8({name:"dsh-edge",version:v0},{capabilities:{},jsonSchemaValidator:$ht});return await i.connect(r),{client:i,close:o(async()=>{await i.close().catch(()=>{})},"close")}}async function Lve(e,t,n){let r=AbortSignal.timeout(ua.probeTimeoutMs),i;try{i=await Mve(t,n,r)}catch(l){throw new Error(jp(l instanceof Error?l.message:String(l)))}let{client:s,close:a}=i;try{let l=[],c=new Set,u=new Set,d;for(let h=0;h<ua.maxCatalogPages;h++){let g=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let y of g.tools){if(l.length>=ua.maxToolsPerServer)break;let v=Cve(e,y.name);if(c.has(v))throw new Error(`Server listed tool "${y.name}" more than once`);c.add(v);let b=y.annotations?.readOnlyHint,S=Rve(y.outputSchema);l.push({name:y.name,publicName:v,description:y.description??"",inputSchema:y.inputSchema??{type:"object"},...S!==void 0?{outputSchema:S}:{},...b!==void 0?{annotations:{readOnlyHint:b}}:{}})}if(l.length>=ua.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?.(),m=s.getInstructions?.();return{tools:l,serverInfo:p?{name:p.name,version:p.version}:void 0,instructions:typeof m=="string"&&m.length>0?m.slice(0,ua.maxInstructionsLength):void 0}}finally{await a()}}async function lA(e,t,n,r,i,s){let a=s??ua.callTimeoutMs,l=i?AbortSignal.any([i,AbortSignal.timeout(a)]):AbortSignal.timeout(a),c;try{c=await Mve(e,r,l)}catch(u){throw new Error(jp(u instanceof Error?u.message:String(u)))}try{let u=await c.client.callTool({name:t,arguments:n},void 0,{signal:l});return{content:u.content??[],structuredContent:u.structuredContent,isError:u.isError===!0}}catch(u){throw new Error(jp(u instanceof Error?u.message:String(u)))}finally{await c.close()}}var Aht,Iht,Cht,$ht,w0,$S=se(()=>{"use strict";U3e();wve();Ave();oA();aA();NS();Aht=[".internal",".local",".localhost"],Iht=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],Cht=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];o(Rht,"extractMappedIPv4");o(Oht,"isIpAddress");o(ch,"assertSafeUrl");o(Nht,"buildHeaders");$ht=new sA,w0=o(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");o(Mve,"connectClient");o(Lve,"probe");o(lA,"callTool")});import{Buffer as Pht}from"node:buffer";function jht(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Lht.has(e.code)}function Fve(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Mht.has(e.code)}function Uve(e,t,n){let r=Pht.from(e,"base64");if(e.length===0&&t==="reject"||r.toString("base64")!==e)throw new lr(n==="INVALID_IMAGE_BASE64"?"Image upload is not canonical base64.":"File upload is not canonical base64.",n);return new Uint8Array(r)}function Fht(e){return Uve(e,"reject","INVALID_IMAGE_BASE64")}function Uht(e){return{data:Fht(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function PS(e,t){return e.saveImages(t.map(Uht))}async function qht(e,t){return e.saveFile({data:Uve(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function qve(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 a=Math.max(1,Math.floor(e*r)),l=Math.max(1,Math.round(a*t/e));for(;a*l>n&&a>1;)a-=1,l=Math.max(1,Math.round(a*t/e));return{width:a,height:l}}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 WV(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 jve,Dht,Mht,Lht,lr,HV,uh=se(()=>{zn();jve=["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"],Dht=[...jve,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],Mht=new Set(jve),Lht=new Set(Dht),lr=class extends Error{static{o(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};o(jht,"isAttachmentError");o(Fve,"isImageAdmissionError");o(Uve,"decodeCanonicalBase64");o(Fht,"decodeBase64");o(Uht,"saveInput");o(PS,"admitEncodedImages");o(qht,"admitEncodedFile");o(qve,"requestImageDimensions");o(WV,"longEdgeDimensions");HV=class extends St{static{o(this,"AttachmentStore")}constructor(e){super(e,"attachments")}validateImageBatch(e){let{maxImagesPerMessage:t,maxMessageImageBytes:n,mediaTypes:r}=this.imageLimits;if(e.length>t)throw new lr("Image batch exceeds the configured image-count limit.","TOO_MANY_IMAGES");if(e.reduce((i,s)=>i+s.data.byteLength,0)>n)throw new lr("Image batch exceeds the configured aggregate image-byte limit.","IMAGES_TOO_LARGE");for(let i of e)if(!r.includes(i.mediaType))throw new lr(`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 PS(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 qht(this,e)}isAttachmentError(e){return jht(e)}imageHostPath(e){}saveFile(e){return Promise.reject(new lr("The mounted attachment provider cannot store verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}saveFileStream(e){return Promise.reject(new lr("The mounted attachment provider cannot stream verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}async*readFileStream(e,t){t?.throwIfAborted(),await Promise.reject(new lr("The mounted attachment provider cannot read verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}fileHostPath(e){}readImageRequest(e,t,n){return n?.throwIfAborted(),Promise.reject(new lr("The mounted attachment provider cannot derive model-request images.","ATTACHMENT_PROJECTION_UNSUPPORTED"))}}});var uA={};nn(uA,{buildAuthorizationUrl:()=>Jht,discoverEndpoints:()=>Zht,exchangeCode:()=>Yht,isTokenExpired:()=>Qht,refreshToken:()=>Xht,registerClient:()=>Kht});function Hve(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 Ght(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 Zht(e){let t=AbortSignal.timeout(cA),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);ch(i.href);let s=await w0(i.href,{signal:t});if(!s.ok)throw new Error(`PRM discovery failed: HTTP ${s.status}`);let l=(await s.json()).authorization_servers?.[0];if(typeof l!="string")throw new Error("No authorization server in PRM");let c=new URL(l),u=c.pathname==="/"?"/.well-known/oauth-authorization-server":`/.well-known/oauth-authorization-server${c.pathname}`,d=new URL(u,c.origin);ch(d.href);let p=await w0(d.href,{signal:t});if(!p.ok)throw new Error(`AS metadata failed: HTTP ${p.status}`);let m=await p.json();if(typeof m.authorization_endpoint!="string"||typeof m.token_endpoint!="string")throw new Error("Missing required endpoints in AS metadata");return{authorization:m.authorization_endpoint,token:m.token_endpoint,registration:m.registration_endpoint}}async function Kht(e,t,n){let r=AbortSignal.timeout(cA);ch(e);let i=await w0(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 Jht(e,t,n,r,i){let s=Hve(32),a=Hve(64),l=await Ght(a),c=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:l,code_challenge_method:"S256",resource:i}))c.searchParams.set(u,d);return{authorizationUrl:c.href,pendingFlow:{state:s,codeVerifier:a,redirectUri:n,serverName:r,serverUrl:i,stagedClient:t,createdAt:Date.now()}}}async function Yht(e,t,n,r,i,s){let a=AbortSignal.timeout(cA),l=new URLSearchParams({grant_type:"authorization_code",code:n,redirect_uri:i,client_id:t.clientId,code_verifier:r});s!==void 0&&l.set("resource",s),t.clientSecret!==void 0&&l.set("client_secret",t.clientSecret),ch(e);let c=await w0(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:l.toString(),signal:a});if(!c.ok)throw new Error(`Token exchange failed: HTTP ${c.status}`);return Vve(await c.json())}async function Xht(e,t,n,r){let i=AbortSignal.timeout(cA),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),ch(e);let a=await w0(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:s.toString(),signal:i});if(!a.ok)throw new Error(`Token refresh failed: HTTP ${a.status}`);return Vve(await a.json())}function Vve(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 Qht(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var cA,dA=se(()=>{"use strict";$S();cA=1e4;o(Hve,"randomString");o(Ght,"sha256Base64Url");o(Zht,"discoverEndpoints");o(Kht,"registerClient");o(Jht,"buildAuthorizationUrl");o(Yht,"exchangeCode");o(Xht,"refreshToken");o(Vve,"parseTokenResponse");o(Qht,"isTokenExpired")});var jn,ewe,L3=se(()=>{zn();dr();jn=class extends jr{static{o(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},ewe=class extends St{static{o(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new jn("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function FS(e){return SA.test(e)}function kA(e){return e.invocation.modelInvocable}function F3(e){return e.invocation.userInvocable}function uG(e){let t=L1t(e);return[`<skill_content name="${j1t(e.name)}">`,"<skill_resources>",...t,"</skill_resources>","","<skill_instructions>",e.content,"</skill_instructions>","</skill_content>"].join(`
156
156
  `)}function L1t(e){let t=e.resourceBase;if(t===void 0)return[`Resources for this skill are managed by provider "${j3(e.provider)}".`,"Load referenced resources only as needed."];switch(t.kind){case"directory":return[`Base directory for this skill: ${j3(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: ${j3(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: ${j3(t.description)}`,"Load referenced resources only as needed."];default:return Hr(t,"SkillResourceBase.kind")}}function j1t(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;")}function j3(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function U1t(e,t){if(Array.isArray(e))return{candidates:e,complete:!0};if(e===null||typeof e!="object")throw xwe(t);let n=e;if(!Array.isArray(n.candidates)||typeof n.complete!="boolean")throw xwe(t);return n}function xwe(e){return new TypeError(`skill provider "${e}" list() must return an array or { candidates, complete } observation`)}function B1t(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:M1t,locator:e,...e.path!==void 0?{path:e.path}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}function z1t(e,t){if(typeof e.name!="string")throw new TypeError(`skill provider "${t}" returned a non-string skill name`);if(!SA.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(dG(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 W1t(e){if(!SA.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`);dG(e.invocation,`runtime skill "${e.name}"`)}function H1t(e){let t=e.name,n=e.description,r=e.whenToUse,i=e.invocation,s=e.source,a=e.provider,l=e.content,c=e.path;if(typeof t!="string")throw new TypeError("loaded skill name must be a string");if(!SA.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(dG(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 a!="string")throw new TypeError(`loaded skill "${t}" provider must be a string`);if(typeof l!="string")throw new TypeError(`loaded skill "${t}" content must be a string`);if(c!==void 0&&typeof c!="string")throw new TypeError(`loaded skill "${t}" path must be a string`)}function V1t(e){let{name:t,description:n,whenToUse:r,invocation:i,source:s,provider:a,resourceBase:l}=e;return{name:t,...e.path===void 0?{}:{path:e.path},description:n,...r!==void 0?{whenToUse:r}:{},invocation:i,source:s,provider:a,...l!==void 0?{resourceBase:l}:{}}}function dG(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 G1t(e,t){return _we(e.name,t.name)}function _we(e,t){return e<t?-1:e>t?1:0}function Z1t(e,t){return e.candidate.rank-t.candidate.rank||e.providerOrder-t.providerOrder||e.localOrder-t.localOrder}function K1t(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 Swe(e,t){return t===void 0?e:(jS(t),new Promise((n,r)=>{let i=o(()=>{t.removeEventListener("abort",s)},"cleanup"),s=o(()=>{i(),r(xA(t.reason))},"onAbort");t.addEventListener("abort",s,{once:!0}),e.then(a=>{i(),n(a)},a=>{i(),r(xA(a))})}))}function jS(e){if(e?.aborted===!0)throw xA(e.reason)}function xA(e){try{if(e instanceof Error)return e}catch{}return new Error(bA(e))}function bA(e){try{return String(e)}catch{return"[unrenderable thrown value]"}}var SA,bwe,D1t,wA,M1t,kwe,F1t,Ewe,q1t,x0=se(()=>{zn();Pi();Po();cn();SA=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,bwe=128,D1t=2,wA="runtime",M1t=250,kwe=600;o(FS,"isSkillName");o(kA,"isModelInvocable");o(F3,"isUserInvocable");o(uG,"renderSkillContent");o(L1t,"renderResourceHint");o(j1t,"escapeAttr");o(j3,"escapeText");F1t=class{static{o(this,"SkillLayer")}providers;runtime=new Map;constructor(e){this.providers=new bp(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}},Ewe=class extends St{static{o(this,"SkillRegistry")}static Config=M.object({collectCacheMaxEntries:M.number().default(bwe)});collectCacheMaxEntries;layers=new xp(e=>new F1t(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??bwe,K1t("collectCacheMaxEntries",this.collectCacheMaxEntries)}registerProvider(e){let t=new AbortController,n,r,i={signal:t.signal,invalidate:o(()=>{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===wA)throw new Error(`"${wA}" is reserved for runtime skill registrations`);let a=this.nextProviderOrder;return this.nextProviderOrder+=1,this.layers.effect(this.ctx,l=>{let c=l.providers.insert(s,{provider:r,order:a});return n={layer:l,name:s},()=>{n=void 0,c(),t.abort(new Error(`skill provider "${s}" disposed`))}},{label:"skills.registerProvider()"})}catch(s){throw t.abort(s),s}}register(e){W1t(e);let t=ao(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??wA};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=>V1t(n.candidate)).sort(G1t),complete:t.cacheable}}async get(e,t={}){if(!FS(e))return;let n=await this.collect(t);jS(t.signal);let r=n.entries.get(e);if(r===void 0)return;let i=await Swe(r.provider.get(r.candidate,t),t.signal);if(i!==void 0){if(H1t(i),i.name!==r.candidate.name){this.invalidateEntry(r);return}return i}}async collect(e){jS(e.signal);let t=1;for(;;){let n=this.revision,r=this.collectCacheKey(e.cwd,lx(e.scope),n),i=this.collectCache.get(r);if(i!==void 0)return{entries:i,cacheable:!0};let s=await this.collectFresh(e);if(jS(e.signal),n!==this.revision){if(t<D1t){t+=1;continue}return{entries:s.entries,cacheable:!1}}if(s.cacheable&&(this.collectCache.set(r,s.entries),this.collectCache.size>this.collectCacheMaxEntries)){let a=this.collectCache.keys().next();this.collectCache.delete(a.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 a of s.entries)n.set(a.candidate.name,a)}return{entries:n,cacheable:r}}async collectLayer(e,t){let n=await this.listLayerCandidates(e,t);n.entries.sort(Z1t);let r=new Set,i=[];for(let s of n.entries){let a=s.candidate;if(r.has(a.name)){this.ctx.logger.warn(`skill "${a.name}" from ${a.source} ignored because a higher-priority skill already exists`);continue}r.add(a.name),i.push(s)}return{entries:i,cacheable:n.cacheable}}async listLayerCandidates(e,t){jS(t.signal);let n=[],r=!0,i=0;for(let s of[...e.runtime.values()].sort((a,l)=>_we(a.name,l.name)))n.push({candidate:B1t(s),provider:q1t,providerOrder:-1,localOrder:i,layer:e}),i+=1;for(let{provider:s,order:a}of[...e.providers.values()]){let l=0,c;try{c=await Swe(s.list(t),t.signal)}catch(d){if(t.signal?.aborted===!0)throw xA(t.signal.reason);r=!1,this.ctx.logger.warn(`skill provider "${s.name}" skipped: ${bA(d)}`)}if(c===void 0)continue;let u=U1t(c,s.name);u.complete||(r=!1);for(let d of u.candidates)z1t(d,s.name),n.push({candidate:d,provider:s,providerOrder:a,localOrder:l,layer:e}),l+=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: ${bA(n)}`)})}catch(t){this.ctx.logger.warn(`skills/change listener threw: ${bA(t)}`)}}};o(U1t,"normalizeProviderObservation");o(xwe,"invalidProviderObservation");q1t={name:wA,list(){return Promise.resolve([])},get(e){return Promise.resolve(e.locator)}};o(B1t,"runtimeCandidate");o(z1t,"validateCandidate");o(W1t,"validateRuntimeSkill");o(H1t,"validateDefinition");o(V1t,"toSummary");o(dG,"validateInvocation");o(G1t,"compareSkillSummary");o(_we,"compareCodePoints");o(Z1t,"compareIndexedCandidates");o(K1t,"assertPositiveInteger");o(Swe,"waitWithAbort");o(jS,"throwIfAborted");o(xA,"toError");o(bA,"errorMessage")});var Eu,B3=se(()=>{Eu=class{static{o(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 ph,Vbe,YG=se(()=>{zn();ph=class extends Error{static{o(this,"DirectoryPickerError")}code;path;constructor(e,t,n){super(n),this.code=e,this.path=t,this.name="DirectoryPickerError"}},Vbe=class extends St{static{o(this,"DirectoryPicker")}constructor(e){super(e,"directoryPicker")}}});var kSe=we((N9n,G9)=>{var SSe=SSe||function(e){return Buffer.from(e).toString("base64")};function zwt(e){var t=this,n=Math.round,r=Math.floor,i=new Array(64),s=new Array(64),a=new Array(64),l=new Array(64),c,u,d,p,m=new Array(65535),h=new Array(65535),g=new Array(64),y=new Array(64),v=[],b=0,S=7,k=new Array(64),x=new Array(64),E=new Array(64),T=new Array(256),R=new Array(2048),U,H=[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],B=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],$=[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],X=[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],I=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],z=[0,1,2,3,4,5,6,7,8,9,10,11],A=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],C=[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 N(ie){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],ke=0;ke<64;ke++){var lt=r((Me[ke]*ie+50)/100);lt<1?lt=1:lt>255&&(lt=255),i[H[ke]]=lt}for(var Be=[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 yt=r((Be[Le]*ie+50)/100);yt<1?yt=1:yt>255&&(yt=255),s[H[Le]]=yt}for(var it=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379],Ge=0,mt=0;mt<8;mt++)for(var Re=0;Re<8;Re++)a[Ge]=1/(i[H[Ge]]*it[mt]*it[Re]*8),l[Ge]=1/(s[H[Ge]]*it[mt]*it[Re]*8),Ge++}o(N,"initQuantTables");function D(ie,Me){for(var ke=0,lt=0,Be=new Array,Le=1;Le<=16;Le++){for(var yt=1;yt<=ie[Le];yt++)Be[Me[lt]]=[],Be[Me[lt]][0]=ke,Be[Me[lt]][1]=Le,lt++,ke++;ke*=2}return Be}o(D,"computeHuffmanTbl");function P(){c=D(B,$),u=D(I,z),d=D(V,X),p=D(A,C)}o(P,"initHuffmanTbl");function G(){for(var ie=1,Me=2,ke=1;ke<=15;ke++){for(var lt=ie;lt<Me;lt++)h[32767+lt]=ke,m[32767+lt]=[],m[32767+lt][1]=ke,m[32767+lt][0]=lt;for(var Be=-(Me-1);Be<=-ie;Be++)h[32767+Be]=ke,m[32767+Be]=[],m[32767+Be][1]=ke,m[32767+Be][0]=Me-1+Be;ie<<=1,Me<<=1}}o(G,"initCategoryNumber");function J(){for(var ie=0;ie<256;ie++)R[ie]=19595*ie,R[ie+256>>0]=38470*ie,R[ie+512>>0]=7471*ie+32768,R[ie+768>>0]=-11059*ie,R[ie+1024>>0]=-21709*ie,R[ie+1280>>0]=32768*ie+8421375,R[ie+1536>>0]=-27439*ie,R[ie+1792>>0]=-5329*ie}o(J,"initRGBYUVTable");function K(ie){for(var Me=ie[0],ke=ie[1]-1;ke>=0;)Me&1<<ke&&(b|=1<<S),ke--,S--,S<0&&(b==255?(F(255),F(0)):F(b),S=7,b=0)}o(K,"writeBits");function F(ie){v.push(ie)}o(F,"writeByte");function ee(ie){F(ie>>8&255),F(ie&255)}o(ee,"writeWord");function ge(ie,Me){var ke,lt,Be,Le,yt,it,Ge,mt,Re=0,kt,zt=8,pt=64;for(kt=0;kt<zt;++kt){ke=ie[Re],lt=ie[Re+1],Be=ie[Re+2],Le=ie[Re+3],yt=ie[Re+4],it=ie[Re+5],Ge=ie[Re+6],mt=ie[Re+7];var yn=ke+mt,Bt=ke-mt,jt=lt+Ge,oe=lt-Ge,$e=Be+it,Ve=Be-it,at=Le+yt,Rt=Le-yt,Ye=yn+at,sn=yn-at,Qt=jt+$e,vn=jt-$e;ie[Re]=Ye+Qt,ie[Re+4]=Ye-Qt;var Dt=(vn+sn)*.707106781;ie[Re+2]=sn+Dt,ie[Re+6]=sn-Dt,Ye=Rt+Ve,Qt=Ve+oe,vn=oe+Bt;var Or=(Ye-vn)*.382683433,Mr=.5411961*Ye+Or,es=1.306562965*vn+Or,Ei=Qt*.707106781,ur=Bt+Ei,ts=Bt-Ei;ie[Re+5]=ts+Mr,ie[Re+3]=ts-Mr,ie[Re+1]=ur+es,ie[Re+7]=ur-es,Re+=8}for(Re=0,kt=0;kt<zt;++kt){ke=ie[Re],lt=ie[Re+8],Be=ie[Re+16],Le=ie[Re+24],yt=ie[Re+32],it=ie[Re+40],Ge=ie[Re+48],mt=ie[Re+56];var _s=ke+mt,Bs=ke-mt,ra=lt+Ge,Ft=lt-Ge,Dn=Be+it,ia=Be-it,Ja=Le+yt,wa=Le-yt,ba=_s+Ja,Ca=_s-Ja,Ya=ra+Dn,To=ra-Dn;ie[Re]=ba+Ya,ie[Re+32]=ba-Ya;var gc=(To+Ca)*.707106781;ie[Re+16]=Ca+gc,ie[Re+48]=Ca-gc,ba=wa+ia,Ya=ia+Ft,To=Ft+Bs;var Ol=(ba-To)*.382683433,Vu=.5411961*ba+Ol,Gu=1.306562965*To+Ol,Zu=Ya*.707106781,Ku=Bs+Zu,kf=Bs-Zu;ie[Re+40]=kf+Vu,ie[Re+24]=kf-Vu,ie[Re+8]=Ku+Gu,ie[Re+56]=Ku-Gu,Re++}var np;for(kt=0;kt<pt;++kt)np=ie[kt]*Me[kt],g[kt]=np>0?np+.5|0:np-.5|0;return g}o(ge,"fDCTQuant");function ve(){ee(65504),ee(16),F(74),F(70),F(73),F(70),F(0),F(1),F(1),F(0),ee(1),ee(1),F(0),F(0)}o(ve,"writeAPP0");function le(ie){if(ie){ee(65505),ie[0]===69&&ie[1]===120&&ie[2]===105&&ie[3]===102?ee(ie.length+2):(ee(ie.length+5+2),F(69),F(120),F(105),F(102),F(0));for(var Me=0;Me<ie.length;Me++)F(ie[Me])}}o(le,"writeAPP1");function xe(ie,Me){ee(65472),ee(17),F(8),ee(Me),ee(ie),F(3),F(1),F(17),F(0),F(2),F(17),F(1),F(3),F(17),F(1)}o(xe,"writeSOF0");function Ee(){ee(65499),ee(132),F(0);for(var ie=0;ie<64;ie++)F(i[ie]);F(1);for(var Me=0;Me<64;Me++)F(s[Me])}o(Ee,"writeDQT");function ce(){ee(65476),ee(418),F(0);for(var ie=0;ie<16;ie++)F(B[ie+1]);for(var Me=0;Me<=11;Me++)F($[Me]);F(16);for(var ke=0;ke<16;ke++)F(V[ke+1]);for(var lt=0;lt<=161;lt++)F(X[lt]);F(1);for(var Be=0;Be<16;Be++)F(I[Be+1]);for(var Le=0;Le<=11;Le++)F(z[Le]);F(17);for(var yt=0;yt<16;yt++)F(A[yt+1]);for(var it=0;it<=161;it++)F(C[it])}o(ce,"writeDHT");function ue(ie){typeof ie>"u"||ie.constructor!==Array||ie.forEach(Me=>{if(typeof Me=="string"){ee(65534);var ke=Me.length;ee(ke+2);var lt;for(lt=0;lt<ke;lt++)F(Me.charCodeAt(lt))}})}o(ue,"writeCOM");function st(){ee(65498),ee(12),F(3),F(1),F(0),F(2),F(17),F(3),F(17),F(0),F(63),F(0)}o(st,"writeSOS");function He(ie,Me,ke,lt,Be){for(var Le=Be[0],yt=Be[240],it,Ge=16,mt=63,Re=64,kt=ge(ie,Me),zt=0;zt<Re;++zt)y[H[zt]]=kt[zt];var pt=y[0]-ke;ke=y[0],pt==0?K(lt[0]):(it=32767+pt,K(lt[h[it]]),K(m[it]));for(var yn=63;yn>0&&y[yn]==0;yn--);if(yn==0)return K(Le),ke;for(var Bt=1,jt;Bt<=yn;){for(var oe=Bt;y[Bt]==0&&Bt<=yn;++Bt);var $e=Bt-oe;if($e>=Ge){jt=$e>>4;for(var Ve=1;Ve<=jt;++Ve)K(yt);$e=$e&15}it=32767+y[Bt],K(Be[($e<<4)+h[it]]),K(m[it]),Bt++}return yn!=mt&&K(Le),ke}o(He,"processDU");function rt(){for(var ie=String.fromCharCode,Me=0;Me<256;Me++)T[Me]=ie(Me)}o(rt,"initCharLookupTable"),this.encode=function(ie,Me){var ke=new Date().getTime();Me&&Ie(Me),v=new Array,b=0,S=7,ee(65496),ve(),ue(ie.comments),le(ie.exifBuffer),Ee(),xe(ie.width,ie.height),ce(),st();var lt=0,Be=0,Le=0;b=0,S=7,this.encode.displayName="_encode_";for(var yt=ie.data,it=ie.width,Ge=ie.height,mt=it*4,Re=it*3,kt,zt=0,pt,yn,Bt,jt,oe,$e,Ve,at;zt<Ge;){for(kt=0;kt<mt;){for(jt=mt*zt+kt,oe=jt,$e=-1,Ve=0,at=0;at<64;at++)Ve=at>>3,$e=(at&7)*4,oe=jt+Ve*mt+$e,zt+Ve>=Ge&&(oe-=mt*(zt+1+Ve-Ge)),kt+$e>=mt&&(oe-=kt+$e-mt+4),pt=yt[oe++],yn=yt[oe++],Bt=yt[oe++],k[at]=(R[pt]+R[yn+256>>0]+R[Bt+512>>0]>>16)-128,x[at]=(R[pt+768>>0]+R[yn+1024>>0]+R[Bt+1280>>0]>>16)-128,E[at]=(R[pt+1280>>0]+R[yn+1536>>0]+R[Bt+1792>>0]>>16)-128;lt=He(k,a,lt,c,d),Be=He(x,l,Be,u,p),Le=He(E,l,Le,u,p),kt+=32}zt+=8}if(S>=0){var Rt=[];Rt[1]=S+1,Rt[0]=(1<<S+1)-1,K(Rt)}if(ee(65497),typeof G9>"u")return new Uint8Array(v);return Buffer.from(v);var Ye,sn};function Ie(ie){if(ie<=0&&(ie=1),ie>100&&(ie=100),U!=ie){var Me=0;ie<50?Me=Math.floor(5e3/ie):Me=Math.floor(200-ie*2),N(Me),U=ie}}o(Ie,"setQuality");function Se(){var ie=new Date().getTime();e||(e=50),rt(),P(),G(),J(),Ie(e);var Me=new Date().getTime()-ie}o(Se,"init"),Se()}o(zwt,"JPEGEncoder");typeof G9<"u"?G9.exports=xSe:typeof window<"u"&&(window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=xSe);function xSe(e,t){typeof t>"u"&&(t=50);var n=new zwt(t),r=n.encode(e,t);return{data:r,width:e.width,height:e.height}}o(xSe,"encode")});var _Se=we((P9n,TK)=>{var _K=o((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,a=1567,l=3784,c=5793,u=2896;function d(){}o(d,"constructor");function p(S,k){for(var x=0,E=[],T,R,U=16;U>0&&!S[U-1];)U--;E.push({children:[],index:0});var H=E[0],B;for(T=0;T<U;T++){for(R=0;R<S[T];R++){for(H=E.pop(),H.children[H.index]=k[x];H.index>0;){if(E.length===0)throw new Error("Could not recreate Huffman Table");H=E.pop()}for(H.index++,E.push(H);E.length<=T;)E.push(B={children:[],index:0}),H.children[H.index]=B.children,H=B;x++}T+1<U&&(E.push(B={children:[],index:0}),H.children[H.index]=B.children,H=B)}return E[0].children}o(p,"buildHuffmanTable");function m(S,k,x,E,T,R,U,H,B,$){var V=x.precision,X=x.samplesPerLine,I=x.scanLines,z=x.mcusPerLine,A=x.progressive,C=x.maxH,N=x.maxV,D=k,P=0,G=0;function J(){if(G>0)return G--,P>>G&1;if(P=S[k++],P==255){var Re=S[k++];if(Re)throw new Error("unexpected marker: "+(P<<8|Re).toString(16))}return G=7,P>>>7}o(J,"readBit");function K(Re){for(var kt=Re,zt;(zt=J())!==null;){if(kt=kt[zt],typeof kt=="number")return kt;if(typeof kt!="object")throw new Error("invalid huffman sequence")}return null}o(K,"decodeHuffman");function F(Re){for(var kt=0;Re>0;){var zt=J();if(zt===null)return;kt=kt<<1|zt,Re--}return kt}o(F,"receive");function ee(Re){var kt=F(Re);return kt>=1<<Re-1?kt:kt+(-1<<Re)+1}o(ee,"receiveAndExtend");function ge(Re,kt){var zt=K(Re.huffmanTableDC),pt=zt===0?0:ee(zt);kt[0]=Re.pred+=pt;for(var yn=1;yn<64;){var Bt=K(Re.huffmanTableAC),jt=Bt&15,oe=Bt>>4;if(jt===0){if(oe<15)break;yn+=16;continue}yn+=oe;var $e=t[yn];kt[$e]=ee(jt),yn++}}o(ge,"decodeBaseline");function ve(Re,kt){var zt=K(Re.huffmanTableDC),pt=zt===0?0:ee(zt)<<B;kt[0]=Re.pred+=pt}o(ve,"decodeDCFirst");function le(Re,kt){kt[0]|=J()<<B}o(le,"decodeDCSuccessive");var xe=0;function Ee(Re,kt){if(xe>0){xe--;return}for(var zt=R,pt=U;zt<=pt;){var yn=K(Re.huffmanTableAC),Bt=yn&15,jt=yn>>4;if(Bt===0){if(jt<15){xe=F(jt)+(1<<jt)-1;break}zt+=16;continue}zt+=jt;var oe=t[zt];kt[oe]=ee(Bt)*(1<<B),zt++}}o(Ee,"decodeACFirst");var ce=0,ue;function st(Re,kt){for(var zt=R,pt=U,yn=0;zt<=pt;){var Bt=t[zt],jt=kt[Bt]<0?-1:1;switch(ce){case 0:var oe=K(Re.huffmanTableAC),$e=oe&15,yn=oe>>4;if($e===0)yn<15?(xe=F(yn)+(1<<yn),ce=4):(yn=16,ce=1);else{if($e!==1)throw new Error("invalid ACn encoding");ue=ee($e),ce=yn?2:3}continue;case 1:case 2:kt[Bt]?kt[Bt]+=(J()<<B)*jt:(yn--,yn===0&&(ce=ce==2?3:0));break;case 3:kt[Bt]?kt[Bt]+=(J()<<B)*jt:(kt[Bt]=ue<<B,ce=0);break;case 4:kt[Bt]&&(kt[Bt]+=(J()<<B)*jt);break}zt++}ce===4&&(xe--,xe===0&&(ce=0))}o(st,"decodeACSuccessive");function He(Re,kt,zt,pt,yn){var Bt=zt/z|0,jt=zt%z,oe=Bt*Re.v+pt,$e=jt*Re.h+yn;Re.blocks[oe]===void 0&&$.tolerantDecoding||kt(Re,Re.blocks[oe][$e])}o(He,"decodeMcu");function rt(Re,kt,zt){var pt=zt/Re.blocksPerLine|0,yn=zt%Re.blocksPerLine;Re.blocks[pt]===void 0&&$.tolerantDecoding||kt(Re,Re.blocks[pt][yn])}o(rt,"decodeBlock");var Ie=E.length,Se,ie,Me,ke,lt,Be;A?R===0?Be=H===0?ve:le:Be=H===0?Ee:st:Be=ge;var Le=0,yt,it;Ie==1?it=E[0].blocksPerLine*E[0].blocksPerColumn:it=z*x.mcusPerColumn,T||(T=it);for(var Ge,mt;Le<it;){for(ie=0;ie<Ie;ie++)E[ie].pred=0;if(xe=0,Ie==1)for(Se=E[0],lt=0;lt<T;lt++)rt(Se,Be,Le),Le++;else for(lt=0;lt<T;lt++){for(ie=0;ie<Ie;ie++)for(Se=E[ie],Ge=Se.h,mt=Se.v,Me=0;Me<mt;Me++)for(ke=0;ke<Ge;ke++)He(Se,Be,Le,Me,ke);if(Le++,Le===it)break}if(Le===it)do{if(S[k]===255&&S[k+1]!==0)break;k+=1}while(k<S.length-2);if(G=0,yt=S[k]<<8|S[k+1],yt<65280)throw new Error("marker was not found");if(yt>=65488&&yt<=65495)k+=2;else break}return k-D}o(m,"decodeScan");function h(S,k){var x=[],E=k.blocksPerLine,T=k.blocksPerColumn,R=E<<3,U=new Int32Array(64),H=new Uint8Array(64);function B(D,P,G){var J=k.quantizationTable,K,F,ee,ge,ve,le,xe,Ee,ce,ue=G,st;for(st=0;st<64;st++)ue[st]=D[st]*J[st];for(st=0;st<8;++st){var He=8*st;if(ue[1+He]==0&&ue[2+He]==0&&ue[3+He]==0&&ue[4+He]==0&&ue[5+He]==0&&ue[6+He]==0&&ue[7+He]==0){ce=c*ue[0+He]+512>>10,ue[0+He]=ce,ue[1+He]=ce,ue[2+He]=ce,ue[3+He]=ce,ue[4+He]=ce,ue[5+He]=ce,ue[6+He]=ce,ue[7+He]=ce;continue}K=c*ue[0+He]+128>>8,F=c*ue[4+He]+128>>8,ee=ue[2+He],ge=ue[6+He],ve=u*(ue[1+He]-ue[7+He])+128>>8,Ee=u*(ue[1+He]+ue[7+He])+128>>8,le=ue[3+He]<<4,xe=ue[5+He]<<4,ce=K-F+1>>1,K=K+F+1>>1,F=ce,ce=ee*l+ge*a+128>>8,ee=ee*a-ge*l+128>>8,ge=ce,ce=ve-xe+1>>1,ve=ve+xe+1>>1,xe=ce,ce=Ee+le+1>>1,le=Ee-le+1>>1,Ee=ce,ce=K-ge+1>>1,K=K+ge+1>>1,ge=ce,ce=F-ee+1>>1,F=F+ee+1>>1,ee=ce,ce=ve*s+Ee*i+2048>>12,ve=ve*i-Ee*s+2048>>12,Ee=ce,ce=le*r+xe*n+2048>>12,le=le*n-xe*r+2048>>12,xe=ce,ue[0+He]=K+Ee,ue[7+He]=K-Ee,ue[1+He]=F+xe,ue[6+He]=F-xe,ue[2+He]=ee+le,ue[5+He]=ee-le,ue[3+He]=ge+ve,ue[4+He]=ge-ve}for(st=0;st<8;++st){var rt=st;if(ue[8+rt]==0&&ue[16+rt]==0&&ue[24+rt]==0&&ue[32+rt]==0&&ue[40+rt]==0&&ue[48+rt]==0&&ue[56+rt]==0){ce=c*G[st+0]+8192>>14,ue[0+rt]=ce,ue[8+rt]=ce,ue[16+rt]=ce,ue[24+rt]=ce,ue[32+rt]=ce,ue[40+rt]=ce,ue[48+rt]=ce,ue[56+rt]=ce;continue}K=c*ue[0+rt]+2048>>12,F=c*ue[32+rt]+2048>>12,ee=ue[16+rt],ge=ue[48+rt],ve=u*(ue[8+rt]-ue[56+rt])+2048>>12,Ee=u*(ue[8+rt]+ue[56+rt])+2048>>12,le=ue[24+rt],xe=ue[40+rt],ce=K-F+1>>1,K=K+F+1>>1,F=ce,ce=ee*l+ge*a+2048>>12,ee=ee*a-ge*l+2048>>12,ge=ce,ce=ve-xe+1>>1,ve=ve+xe+1>>1,xe=ce,ce=Ee+le+1>>1,le=Ee-le+1>>1,Ee=ce,ce=K-ge+1>>1,K=K+ge+1>>1,ge=ce,ce=F-ee+1>>1,F=F+ee+1>>1,ee=ce,ce=ve*s+Ee*i+2048>>12,ve=ve*i-Ee*s+2048>>12,Ee=ce,ce=le*r+xe*n+2048>>12,le=le*n-xe*r+2048>>12,xe=ce,ue[0+rt]=K+Ee,ue[56+rt]=K-Ee,ue[8+rt]=F+xe,ue[48+rt]=F-xe,ue[16+rt]=ee+le,ue[40+rt]=ee-le,ue[24+rt]=ge+ve,ue[32+rt]=ge-ve}for(st=0;st<64;++st){var Ie=128+(ue[st]+8>>4);P[st]=Ie<0?0:Ie>255?255:Ie}}o(B,"quantizeAndInverse"),b(R*T*8);for(var $,V,X=0;X<T;X++){var I=X<<3;for($=0;$<8;$++)x.push(new Uint8Array(R));for(var z=0;z<E;z++){B(k.blocks[X][z],H,U);var A=0,C=z<<3;for(V=0;V<8;V++){var N=x[I+V];for($=0;$<8;$++)N[C+$]=H[A++]}}}return x}o(h,"buildComponentData");function g(S){return S<0?0:S>255?255:S}o(g,"clampTo8bit"),d.prototype={load:o(function(k){var x=new XMLHttpRequest;x.open("GET",k,!0),x.responseType="arraybuffer",x.onload=(function(){var E=new Uint8Array(x.response||x.mozResponseArrayBuffer);this.parse(E),this.onload&&this.onload()}).bind(this),x.send(null)},"load"),parse:o(function(k){var x=this.opts.maxResolutionInMP*1e3*1e3,E=0,T=k.length;function R(){var oe=k[E]<<8|k[E+1];return E+=2,oe}o(R,"readUint16");function U(){var oe=R(),$e=k.subarray(E,E+oe-2);return E+=$e.length,$e}o(U,"readDataBlock");function H(oe){var $e=1,Ve=1,at,Rt;for(Rt in oe.components)oe.components.hasOwnProperty(Rt)&&(at=oe.components[Rt],$e<at.h&&($e=at.h),Ve<at.v&&(Ve=at.v));var Ye=Math.ceil(oe.samplesPerLine/8/$e),sn=Math.ceil(oe.scanLines/8/Ve);for(Rt in oe.components)if(oe.components.hasOwnProperty(Rt)){at=oe.components[Rt];var Qt=Math.ceil(Math.ceil(oe.samplesPerLine/8)*at.h/$e),vn=Math.ceil(Math.ceil(oe.scanLines/8)*at.v/Ve),Dt=Ye*at.h,Or=sn*at.v,Mr=Or*Dt,es=[];b(Mr*256);for(var Ei=0;Ei<Or;Ei++){for(var ur=[],ts=0;ts<Dt;ts++)ur.push(new Int32Array(64));es.push(ur)}at.blocksPerLine=Qt,at.blocksPerColumn=vn,at.blocks=es}oe.maxH=$e,oe.maxV=Ve,oe.mcusPerLine=Ye,oe.mcusPerColumn=sn}o(H,"prepareComponents");var B=null,$=null,V=null,X,I,z=[],A=[],C=[],N=[],D=R(),P=-1;if(this.comments=[],D!=65496)throw new Error("SOI not found");for(D=R();D!=65497;){var G,J,K;switch(D){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 F=U();if(D===65534){var ee=String.fromCharCode.apply(null,F);this.comments.push(ee)}D===65504&&F[0]===74&&F[1]===70&&F[2]===73&&F[3]===70&&F[4]===0&&(B={version:{major:F[5],minor:F[6]},densityUnits:F[7],xDensity:F[8]<<8|F[9],yDensity:F[10]<<8|F[11],thumbWidth:F[12],thumbHeight:F[13],thumbData:F.subarray(14,14+3*F[12]*F[13])}),D===65505&&F[0]===69&&F[1]===120&&F[2]===105&&F[3]===102&&F[4]===0&&(this.exifBuffer=F.subarray(5,F.length)),D===65518&&F[0]===65&&F[1]===100&&F[2]===111&&F[3]===98&&F[4]===101&&F[5]===0&&($={version:F[6],flags0:F[7]<<8|F[8],flags1:F[9]<<8|F[10],transformCode:F[11]});break;case 65499:for(var ge=R(),ve=ge+E-2;E<ve;){var le=k[E++];b(256);var xe=new Int32Array(64);if(le>>4===0)for(J=0;J<64;J++){var Ee=t[J];xe[Ee]=k[E++]}else if(le>>4===1)for(J=0;J<64;J++){var Ee=t[J];xe[Ee]=R()}else throw new Error("DQT: invalid table spec");z[le&15]=xe}break;case 65472:case 65473:case 65474:R(),X={},X.extended=D===65473,X.progressive=D===65474,X.precision=k[E++],X.scanLines=R(),X.samplesPerLine=R(),X.components={},X.componentsOrder=[];var ce=X.scanLines*X.samplesPerLine;if(ce>x){var ue=Math.ceil((ce-x)/1e6);throw new Error(`maxResolutionInMP limit exceeded by ${ue}MP`)}var st=k[E++],He,rt=0,Ie=0;for(G=0;G<st;G++){He=k[E];var Se=k[E+1]>>4,ie=k[E+1]&15,Me=k[E+2];if(Se<=0||ie<=0)throw new Error("Invalid sampling factor, expected values above 0");X.componentsOrder.push(He),X.components[He]={h:Se,v:ie,quantizationIdx:Me},E+=3}H(X),A.push(X);break;case 65476:var ke=R();for(G=2;G<ke;){var lt=k[E++],Be=new Uint8Array(16),Le=0;for(J=0;J<16;J++,E++)Le+=Be[J]=k[E];b(16+Le);var yt=new Uint8Array(Le);for(J=0;J<Le;J++,E++)yt[J]=k[E];G+=17+Le,(lt>>4===0?N:C)[lt&15]=p(Be,yt)}break;case 65501:R(),I=R();break;case 65500:R(),R();break;case 65498:var it=R(),Ge=k[E++],mt=[],Re;for(G=0;G<Ge;G++){Re=X.components[k[E++]];var kt=k[E++];Re.huffmanTableDC=N[kt>>4],Re.huffmanTableAC=C[kt&15],mt.push(Re)}var zt=k[E++],pt=k[E++],yn=k[E++],Bt=m(k,E,X,mt,I,zt,pt,yn>>4,yn&15,this.opts);E+=Bt;break;case 65535:k[E]!==255&&E--;break;default:if(k[E-3]==255&&k[E-2]>=192&&k[E-2]<=254){E-=3;break}else if(D===224||D==225){if(P!==-1)throw new Error(`first unknown JPEG marker at offset ${P.toString(16)}, second unknown JPEG marker ${D.toString(16)} at offset ${(E-1).toString(16)}`);P=E-1;let oe=R();if(k[E+oe-2]===255){E+=oe-2;break}}throw new Error("unknown JPEG marker "+D.toString(16))}D=R()}if(A.length!=1)throw new Error("only single frame JPEGs supported");for(var G=0;G<A.length;G++){var jt=A[G].components;for(var J in jt)jt[J].quantizationTable=z[jt[J].quantizationIdx],delete jt[J].quantizationIdx}this.width=X.samplesPerLine,this.height=X.scanLines,this.jfif=B,this.adobe=$,this.components=[];for(var G=0;G<X.componentsOrder.length;G++){var Re=X.components[X.componentsOrder[G]];this.components.push({lines:h(X,Re),scaleX:Re.h/X.maxH,scaleY:Re.v/X.maxV})}},"parse"),getData:o(function(k,x){var E=this.width/k,T=this.height/x,R,U,H,B,$,V,X,I,z,A,C=0,N,D,P,G,J,K,F,ee,ge,ve,le,xe=k*x*this.components.length;b(xe);var Ee=new Uint8Array(xe);switch(this.components.length){case 1:for(R=this.components[0],A=0;A<x;A++)for($=R.lines[0|A*R.scaleY*T],z=0;z<k;z++)N=$[0|z*R.scaleX*E],Ee[C++]=N;break;case 2:for(R=this.components[0],U=this.components[1],A=0;A<x;A++)for($=R.lines[0|A*R.scaleY*T],V=U.lines[0|A*U.scaleY*T],z=0;z<k;z++)N=$[0|z*R.scaleX*E],Ee[C++]=N,N=V[0|z*U.scaleX*E],Ee[C++]=N;break;case 3:for(le=!0,this.adobe&&this.adobe.transformCode?le=!0:typeof this.opts.colorTransform<"u"&&(le=!!this.opts.colorTransform),R=this.components[0],U=this.components[1],H=this.components[2],A=0;A<x;A++)for($=R.lines[0|A*R.scaleY*T],V=U.lines[0|A*U.scaleY*T],X=H.lines[0|A*H.scaleY*T],z=0;z<k;z++)le?(N=$[0|z*R.scaleX*E],D=V[0|z*U.scaleX*E],P=X[0|z*H.scaleX*E],ee=g(N+1.402*(P-128)),ge=g(N-.3441363*(D-128)-.71413636*(P-128)),ve=g(N+1.772*(D-128))):(ee=$[0|z*R.scaleX*E],ge=V[0|z*U.scaleX*E],ve=X[0|z*H.scaleX*E]),Ee[C++]=ee,Ee[C++]=ge,Ee[C++]=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),R=this.components[0],U=this.components[1],H=this.components[2],B=this.components[3],A=0;A<x;A++)for($=R.lines[0|A*R.scaleY*T],V=U.lines[0|A*U.scaleY*T],X=H.lines[0|A*H.scaleY*T],I=B.lines[0|A*B.scaleY*T],z=0;z<k;z++)le?(N=$[0|z*R.scaleX*E],D=V[0|z*U.scaleX*E],P=X[0|z*H.scaleX*E],G=I[0|z*B.scaleX*E],J=255-g(N+1.402*(P-128)),K=255-g(N-.3441363*(D-128)-.71413636*(P-128)),F=255-g(N+1.772*(D-128))):(J=$[0|z*R.scaleX*E],K=V[0|z*U.scaleX*E],F=X[0|z*H.scaleX*E],G=I[0|z*B.scaleX*E]),Ee[C++]=255-J,Ee[C++]=255-K,Ee[C++]=255-F,Ee[C++]=255-G;break;default:throw new Error("Unsupported color mode")}return Ee},"getData"),copyToImageData:o(function(k,x){var E=k.width,T=k.height,R=k.data,U=this.getData(E,T),H=0,B=0,$,V,X,I,z,A,C,N,D;switch(this.components.length){case 1:for(V=0;V<T;V++)for($=0;$<E;$++)X=U[H++],R[B++]=X,R[B++]=X,R[B++]=X,x&&(R[B++]=255);break;case 3:for(V=0;V<T;V++)for($=0;$<E;$++)C=U[H++],N=U[H++],D=U[H++],R[B++]=C,R[B++]=N,R[B++]=D,x&&(R[B++]=255);break;case 4:for(V=0;V<T;V++)for($=0;$<E;$++)z=U[H++],A=U[H++],X=U[H++],I=U[H++],C=255-g(z*(1-I/255)+I),N=255-g(A*(1-I/255)+I),D=255-g(X*(1-I/255)+I),R[B++]=C,R[B++]=N,R[B++]=D,x&&(R[B++]=255);break;default:throw new Error("Unsupported color mode")}},"copyToImageData")};var y=0,v=0;function b(S=0){var k=y+S;if(k>v){var x=Math.ceil((k-v)/1024/1024);throw new Error(`maxMemoryUsageInMB limit exceeded by at least ${x}MB`)}y=k}return o(b,"requestMemoryAllocation"),d.resetMaxMemoryUsage=function(S){y=0,v=S},d.getBytesAllocated=function(){return y},d.requestMemoryAllocation=b,d}),"jpegImage")();typeof TK<"u"?TK.exports=ESe:typeof window<"u"&&(window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=ESe);function ESe(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 _K;s.opts=r,_K.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),s.parse(i);var a=r.formatAsRGBA?4:3,l=s.width*s.height*a;try{_K.requestMemoryAllocation(l);var c={width:s.width,height:s.height,exifBuffer:s.exifBuffer,data:r.useTArray?new Uint8Array(l):Buffer.alloc(l)};s.comments.length>0&&(c.comments=s.comments)}catch(u){throw u instanceof RangeError?new Error("Could not allocate enough memory for the image. Required: "+l):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(c,r.formatAsRGBA),c}o(ESe,"decode")});var ASe=we((M9n,TSe)=>{var Wwt=kSe(),Hwt=_Se();TSe.exports={encode:Wwt,decode:Hwt}});function l4e(e,t){let n=0,r=0,s=o(a=>{let l;for(let[c,u]of a.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&&(l??=a.slice(0,c)),l?.push(d)}return l??a},"visit")(e.content);if(r!==t.length)throw new Error(`image/offload: image index ${t[r]} does not exist`);return fn({...e,content:s})}var c4e=se(()=>{Pi();o(l4e,"offloadMessageImages")});function u4e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function d4e(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0&&!Object.is(e,-0)}var fI,EJ=se(()=>{c4e();o(u4e,"isRecord");o(d4e,"isIndex");fI={type:"image/offload",project(e,t){let n=e.data;if(!u4e(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(!u4e(s)||Object.keys(s).length!==2||!d4e(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 a=s.seq;if(r.has(a))throw new Error(`image/offload: duplicate target seq ${a}`);if(!i.has(a))throw new Error(`image/offload: target seq ${a} is not a current surface node`);let l=t.events[a-t.baseSeq];if(l?.type!=="user/message"&&l?.type!=="tool/result")throw new Error(`image/offload: target seq ${a} must be user/message or tool/result`);let c=-1;for(let d of s.imageIndexes){if(!d4e(d)||d<=c)throw new Error("image/offload: imageIndexes must be strictly increasing non-negative safe integers");c=d}let u=t.messages.get(a)??(l.type==="user/message"?l.data:l.data.message);r.set(a,l4e(u,s.imageIndexes))}return r}}});var II,REe=se(()=>{EJ();II=[fI]});async function LEe(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(l){try{await i.close()}catch{}throw l}await i.close();let{events:a}=s;return{eventState:s.eventState,header:i.header,inheritedEventCount:i.inheritedEventCount,events:[...a,...T5(a)]}}function aY(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 Cr(`session source headers conflict for session "${e.id}"`,"SESSION_QUERY_SOURCE_CONFLICT")}function CI(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 oY(e){return{header:e.header,events:e.snapshotEvents()}}function RI(e,t){return e.map(n=>t.get(n))}async function lY(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 Cr(`session persistence listing failed: ${dY(n)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:n})}}async function OEe(e,t,n){try{return await LEe(e,t,n)}catch(r){throw n?.aborted&&n.throwIfAborted(),r instanceof Error&&r.name==="SessionPersistenceCorruptionError"?new Cr(`stored session "${t}" is corrupt: ${dY(r)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:r}):new Cr(`failed to read stored session "${t}": ${dY(r)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:r})}}function NEe(e){return{header:structuredClone(e.header),inheritedEventCount:e.inheritedEventCount,events:e.snapshotEvents().map(t=>structuredClone(t))}}function Xkt(e,t){return t.header.createdAt-e.header.createdAt||e.header.id.localeCompare(t.header.id)}function OI(e){return new Cr(`session "${e}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND")}function dY(e){return e instanceof Error?e.message:"unknown error"}function Kk(e){if(e?.aborted===!0)throw new Cr("session observation was aborted","SESSION_QUERY_ABORTED",{cause:e.reason})}function $Ee(e,t){return PEe(t,"SessionPersistenceNotFoundError")?pY(e,t):PEe(t,"SessionPersistenceCorruptionError")?new Cr(`stored session "${e}" is corrupt: ${t.message}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:t}):new Cr(`failed to observe session "${e}": ${NI(t)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:t})}function pY(e,t){return new Cr(`session "${e}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND",t===void 0?void 0:{cause:t})}function NI(e){return e instanceof Error?e.message:"unknown error"}function PEe(e,t){return e instanceof Error&&e.name===t}function e4t(e){switch(e.type){case"user/message":return cY(e.data.content);case"assistant/message":return cY(e.data.message.content);case"tool/call":return Jk([e.data.name,e.data.arguments]);case"tool/result":return Jk([cY(e.data.message.content),e.data.error?.name??"",e.data.error?.code??""]);case"todo/write":return Jk(e.data.todos.flatMap(t=>[t.status,t.content]));case"turn/end":return t4t(e.data.reason);case"turn/start":case"step/start":case"step/end":case"assistant/attempt":case"request/header":return"";default:return""}}function t4t(e){switch(e.kind){case"error":return Jk(["error",e.error.message]);case"aborted":return"aborted";case"max-tokens":case"interrupted":return e.kind;case"completed":return"";default:return""}}function cY(e){return Jk(e.flatMap(n4t))}function n4t(e){switch(e.type){case"text":return[e.text];case"reasoning":return[];case"tool-call":return[e.name,e.arguments];default:return[]}}function Jk(e){return e.map(t=>t.trim()).filter(Boolean).join(`
157
157
  `)}function hY(e,t){let n=r4t(t),r=[];for(let i of t){let s=e4t(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 r4t(e){let t;try{t=zD(e,II)}catch(r){throw new Cr(`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 mY(e,t=[]){let n=t.map(s4t);return e.filter(r=>n.every(i=>i(r)))}function MI(e,t=[]){let n=t.map(a4t);return e.filter(r=>n.every(i=>i(r)))}function gY(e){return jEe(e),e.map(t=>{switch(t.kind){case"id":return{kind:t.kind,values:PI(t.kind,t.values)};case"cwd":return{kind:t.kind,values:DEe(t.kind,t.values)};case"created-at":return FEe(t.kind,t);case"parent":return{kind:t.kind,values:DEe(t.kind,t.values)};case"availability":{let n=PI(t.kind,t.values);return FI(t.kind,n,["live","persisted"]),{kind:t.kind,values:n}}default:return jI(t)}})}function LI(e){return jEe(e),e.map(t=>{switch(t.kind){case"seq":case"time":return FEe(t.kind,t);case"type":return{kind:t.kind,values:PI(t.kind,t.values)};case"surface":{let n=PI(t.kind,t.values);return FI(t.kind,n,["current","shadowed","log-only"]),{kind:t.kind,values:n}}case"text":if(typeof t.text!="string")throw Tv("text filter text must be a string");return{kind:t.kind,text:t.text};default:return jI(t)}})}function i4t(e){let t=e.trim();if(t.length===0)throw new Cr("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 s4t(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=DI(e.kind,e);return n=>fY(n.header.createdAt,t)}case"parent":return t=>e.values.includes(t.header.parentSession??null);case"availability":return FI(e.kind,e.values,["live","persisted"]),t=>e.values.some(n=>n==="live"?t.live:t.persisted);default:return jI(e)}}function a4t(e){switch(e.kind){case"seq":{let t=DI(e.kind,e);return n=>fY(n.seq,t)}case"time":{let t=DI(e.kind,e);return n=>fY(n.time,t)}case"type":return t=>e.values.includes(t.type);case"surface":return FI(e.kind,e.values,["current","shadowed","log-only"]),t=>e.values.includes(t.surface);case"text":{let t=i4t(e.text);return n=>t.test(n.text)}default:return jI(e)}}function PI(e,t){if(!UEe(t)||t.some(n=>typeof n!="string"))throw Tv(`${e} filter values must be an array of strings`);return[...t]}function jEe(e){if(!Array.isArray(e))throw Tv("filters must be an array")}function DEe(e,t){if(!UEe(t)||t.some(n=>n!==null&&typeof n!="string"))throw Tv(`${e} filter values must be an array of strings or null`);return[...t]}function FEe(e,t){let n={kind:e,...t.from===void 0?{}:{from:t.from},...t.to===void 0?{}:{to:t.to}};return DI(e,n),n}function jI(e){let t=e.kind;throw Tv(`unknown filter kind ${typeof t=="string"?`"${t}"`:"(missing)"}`)}function FI(e,t,n){for(let r of t)if(!n.includes(r))throw new Cr(`session ${e} filter contains unknown value "${r}"`,"SESSION_QUERY_INVALID_FILTER")}function DI(e,t){if(t.from!==void 0&&!Number.isFinite(t.from))throw uY(e,"from must be finite");if(t.to!==void 0&&!Number.isFinite(t.to))throw uY(e,"to must be finite");if(t.from!==void 0&&t.to!==void 0&&t.from>t.to)throw uY(e,"from must be less than or equal to to");return t}function fY(e,t){return(t.from===void 0||e>=t.from)&&(t.to===void 0||e<=t.to)}function uY(e,t){return Tv(`${e} filter ${t}`)}function Tv(e){return new Cr(`session ${e}`,"SESSION_QUERY_INVALID_FILTER")}function UEe(e){return Array.isArray(e)}function o4t(e,t){return yY(e,t).records}function l4t(e,t){return yY(e,t).currentSeqs.map(n=>{let r=t[n];if(r===void 0||r.seq!==n||!gm(r))throw new Cr(`invalid session surface: current node ${n} is not a surface event`,"SESSION_QUERY_INVALID_SURFACE");return dx(r)})}function c4t(e,t,n){let r=t[n];if(r===void 0||r.seq!==n)throw new Cr(`session "${e}" has no event at seq ${n}`,"SESSION_QUERY_EVENT_NOT_FOUND");let i=yY(e,t),s=[],a=i.replacedBy.get(n);for(;a!==void 0;)s.push(a),a=i.replacedBy.get(a);let l=[];for(let d of t)d.seq<=n||MEe(d).includes(n)&&l.push(d.seq);let c=i.records[n],u=i.replacedBy.get(n);return{target:c,...u===void 0?{}:{replacedBy:u},replacementChain:s,replacedEventSeqs:i.replacedEventSeqs.get(n)??[],sourceEventSeqs:[...MEe(r)],derivedEventSeqs:l}}function u4t(e,t){let n=new Map(e.map(p=>[p.header.id,p])),r=n.get(t);if(r===void 0)throw new Cr(`session "${t}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND");let i=[],s=new Set([t]),a,l=r.header.parentSession;for(;l!==void 0;){if(s.has(l))throw new Cr(`session lineage contains a cycle at "${l}"`,"SESSION_QUERY_INVALID_LINEAGE");s.add(l);let p=n.get(l);if(p===void 0){a=l;break}i.push(p),l=p.header.parentSession}let c=new Map;for(let p of e){let m=p.header.parentSession;if(m===void 0)continue;let h=c.get(m)??[];h.push(p),c.set(m,h)}for(let p of c.values())p.sort((m,h)=>m.header.createdAt-h.header.createdAt||m.header.id.localeCompare(h.header.id));let u=d4t(c,t),d={target:$I(r),ancestors:i.map($I),descendants:u};return a!==void 0?{...d,complete:!1,unresolvedParentId:a}:{...d,complete:!0,root:$I(i.at(-1)??r)}}function yY(e,t){let n;try{n=zD(t,II)}catch(a){throw new Cr(`invalid session surface: ${a instanceof Error?a.message:"unknown error"}`,"SESSION_QUERY_INVALID_SURFACE",{cause:a})}let r=new Set(n.nodes),i=new Map,s=new Map;for(let a of n.replacements){let l=a.shadowedSeqs;s.set(a.seq,l);for(let c of l)i.set(c,a.seq)}return{records:t.map(a=>({sessionId:e,seq:a.seq,type:a.type,time:a.time,surface:r.has(a.seq)?"current":i.has(a.seq)?"shadowed":"log-only"})),replacedBy:i,replacedEventSeqs:s,currentSeqs:[...n.nodes]}}function MEe(e){return e.sourceEventSeqs??[]}function d4t(e,t){let n=[],r=[{sessionId:t,descendants:n}];for(;r.length>0;){let i=r.pop(),s=[];for(let a of e.get(i.sessionId)??[]){let l={session:$I(a),descendants:[]};s.push(l),i.descendants.push(l)}for(let a=s.length-1;a>=0;a-=1){let l=s[a];r.push({sessionId:l.session.header.id,descendants:l.descendants})}}return n}function $I(e){return{...e,header:structuredClone(e.header)}}var Cr,Ykt,Qkt,qEe,vY=se(()=>{REe();zn();ys();Mm();dr();Cr=class extends jr{static{o(this,"SessionQueryError")}constructor(e,t,n){super(e,t,n)}};o(LEe,"readColdSessionLog");o(aY,"assertSessionHeadersCompatible");Ykt=class{static{o(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 lY(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&&aY(i.header,s.header),r.set(i.id,{header:structuredClone(i.header),live:!0,persisted:s!==void 0})}return[...r.values()].sort(Xkt)}async load(e,t){t?.throwIfAborted();let n=this._ctx.sessions.get(e);if(n!==void 0){let c=NEe(n);return t?.throwIfAborted(),c}let r=this._persistence;if(r===void 0)throw OI(e);let i=(await lY(r,t)).find(c=>c.id===e);if(t?.throwIfAborted(),i===void 0)throw OI(e);let s=await OEe(r,e,t);t?.throwIfAborted();let a=this._ctx.sessions.get(e);if(a!==void 0){let c=NEe(a);return t?.throwIfAborted(),c}aY(s.header,i);let l={header:structuredClone(s.header),inheritedEventCount:s.inheritedEventCount,events:s.events.map(c=>structuredClone(c))};return t?.throwIfAborted(),l}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,CI(g,oY(y),t,n))}if(s.length===0)return RI(r,i);let a=this._persistence;if(a===void 0){for(let g of s)i.set(g,{sessionId:g,status:"rejected",reason:OI(g)});return RI(r,i)}let l;try{l=await lY(a,n),n?.throwIfAborted()}catch(g){n?.aborted&&n.throwIfAborted();for(let y of s)i.set(y,{sessionId:y,status:"rejected",reason:g});return RI(r,i)}let c=new Map(l.map(g=>[g.id,g])),u=o(async g=>{let y=c.get(g);if(y===void 0){let v=this._ctx.sessions.get(g);i.set(g,v===void 0?{sessionId:g,status:"rejected",reason:OI(g)}:CI(g,oY(v),t,n));return}try{n?.throwIfAborted();let v=await OEe(a,g,n);n?.throwIfAborted();let b=this._ctx.sessions.get(g);if(b!==void 0){i.set(g,CI(g,oY(b),t,n));return}aY(v.header,y),i.set(g,CI(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=o(async()=>{for(;;){n?.throwIfAborted();let g=d;if(g>=s.length)return;d+=1,await u(s[g])}},"worker"),m=Math.min(this._persistedReadConcurrency,s.length),h=await Promise.allSettled(Array.from({length:m},()=>p()));n?.aborted&&n.throwIfAborted();for(let g of h)if(g.status==="rejected")throw g.reason;return n?.throwIfAborted(),RI(r,i)}};o(CI,"projectSource");o(oY,"sourceLive");o(RI,"orderedResults");o(lY,"listPersisted");o(OEe,"inspectPersisted");o(NEe,"snapshotLive");o(Xkt,"compareSessions");o(OI,"notFound$1");o(dY,"errorMessage$1");Qkt=class{static{o(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(;;){Kk(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 pY(e);let a=await this.statSource(s,e,n),l=this.ctx.sessions.get(e);if(l!==void 0)return this.live(l,r);let c=this.cachedEntry(s.identity,e,a.revision);if(c===void 0){let d=await this.loadSource(s,e,n);Kk(n);let p=this.ctx.sessions.get(e);if(p!==void 0)return this.live(p,r);let m=d.events,h;try{h=this.ctx.sessions.prepare(e,{seed:m,meta:structuredClone(d.header),inheritedEventCount:d.inheritedEventCount,eventState:d.eventState})}catch(g){if(this.ctx.sessions.get(e)!==void 0)continue;throw new Cr(`stored session "${e}" is corrupt: ${NI(g)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:g})}c={persistenceIdentity:s.identity,revision:a.revision,session:h,events:Object.freeze(m),refs:0},this.store(e,c)}let u;try{u=r==="none"?void 0:this.preparedProjections(c)}catch(d){throw new Cr(`failed to project session "${e}": ${NI(d)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:d})}return this.preparedLease(e,c,u)}}async statSource(e,t,n){let r;try{r=await e.stat(t,n===void 0?void 0:{signal:n})}catch(i){throw Kk(n),$Ee(t,i)}if(Kk(n),r===void 0)throw pY(t);if(r.header.id!==t)throw new Cr(`session persistence returned "${r.header.id}" for "${t}"`,"SESSION_QUERY_SOURCE_CONFLICT");return r}async loadSource(e,t,n){try{return await LEe(e,t,n)}catch(r){throw Kk(n),$Ee(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=o(()=>{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:o(()=>{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(a){throw new Cr(`failed to project session "${e.id}": ${NI(a)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:a})}let s=o(()=>{let a=!1;return{source:"live",header:e.header,inheritedEventCount:e.inheritedEventCount,get events(){return r??=e.snapshotEvents(_n(0),n),r},cursor:n===0?-1:an(n-1),...i===void 0?{}:{projections:i},retain:o(()=>{if(a)throw new Error(`session observation "${e.id}" is disposed`);return s()},"retain"),[Symbol.dispose]:()=>{a=!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,_n(0)):n.hydratePrepared(e.session,e.events)}};o(Kk,"throwIfObservationAborted");o($Ee,"mapPersistenceFailure");o(pY,"notFound");o(NI,"errorMessage");o(PEe,"hasErrorName");o(e4t,"extractSessionEventText");o(t4t,"turnEndText");o(cY,"contentText");o(n4t,"blockText");o(Jk,"joinText");o(hY,"buildSessionEventSearchDocuments");o(r4t,"classifySurface");o(mY,"filterSessionResults");o(MI,"filterSessionEventDocuments");o(gY,"materializeSessionResultFilters");o(LI,"materializeSessionEventResultFilters");o(i4t,"compileSessionTextFilter");o(s4t,"sessionPredicate");o(a4t,"eventPredicate");o(PI,"copyStrings");o(jEe,"assertArray");o(DEe,"copyNullableStrings");o(FEe,"copyRange");o(jI,"unknownFilter");o(FI,"assertAllowedValues");o(DI,"validateRange");o(fY,"matchesRange");o(uY,"invalidRange");o(Tv,"invalidFilter");o(UEe,"isRuntimeArray");o(o4t,"eventRecords");o(l4t,"currentSurfaceEvents");o(c4t,"traceEvent");o(u4t,"traceSession");o(yY,"analyzeEventLog");o(MEe,"eventSources");o(d4t,"buildDescendants");o($I,"cloneRecord");qEe=class extends St{static{o(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 Cr("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 Cr("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 Cr("session-query: preparedSessionCacheSize must be a positive safe integer","SESSION_QUERY_INVALID_CONFIG");this._corpus=new Ykt(e,n),this._observations=new Qkt(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 Ig.create(e,t.events,t.header,t.inheritedEventCount,II),{session:structuredClone(t.header),inheritedEventCount:t.inheritedEventCount,events:t.events.map(dx)}}async filterSessions(e,t){let n=gY(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=Dm(n.events);return{session:structuredClone(n.header),...r===void 0?{}:{title:r}}},t)}async listEvents(e){return o4t(e,(await this._corpus.load(e)).events)}async filterEvents(e,t){let n=LI(t);return this._filterEvents(e,n)}async _filterSessions(e,t){return mY(await this._corpus.listSessions(t),e)}async _filterEvents(e,t){return MI(hY(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:l4t(e,t.events)}}async traceSession(e,t){let n=await this._corpus.listSessions(t);return t?.throwIfAborted(),u4t(n,e)}async traceEvent(e,t){let n=await this._corpus.load(e.sessionId,t);return t?.throwIfAborted(),{session:n.header,...c4t(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 a=s.events[t];if(a===void 0||a.seq!==t)throw new Cr(`session "${e}" has no event at seq ${t}`,"SESSION_QUERY_EVENT_NOT_FOUND");let l=an(Math.max(0,t-n)),c=an(Math.min(s.events.length-1,t+r)),u=dx(a),d=s.events.slice(l,c+1).map(p=>p===a?u:dx(p));return{session:structuredClone(s.header),inheritedEventCount:s.inheritedEventCount,target:u,events:d,startSeq:l,endSeq:c}}_readWindow(e,t){if(t===void 0)return 0;if(!Number.isInteger(t)||t<0||t>this._readWindowMax)throw new Cr(`${e} must be an integer between 0 and ${this._readWindowMax}`,"SESSION_QUERY_INVALID_WINDOW");return t}}});var Av=we((LOn,QEe)=>{"use strict";QEe.exports=j0;j0.CAPTURING_PHASE=1;j0.AT_TARGET=2;j0.BUBBLING_PHASE=3;function j0(e,t){if(this.type="",this.target=null,this.currentTarget=null,this.eventPhase=j0.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]}o(j0,"Event");j0.prototype=Object.create(Object.prototype,{constructor:{value:j0},stopPropagation:{value:o(function(){this._propagationStopped=!0},"stopPropagation")},stopImmediatePropagation:{value:o(function(){this._propagationStopped=!0,this._immediatePropagationStopped=!0},"stopImmediatePropagation")},preventDefault:{value:o(function(){this.cancelable&&(this.defaultPrevented=!0)},"preventDefault")},initEvent:{value:o(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 _Y=we((FOn,t_e)=>{"use strict";var e_e=Av();t_e.exports=EY;function EY(){e_e.call(this),this.view=null,this.detail=0}o(EY,"UIEvent");EY.prototype=Object.create(e_e.prototype,{constructor:{value:EY},initUIEvent:{value:o(function(e,t,n,r,i){this.initEvent(e,t,n),this.view=r,this.detail=i},"value")}})});var AY=we((qOn,r_e)=>{"use strict";var n_e=_Y();r_e.exports=TY;function TY(){n_e.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}o(TY,"MouseEvent");TY.prototype=Object.create(n_e.prototype,{constructor:{value:TY},initMouseEvent:{value:o(function(e,t,n,r,i,s,a,l,c,u,d,p,m,h,g){switch(this.initEvent(e,t,n,r,i),this.screenX=s,this.screenY=a,this.clientX=l,this.clientY=c,this.ctrlKey=u,this.altKey=d,this.shiftKey=p,this.metaKey=m,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:o(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 HI=we((zOn,s_e)=>{"use strict";s_e.exports=WI;var I4t=1,C4t=3,R4t=4,O4t=5,N4t=7,$4t=8,P4t=9,D4t=11,M4t=12,L4t=13,j4t=14,F4t=15,U4t=17,q4t=18,B4t=19,z4t=20,W4t=21,H4t=22,V4t=23,G4t=24,Z4t=25,K4t=[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"],J4t=[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."],i_e={INDEX_SIZE_ERR:I4t,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:C4t,WRONG_DOCUMENT_ERR:R4t,INVALID_CHARACTER_ERR:O4t,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:N4t,NOT_FOUND_ERR:$4t,NOT_SUPPORTED_ERR:P4t,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:D4t,SYNTAX_ERR:M4t,INVALID_MODIFICATION_ERR:L4t,NAMESPACE_ERR:j4t,INVALID_ACCESS_ERR:F4t,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:U4t,SECURITY_ERR:q4t,NETWORK_ERR:B4t,ABORT_ERR:z4t,URL_MISMATCH_ERR:W4t,QUOTA_EXCEEDED_ERR:H4t,TIMEOUT_ERR:V4t,INVALID_NODE_TYPE_ERR:G4t,DATA_CLONE_ERR:Z4t};function WI(e){Error.call(this),Error.captureStackTrace(this,this.constructor),this.code=e,this.message=J4t[e],this.name=K4t[e]}o(WI,"DOMException");WI.prototype.__proto__=Error.prototype;for(zI in i_e)IY={value:i_e[zI]},Object.defineProperty(WI,zI,IY),Object.defineProperty(WI.prototype,zI,IY);var IY,zI});var VI=we(a_e=>{a_e.isApiWritable=!globalThis.__domino_frozen__});var Js=we(Ri=>{"use strict";var Ks=HI(),pa=Ks,Y4t=VI().isApiWritable;Ri.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"};Ri.IndexSizeError=function(){throw new Ks(pa.INDEX_SIZE_ERR)};Ri.HierarchyRequestError=function(){throw new Ks(pa.HIERARCHY_REQUEST_ERR)};Ri.WrongDocumentError=function(){throw new Ks(pa.WRONG_DOCUMENT_ERR)};Ri.InvalidCharacterError=function(){throw new Ks(pa.INVALID_CHARACTER_ERR)};Ri.NoModificationAllowedError=function(){throw new Ks(pa.NO_MODIFICATION_ALLOWED_ERR)};Ri.NotFoundError=function(){throw new Ks(pa.NOT_FOUND_ERR)};Ri.NotSupportedError=function(){throw new Ks(pa.NOT_SUPPORTED_ERR)};Ri.InvalidStateError=function(){throw new Ks(pa.INVALID_STATE_ERR)};Ri.SyntaxError=function(){throw new Ks(pa.SYNTAX_ERR)};Ri.InvalidModificationError=function(){throw new Ks(pa.INVALID_MODIFICATION_ERR)};Ri.NamespaceError=function(){throw new Ks(pa.NAMESPACE_ERR)};Ri.InvalidAccessError=function(){throw new Ks(pa.INVALID_ACCESS_ERR)};Ri.TypeMismatchError=function(){throw new Ks(pa.TYPE_MISMATCH_ERR)};Ri.SecurityError=function(){throw new Ks(pa.SECURITY_ERR)};Ri.NetworkError=function(){throw new Ks(pa.NETWORK_ERR)};Ri.AbortError=function(){throw new Ks(pa.ABORT_ERR)};Ri.UrlMismatchError=function(){throw new Ks(pa.URL_MISMATCH_ERR)};Ri.QuotaExceededError=function(){throw new Ks(pa.QUOTA_EXCEEDED_ERR)};Ri.TimeoutError=function(){throw new Ks(pa.TIMEOUT_ERR)};Ri.InvalidNodeTypeError=function(){throw new Ks(pa.INVALID_NODE_TYPE_ERR)};Ri.DataCloneError=function(){throw new Ks(pa.DATA_CLONE_ERR)};Ri.nyi=function(){throw new Error("NotYetImplemented")};Ri.shouldOverride=function(){throw new Error("Abstract function; should be overriding in subclass.")};Ri.assert=function(e,t){if(!e)throw new Error("Assertion failed: "+(t||"")+`
158
158
  `+new Error().stack)};Ri.expose=function(e,t){for(var n in e)Object.defineProperty(t.prototype,n,{value:e[n],writable:Y4t})};Ri.merge=function(e,t){for(var n in t)e[n]=t[n]};Ri.documentOrder=function(e,t){return 3-(e.compareDocumentPosition(t)&6)};Ri.toASCIILowerCase=function(e){return e.replace(/[A-Z]+/g,function(t){return t.toLowerCase()})};Ri.toASCIIUpperCase=function(e){return e.replace(/[a-z]+/g,function(t){return t.toUpperCase()})}});var CY=we((GOn,l_e)=>{"use strict";var F0=Av(),X4t=AY(),Q4t=Js();l_e.exports=o_e;function o_e(){}o(o_e,"EventTarget");o_e.prototype={addEventListener:o(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,a=i.length;s<a;s++){var l=i[s];if(l.listener===n&&l.capture===r)return}var c={listener:n,capture:r};typeof n=="function"&&(c.f=n),i.push(c)}},"addEventListener"),removeEventListener:o(function(t,n,r){if(r===void 0&&(r=!1),this._listeners){var i=this._listeners[t];if(i)for(var s=0,a=i.length;s<a;s++){var l=i[s];if(l.listener===n&&l.capture===r){i.length===1?this._listeners[t]=void 0:i.splice(s,1);return}}}},"removeEventListener"),dispatchEvent:o(function(t){return this._dispatchEvent(t,!1)},"dispatchEvent"),_dispatchEvent:o(function(t,n){typeof n!="boolean"&&(n=!1);function r(u,d){var p=d.type,m=d.eventPhase;if(d.currentTarget=u,m!==F0.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 b=0,S=v.length;b<S;b++){if(d._immediatePropagationStopped)return;var k=v[b];if(!(m===F0.CAPTURING_PHASE&&!k.capture||m===F0.BUBBLING_PHASE&&k.capture))if(k.f)k.f.call(d.currentTarget,d);else{var x=k.listener.handleEvent;if(typeof x!="function")throw new TypeError("handleEvent property of event listener object is not a function.");x.call(k.listener,d)}}}}o(r,"invoke"),(!t._initialized||t._dispatching)&&Q4t.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=F0.CAPTURING_PHASE;for(var a=i.length-1;a>=0&&(r(i[a],t),!t._propagationStopped);a--);if(t._propagationStopped||(t.eventPhase=F0.AT_TARGET,r(this,t)),t.bubbles&&!t._propagationStopped){t.eventPhase=F0.BUBBLING_PHASE;for(var l=0,c=i.length;l<c&&(r(i[l],t),!t._propagationStopped);l++);}if(t._dispatching=!1,t.eventPhase=F0.AT_TARGET,t.currentTarget=null,n&&!t.defaultPrevented&&t instanceof X4t)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:o(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:o(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:o(function(t,n){this._handlers||(this._handlers=Object.create(null)),this._handlers[t]=n},"_setEventHandler"),_getEventHandler:o(function(t){return this._handlers&&this._handlers[t]||null},"_getEventHandler")}});var RY=we((KOn,c_e)=>{"use strict";var xh=Js(),Cu=c_e.exports={valid:o(function(e){return xh.assert(e,"list falsy"),xh.assert(e._previousSibling,"previous falsy"),xh.assert(e._nextSibling,"next falsy"),!0},"valid"),insertBefore:o(function(e,t){xh.assert(Cu.valid(e)&&Cu.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(Cu.valid(e)&&Cu.valid(t))},"insertBefore"),replace:o(function(e,t){xh.assert(Cu.valid(e)&&(t===null||Cu.valid(t))),t!==null&&Cu.insertBefore(t,e),Cu.remove(e),xh.assert(Cu.valid(e)&&(t===null||Cu.valid(t)))},"replace"),remove:o(function(e){xh.assert(Cu.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(Cu.valid(e))}},"remove")}});var OY=we((YOn,y_e)=>{"use strict";y_e.exports={serializeOne:aEt,\u0275escapeMatchingClosingTag:h_e,\u0275escapeClosingCommentTag:m_e,\u0275escapeProcessingInstructionContent:g_e};var f_e=Js(),U0=f_e.NAMESPACE,u_e={STYLE:!0,SCRIPT:!0,XMP:!0,IFRAME:!0,NOEMBED:!0,NOFRAMES:!0,PLAINTEXT:!0},eEt={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},tEt={},d_e=/[&<>\u00A0]/g,p_e=/[&"<>\u00A0]/g;function nEt(e){return d_e.test(e)?e.replace(d_e,t=>{switch(t){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case"\xA0":return"&nbsp;"}}):e}o(nEt,"escape");function rEt(e){return p_e.test(e)?e.replace(p_e,t=>{switch(t){case"<":return"&lt;";case">":return"&gt;";case"&":return"&amp;";case'"':return"&quot;";case"\xA0":return"&nbsp;"}}):e}o(rEt,"escapeAttr");function iEt(e){var t=e.namespaceURI;return t?t===U0.XML?"xml:"+e.localName:t===U0.XLINK?"xlink:"+e.localName:t===U0.XMLNS?e.localName==="xmlns"?"xmlns":"xmlns:"+e.localName:e.name:e.localName}o(iEt,"attrname");function h_e(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("")}o(h_e,"escapeMatchingClosingTag");var sEt=/--!?>/;function m_e(e){return sEt.test(e)?e.replace(/(--\!?)>/g,"$1&gt;"):e}o(m_e,"escapeClosingCommentTag");function g_e(e){return e.includes(">")?e.replaceAll(">","&gt;"):e}o(g_e,"escapeProcessingInstructionContent");function aEt(e,t){var n="";switch(e.nodeType){case 1:var r=e.namespaceURI,i=r===U0.HTML,s=i||r===U0.SVG||r===U0.MATHML?e.localName:e.tagName;n+="<"+s;for(var a=0,l=e._numattrs;a<l;a++){var c=e._attr(a);n+=" "+iEt(c),c.value!==void 0&&(n+='="'+rEt(c.value)+'"')}if(n+=">",!(i&&eEt[s])){var u=e.serialize();u_e[s.toUpperCase()]&&(u=h_e(u,s)),i&&tEt[s]&&u.charAt(0)===`
@@ -5928,7 +5928,7 @@ The web search request used endpoint ${JSON.stringify(e)}. Search endpoint confi
5928
5928
  .error { padding: .75rem; border-radius: .5rem; background: #461d2b; color: #ffd6df; }
5929
5929
  .hint { margin: 1.5rem 0 0; font-size: .875rem; }
5930
5930
  code { padding: .1rem .3rem; border-radius: .3rem; background: #0c1222; color: #edf2ff; }
5931
- `}o(g$e,"pageStyles");NS();var Kne="enabled",Jne=Object.freeze({id:"direct",capabilities:Object.freeze(["bash"]),plan:"free",shell:"just-bash-direct",probe:o(e=>e.LOADER===void 0?"available":"needs-binding","probe")}),cE=Object.freeze({id:"dynamic-worker",capabilities:Object.freeze(["bash","coding"]),plan:"paid",shell:"just-bash-isolated",probe:o(e=>e.LOADER===void 0?"needs-binding":"available","probe")}),Yne=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:o(e=>e.DSH_EDGE_CONTAINER_RUNTIME===Kne?"available":"needs-binding","probe")}),QHt=Object.freeze([Yne,cE,Jne]);function Xne(e,t=QHt){return t.filter(n=>n.probe(e)==="available")}o(Xne,"availableEdgeRuntimeProviders");function Qne(e){let t=o(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}}o(Qne,"resolveEdgeRuntimeSelection");function kO(e){let t=Xne(e),{bash:n,container:r}=Qne(t);return t.find(i=>i.id===(r??n)).shell}o(kO,"resolveEdgeRuntimeShell");function eVt(){return"dsh-edge@0.24.0-alpha.1/isolated"}o(eVt,"resolveEdgeDeploymentId");function cy(e){return{baseURL:tK(e.DEEPSEEK_BASE_URL),maxTokens:iK(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:A0(e.DEEPSEEK_MODEL),reasoningEffort:nK(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:w4(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:rK(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:U1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}o(cy,"resolveEdgeDeploymentConfig");function tVt(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}o(tVt,"edgeDeploymentApiKeyConfigured");function nVt(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)}o(nVt,"projectedEdgeBaseURL");function ere(e,t){return{shell:kO(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:eVt(),apiKeyConfigured:tVt(e),baseURL:nVt(e.DEEPSEEK_BASE_URL),maxTokens:iK(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:A0(e.DEEPSEEK_MODEL),reasoningEffort:nK(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:w4(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:rK(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:U1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}o(ere,"resolveEdgeDeploymentProfile");function EO(e){cy(e);let t=ere(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:v0,upstreamVersion:Pve,status:"ready"}}o(EO,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as Snn}from"node:async_hooks";import{RpcTarget as rVt}from"cloudflare:workers";function iVt(e){let{intervalMs:t,ping:n,onFailure:r}=e,i=!1,s=setInterval(()=>{i||n().catch(a=>{i||(i=!0,clearInterval(s),r(a instanceof Error?a:new Error(String(a))))})},t);return()=>{i||(i=!0,clearInterval(s))}}o(iVt,"startHeartbeat");async function sVt(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}`)}o(sVt,"probeComputerdHealth");var aVt="computer.internal",oVt="/health",tre="/api",lVt=8080,cVt=3e4,uVt=2e4,dVt=1,pVt=2e3,fVt=250,hVt=2e3;function mVt(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}o(mVt,"bearerMatches");var TO=class{static{o(this,"CloudflareContainerBackend")}type="cloudflare-container";id;#e;#t;#r;#n;#i;#s;#o;#l;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??aVt,containerPort:e.containerPort??lVt,connectTimeoutMs:e.connectTimeoutMs??cVt,heartbeatIntervalMs:e.heartbeatIntervalMs??uVt,restartAttempts:e.restartAttempts??dVt,healthProbeTimeoutMs:e.healthProbeTimeoutMs??pVt,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??fVt,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??hVt}}async connect(){if(this.#l)return this.#l;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 Qo(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 Qo(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 a=await this.#h(e),l=c$(a),c,u=new Promise(p=>{let m=!1,h=o(()=>{m||(m=!0,c?.(),p(),this.#l=void 0)},"onClose");a.addEventListener("close",h,{once:!0}),a.addEventListener("error",h,{once:!0}),l.onRpcBroken(h)});this.#e.heartbeatIntervalMs>0&&(c=iVt({intervalMs:this.#e.heartbeatIntervalMs,ping:o(()=>l.sync.watermarks(),"ping"),onFailure:o(()=>{try{a.close()}catch{}},"onFailure")}));let d={rpc:l,runtimeId:i,closed:u,close:o(async()=>{c?.();try{l[Symbol.dispose]?.()}catch{}try{a.close()}catch{}this.#l=void 0},"close")};return this.#l=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(Lw),a;try{a=new URL(s??"")}catch{return new Response("invalid egress URL",{status:400})}if(a.protocol!=="http:"&&a.protocol!=="https:")return new Response("invalid egress URL",{status:400});i.delete(n_),i.delete(Lw);let l=new Request(e,{headers:i});return this.#t.gateway.fetch(new Request(a,l))}if(new URL(e.url).pathname!==tre)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${tre} requires a websocket upgrade`,{status:400});if(!mVt(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.#o=t}),this.#i.catch(()=>{})}#a(){this.#i=void 0,this.#s=void 0,this.#o=void 0}async#p(e,t,n,r,i){let s=this.#e.restartAttempts+1,a=Math.max(0,n-Date.now()),l=Math.max(250,Math.floor(a/s)),c=0,u=0,d,p=i;for(;c<s;){c++;let m=Math.min(n,Date.now()+l);if(await this.#m(e,m).then(()=>!0,h=>(d=h,!1)))return p;if(c<s)try{({runtimeId:p}=await e.restart({env:t,enableInternet:this.#t.mode==="direct"})),u++}catch(h){throw this.#o?.(h),this.#a(),new Qo(this.#d("restart",{attempt:c,maxAttempts:s,restarts:u,lastError:h}),{cause:h})}}throw this.#o?.(new Error("computerd never became healthy")),this.#a(),new Qo(this.#d("health",{attempt:c,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 sVt(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 gVt(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=${y$e(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.#o?.(new Error("container is not enforcing RPC_CLIENT_SECRET")),this.#a(),new Qo(`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:oVt,api:tre,healthTimeoutMs:r})})}catch(s){throw this.#o?.(s),this.#a(),new Qo(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${y$e(s)}`,{cause:s})}if(!i.ok){let s=await i.text().catch(()=>""),a=new Error(`/connect ${i.status}`);throw this.#o?.(a),this.#a(),new Qo(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect returned ${i.status}: ${s}`,{cause:a})}}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 Qo(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#a()}}};function gVt(e){return new Promise(t=>setTimeout(t,e))}o(gVt,"sleep");function y$e(e){return e instanceof Error?e.message:String(e)}o(y$e,"describeError");var v$e="computer:container-client-secret",yVt=16;function vVt(){let e=crypto.getRandomValues(new Uint8Array(yVt));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}o(vVt,"generate");var wVt=class{static{o(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(v$e);if(typeof e=="string"&&e.length>0)return e;let t=vVt();return await this.storage.put(v$e,t),t}},w$e="computer:container-launch-record";async function b$e(e){return{enableInternet:e.enableInternet,envDigest:await xVt(e.env)}}o(b$e,"launchRecordFor");function bVt(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}o(bVt,"sameLaunch");async function xVt(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("")}o(xVt,"digestEnv");var SVt=class{static{o(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(w$e)??null}async set(e){await this.storage.put(w$e,e)}},x$e=new WeakMap;function ire(e){let t=x$e.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},x$e.set(e,t)),t}o(ire,"getContainerLifecycle");function _O(e){return ire(e).exit}o(_O,"containerExitInfo");function S$e(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}o(S$e,"formatExitReason");function k$e(e,t,n){let r=ire(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>E$e(r,i,void 0,n),s=>E$e(r,i,s,n))}o(k$e,"installContainerMonitor");async function nre(e,t){let n=ire(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}o(nre,"destroyContainerExpectingExit");async function E$e(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=S$e(n),a=Date.now();e.exit={reason:s,exitedAt:a},i?console.info({message:"workspace.container.exited",reason:s,exitedAt:a,expected:!0}):console.warn({message:"workspace.container.exited",reason:s,exitedAt:a,expected:!1});try{await r?.()}catch(l){console.error({message:"workspace.container.exit_cleanup_failed",reason:S$e(l),exitedAt:Date.now()})}}o(E$e,"recordExit");var rre="computer:container-runtime-identity",kVt=class{static{o(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(rre)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(rre,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(rre)}},EVt=class extends rVt{static{o(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 kVt(e.storage),this.#n=new wVt(e.storage),this.#i=new SVt(e.storage)}async start(e){let t=_O(this.#t),n=await this.#n.ensure(),r=await b$e(e);if(t!==null){try{await nre(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||!bVt(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 nre(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return k$e(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await nre(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await b$e(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),k$e(this.#t,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:_O(this.#t)}}async exitInfo(){return _O(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=_O(this.#t);if(r!==null)throw new Qo(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function _$e(e){class t extends e{static{o(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new EVt(this.ctx)}}return t}o(_$e,"withWorkspaceContainer");var _Vt={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function A$e(e,t){let n=t.indexOf("."),r=t.indexOf("/"),i=n>=0?n:r;if(i<0)return;let s=t.slice(0,i),a=t.slice(i+1),l=_Vt[s]??s,c=e[l];if(c===void 0)return;let u=c[a];return typeof u=="function"?u:void 0}o(A$e,"resolve");function TVt(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}o(TVt,"errorResponse");async function sre(e,t,n,r,i){let s=A$e(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}o(sre,"callEdgeApi");async function I$e(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(A$e(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 a=typeof s.rpcId=="string"?s.rpcId:"invalid-request",l=s.payload??{};try{let c=await sre(e,i,a,l,t.signal);return c===void 0?new Response("not found",{status:404}):Response.json({type:"server-response",rpcId:c.rpcId,result:c.result})}catch(c){return TVt(a,{code:"internal",message:String(c),details:{}})}}o(I$e,"dispatchEdgeApi");dr();ys();Mm();import{DurableObject as knn}from"cloudflare:workers";var AO=class{constructor(t,n=Date.now,r=2){this.sleepAfterMs=t;this.now=n;this.maxConcurrent=r}sleepAfterMs;now;maxConcurrent;static{o(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 AVt(this.stopping,t);continue}await new Promise((r,i)=>{let s=o(()=>{t?.removeEventListener("abort",a),r()},"wake"),a=o(()=>{let l=this.waiters.indexOf(s);l!==-1&&this.waiters.splice(l,1),i(t.reason)},"abort");this.waiters.push(s),t?.addEventListener("abort",a,{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 AVt(e,t){return t===void 0?e:new Promise((n,r)=>{let i=o(()=>r(t.reason),"abort");t.addEventListener("abort",i,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",i))})}o(AVt,"untilAborted");import{WorkerEntrypoint as IGn}from"cloudflare:workers";var Ty=Pl(C$e(),1);import{gunzipSync as YZt}from"node:zlib";var uE=class{static{o(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),a=this.castInput(n,r),l=this.removeEmpty(this.tokenize(s,r)),c=this.removeEmpty(this.tokenize(a,r));return this.diffWithOptionsObj(l,c,r,i)}diffWithOptionsObj(t,n,r,i){var s;let a=o(S=>{if(S=this.postProcess(S,r),i){setTimeout(function(){i(S)},0);return}else return S},"done"),l=n.length,c=t.length,u=1,d=l+c;r.maxEditLength!=null&&(d=Math.min(d,r.maxEditLength));let p=(s=r.timeout)!==null&&s!==void 0?s:1/0,m=Date.now()+p,h=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(h[0],n,t,0,r);if(h[0].oldPos+1>=c&&g+1>=l)return a(this.buildValues(h[0].lastComponent,n,t));let y=-1/0,v=1/0,b=o(()=>{for(let S=Math.max(y,-u);S<=Math.min(v,u);S+=2){let k,x=h[S-1],E=h[S+1];x&&(h[S-1]=void 0);let T=!1;if(E){let U=E.oldPos-S;T=E&&0<=U&&U<l}let R=x&&x.oldPos+1<c;if(!T&&!R){h[S]=void 0;continue}if(!R||T&&x.oldPos<E.oldPos?k=this.addToPath(E,!0,!1,0,r):k=this.addToPath(x,!1,!0,1,r),g=this.extractCommon(k,n,t,S,r),k.oldPos+1>=c&&g+1>=l)return a(this.buildValues(k.lastComponent,n,t))||!0;h[S]=k,k.oldPos+1>=c&&(v=Math.min(v,S-1)),g+1>=l&&(y=Math.max(y,S+1))}u++},"execEditLength");if(i)o(function S(){setTimeout(function(){if(u>d||Date.now()>m)return i(void 0);b()||S()},0)},"exec")();else for(;u<=d&&Date.now()<=m;){let S=b();if(S)return S}}addToPath(t,n,r,i,s){let a=t.lastComponent;return a&&!s.oneChangePerToken&&a.added===n&&a.removed===r?{oldPos:t.oldPos+i,lastComponent:{count:a.count+1,added:n,removed:r,previousComponent:a.previousComponent}}:{oldPos:t.oldPos+i,lastComponent:{count:1,added:n,removed:r,previousComponent:a}}}extractCommon(t,n,r,i,s){let a=n.length,l=r.length,c=t.oldPos,u=c-i,d=0;for(;u+1<a&&c+1<l&&this.equals(r[c+1],n[u+1],s);)u++,c++,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=c,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 a=i.length,l=0,c=0,u=0;for(;l<a;l++){let d=i[l];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(c,c+d.count);p=p.map(function(m,h){let g=r[u+h];return g.length>m.length?g:m}),d.value=this.join(p)}else d.value=this.join(n.slice(c,c+d.count));c+=d.count,d.added||(u+=d.count)}}return i}};var are=class extends uE{static{o(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=CVt}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
5931
+ `}o(g$e,"pageStyles");NS();var Kne="enabled",Jne=Object.freeze({id:"direct",capabilities:Object.freeze(["bash"]),plan:"free",shell:"just-bash-direct",probe:o(e=>e.LOADER===void 0?"available":"needs-binding","probe")}),cE=Object.freeze({id:"dynamic-worker",capabilities:Object.freeze(["bash","coding"]),plan:"paid",shell:"just-bash-isolated",probe:o(e=>e.LOADER===void 0?"needs-binding":"available","probe")}),Yne=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:o(e=>e.DSH_EDGE_CONTAINER_RUNTIME===Kne?"available":"needs-binding","probe")}),QHt=Object.freeze([Yne,cE,Jne]);function Xne(e,t=QHt){return t.filter(n=>n.probe(e)==="available")}o(Xne,"availableEdgeRuntimeProviders");function Qne(e){let t=o(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}}o(Qne,"resolveEdgeRuntimeSelection");function kO(e){let t=Xne(e),{bash:n,container:r}=Qne(t);return t.find(i=>i.id===(r??n)).shell}o(kO,"resolveEdgeRuntimeShell");function eVt(){return"dsh-edge@0.24.0/isolated"}o(eVt,"resolveEdgeDeploymentId");function cy(e){return{baseURL:tK(e.DEEPSEEK_BASE_URL),maxTokens:iK(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:A0(e.DEEPSEEK_MODEL),reasoningEffort:nK(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:w4(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:rK(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:U1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}o(cy,"resolveEdgeDeploymentConfig");function tVt(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}o(tVt,"edgeDeploymentApiKeyConfigured");function nVt(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)}o(nVt,"projectedEdgeBaseURL");function ere(e,t){return{shell:kO(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:eVt(),apiKeyConfigured:tVt(e),baseURL:nVt(e.DEEPSEEK_BASE_URL),maxTokens:iK(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:A0(e.DEEPSEEK_MODEL),reasoningEffort:nK(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:w4(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:rK(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:U1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}o(ere,"resolveEdgeDeploymentProfile");function EO(e){cy(e);let t=ere(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:v0,upstreamVersion:Pve,status:"ready"}}o(EO,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as Snn}from"node:async_hooks";import{RpcTarget as rVt}from"cloudflare:workers";function iVt(e){let{intervalMs:t,ping:n,onFailure:r}=e,i=!1,s=setInterval(()=>{i||n().catch(a=>{i||(i=!0,clearInterval(s),r(a instanceof Error?a:new Error(String(a))))})},t);return()=>{i||(i=!0,clearInterval(s))}}o(iVt,"startHeartbeat");async function sVt(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}`)}o(sVt,"probeComputerdHealth");var aVt="computer.internal",oVt="/health",tre="/api",lVt=8080,cVt=3e4,uVt=2e4,dVt=1,pVt=2e3,fVt=250,hVt=2e3;function mVt(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}o(mVt,"bearerMatches");var TO=class{static{o(this,"CloudflareContainerBackend")}type="cloudflare-container";id;#e;#t;#r;#n;#i;#s;#o;#l;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??aVt,containerPort:e.containerPort??lVt,connectTimeoutMs:e.connectTimeoutMs??cVt,heartbeatIntervalMs:e.heartbeatIntervalMs??uVt,restartAttempts:e.restartAttempts??dVt,healthProbeTimeoutMs:e.healthProbeTimeoutMs??pVt,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??fVt,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??hVt}}async connect(){if(this.#l)return this.#l;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 Qo(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 Qo(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 a=await this.#h(e),l=c$(a),c,u=new Promise(p=>{let m=!1,h=o(()=>{m||(m=!0,c?.(),p(),this.#l=void 0)},"onClose");a.addEventListener("close",h,{once:!0}),a.addEventListener("error",h,{once:!0}),l.onRpcBroken(h)});this.#e.heartbeatIntervalMs>0&&(c=iVt({intervalMs:this.#e.heartbeatIntervalMs,ping:o(()=>l.sync.watermarks(),"ping"),onFailure:o(()=>{try{a.close()}catch{}},"onFailure")}));let d={rpc:l,runtimeId:i,closed:u,close:o(async()=>{c?.();try{l[Symbol.dispose]?.()}catch{}try{a.close()}catch{}this.#l=void 0},"close")};return this.#l=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(Lw),a;try{a=new URL(s??"")}catch{return new Response("invalid egress URL",{status:400})}if(a.protocol!=="http:"&&a.protocol!=="https:")return new Response("invalid egress URL",{status:400});i.delete(n_),i.delete(Lw);let l=new Request(e,{headers:i});return this.#t.gateway.fetch(new Request(a,l))}if(new URL(e.url).pathname!==tre)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${tre} requires a websocket upgrade`,{status:400});if(!mVt(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.#o=t}),this.#i.catch(()=>{})}#a(){this.#i=void 0,this.#s=void 0,this.#o=void 0}async#p(e,t,n,r,i){let s=this.#e.restartAttempts+1,a=Math.max(0,n-Date.now()),l=Math.max(250,Math.floor(a/s)),c=0,u=0,d,p=i;for(;c<s;){c++;let m=Math.min(n,Date.now()+l);if(await this.#m(e,m).then(()=>!0,h=>(d=h,!1)))return p;if(c<s)try{({runtimeId:p}=await e.restart({env:t,enableInternet:this.#t.mode==="direct"})),u++}catch(h){throw this.#o?.(h),this.#a(),new Qo(this.#d("restart",{attempt:c,maxAttempts:s,restarts:u,lastError:h}),{cause:h})}}throw this.#o?.(new Error("computerd never became healthy")),this.#a(),new Qo(this.#d("health",{attempt:c,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 sVt(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 gVt(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=${y$e(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.#o?.(new Error("container is not enforcing RPC_CLIENT_SECRET")),this.#a(),new Qo(`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:oVt,api:tre,healthTimeoutMs:r})})}catch(s){throw this.#o?.(s),this.#a(),new Qo(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${y$e(s)}`,{cause:s})}if(!i.ok){let s=await i.text().catch(()=>""),a=new Error(`/connect ${i.status}`);throw this.#o?.(a),this.#a(),new Qo(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect returned ${i.status}: ${s}`,{cause:a})}}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 Qo(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#a()}}};function gVt(e){return new Promise(t=>setTimeout(t,e))}o(gVt,"sleep");function y$e(e){return e instanceof Error?e.message:String(e)}o(y$e,"describeError");var v$e="computer:container-client-secret",yVt=16;function vVt(){let e=crypto.getRandomValues(new Uint8Array(yVt));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}o(vVt,"generate");var wVt=class{static{o(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(v$e);if(typeof e=="string"&&e.length>0)return e;let t=vVt();return await this.storage.put(v$e,t),t}},w$e="computer:container-launch-record";async function b$e(e){return{enableInternet:e.enableInternet,envDigest:await xVt(e.env)}}o(b$e,"launchRecordFor");function bVt(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}o(bVt,"sameLaunch");async function xVt(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("")}o(xVt,"digestEnv");var SVt=class{static{o(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(w$e)??null}async set(e){await this.storage.put(w$e,e)}},x$e=new WeakMap;function ire(e){let t=x$e.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},x$e.set(e,t)),t}o(ire,"getContainerLifecycle");function _O(e){return ire(e).exit}o(_O,"containerExitInfo");function S$e(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}o(S$e,"formatExitReason");function k$e(e,t,n){let r=ire(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>E$e(r,i,void 0,n),s=>E$e(r,i,s,n))}o(k$e,"installContainerMonitor");async function nre(e,t){let n=ire(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}o(nre,"destroyContainerExpectingExit");async function E$e(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=S$e(n),a=Date.now();e.exit={reason:s,exitedAt:a},i?console.info({message:"workspace.container.exited",reason:s,exitedAt:a,expected:!0}):console.warn({message:"workspace.container.exited",reason:s,exitedAt:a,expected:!1});try{await r?.()}catch(l){console.error({message:"workspace.container.exit_cleanup_failed",reason:S$e(l),exitedAt:Date.now()})}}o(E$e,"recordExit");var rre="computer:container-runtime-identity",kVt=class{static{o(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(rre)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(rre,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(rre)}},EVt=class extends rVt{static{o(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 kVt(e.storage),this.#n=new wVt(e.storage),this.#i=new SVt(e.storage)}async start(e){let t=_O(this.#t),n=await this.#n.ensure(),r=await b$e(e);if(t!==null){try{await nre(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||!bVt(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 nre(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return k$e(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await nre(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await b$e(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),k$e(this.#t,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:_O(this.#t)}}async exitInfo(){return _O(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=_O(this.#t);if(r!==null)throw new Qo(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function _$e(e){class t extends e{static{o(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new EVt(this.ctx)}}return t}o(_$e,"withWorkspaceContainer");var _Vt={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function A$e(e,t){let n=t.indexOf("."),r=t.indexOf("/"),i=n>=0?n:r;if(i<0)return;let s=t.slice(0,i),a=t.slice(i+1),l=_Vt[s]??s,c=e[l];if(c===void 0)return;let u=c[a];return typeof u=="function"?u:void 0}o(A$e,"resolve");function TVt(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}o(TVt,"errorResponse");async function sre(e,t,n,r,i){let s=A$e(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}o(sre,"callEdgeApi");async function I$e(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(A$e(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 a=typeof s.rpcId=="string"?s.rpcId:"invalid-request",l=s.payload??{};try{let c=await sre(e,i,a,l,t.signal);return c===void 0?new Response("not found",{status:404}):Response.json({type:"server-response",rpcId:c.rpcId,result:c.result})}catch(c){return TVt(a,{code:"internal",message:String(c),details:{}})}}o(I$e,"dispatchEdgeApi");dr();ys();Mm();import{DurableObject as knn}from"cloudflare:workers";var AO=class{constructor(t,n=Date.now,r=2){this.sleepAfterMs=t;this.now=n;this.maxConcurrent=r}sleepAfterMs;now;maxConcurrent;static{o(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 AVt(this.stopping,t);continue}await new Promise((r,i)=>{let s=o(()=>{t?.removeEventListener("abort",a),r()},"wake"),a=o(()=>{let l=this.waiters.indexOf(s);l!==-1&&this.waiters.splice(l,1),i(t.reason)},"abort");this.waiters.push(s),t?.addEventListener("abort",a,{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 AVt(e,t){return t===void 0?e:new Promise((n,r)=>{let i=o(()=>r(t.reason),"abort");t.addEventListener("abort",i,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",i))})}o(AVt,"untilAborted");import{WorkerEntrypoint as IGn}from"cloudflare:workers";var Ty=Pl(C$e(),1);import{gunzipSync as YZt}from"node:zlib";var uE=class{static{o(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),a=this.castInput(n,r),l=this.removeEmpty(this.tokenize(s,r)),c=this.removeEmpty(this.tokenize(a,r));return this.diffWithOptionsObj(l,c,r,i)}diffWithOptionsObj(t,n,r,i){var s;let a=o(S=>{if(S=this.postProcess(S,r),i){setTimeout(function(){i(S)},0);return}else return S},"done"),l=n.length,c=t.length,u=1,d=l+c;r.maxEditLength!=null&&(d=Math.min(d,r.maxEditLength));let p=(s=r.timeout)!==null&&s!==void 0?s:1/0,m=Date.now()+p,h=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(h[0],n,t,0,r);if(h[0].oldPos+1>=c&&g+1>=l)return a(this.buildValues(h[0].lastComponent,n,t));let y=-1/0,v=1/0,b=o(()=>{for(let S=Math.max(y,-u);S<=Math.min(v,u);S+=2){let k,x=h[S-1],E=h[S+1];x&&(h[S-1]=void 0);let T=!1;if(E){let U=E.oldPos-S;T=E&&0<=U&&U<l}let R=x&&x.oldPos+1<c;if(!T&&!R){h[S]=void 0;continue}if(!R||T&&x.oldPos<E.oldPos?k=this.addToPath(E,!0,!1,0,r):k=this.addToPath(x,!1,!0,1,r),g=this.extractCommon(k,n,t,S,r),k.oldPos+1>=c&&g+1>=l)return a(this.buildValues(k.lastComponent,n,t))||!0;h[S]=k,k.oldPos+1>=c&&(v=Math.min(v,S-1)),g+1>=l&&(y=Math.max(y,S+1))}u++},"execEditLength");if(i)o(function S(){setTimeout(function(){if(u>d||Date.now()>m)return i(void 0);b()||S()},0)},"exec")();else for(;u<=d&&Date.now()<=m;){let S=b();if(S)return S}}addToPath(t,n,r,i,s){let a=t.lastComponent;return a&&!s.oneChangePerToken&&a.added===n&&a.removed===r?{oldPos:t.oldPos+i,lastComponent:{count:a.count+1,added:n,removed:r,previousComponent:a.previousComponent}}:{oldPos:t.oldPos+i,lastComponent:{count:1,added:n,removed:r,previousComponent:a}}}extractCommon(t,n,r,i,s){let a=n.length,l=r.length,c=t.oldPos,u=c-i,d=0;for(;u+1<a&&c+1<l&&this.equals(r[c+1],n[u+1],s);)u++,c++,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=c,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 a=i.length,l=0,c=0,u=0;for(;l<a;l++){let d=i[l];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(c,c+d.count);p=p.map(function(m,h){let g=r[u+h];return g.length>m.length?g:m}),d.value=this.join(p)}else d.value=this.join(n.slice(c,c+d.count));c+=d.count,d.added||(u+=d.count)}}return i}};var are=class extends uE{static{o(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=CVt}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
5932
5932
  `))&&(t=t.trim()),(!r.newlineIsToken||!n.includes(`
5933
5933
  `))&&(n=n.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
5934
5934
  `)&&(t=t.slice(0,-1)),n.endsWith(`