dsh-edge 0.21.0-alpha.2 → 0.21.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.
@@ -35,6 +35,8 @@ SOFTWARE.
35
35
 
36
36
  ## Bundled component inventory
37
37
 
38
+ `dsh-edge` also applies a version-bound fix to `@cloudflare/computer@0.3.1`, recorded with its reason in `standalone/patches/audit.json`; the component's license below is unchanged.
39
+
38
40
  The following 674 package versions form the conservative, platform-neutral production closure used to assemble the Web and Worker artifacts in this distribution. Platform-specific build binaries that are not distributed in those artifacts are excluded; tree shaking can omit additional code. The inventory and legal texts are generated during packaging rather than referring recipients to a source checkout. License expressions are SPDX identifiers supplied by each package. Dependencies installed separately by npm remain declared in this package's `package.json`.
39
41
 
40
42
  | Component | License |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-edge",
3
- "version": "0.21.0-alpha.2",
3
+ "version": "0.21.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",
@@ -54,6 +54,8 @@ const packageRoot = fileURLToPath(new URL('../', import.meta.url))
54
54
  const standaloneRoot = join(packageRoot, 'standalone')
55
55
  const edgeManifest = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8'))
56
56
  const patchAudit = JSON.parse(readFileSync(join(standaloneRoot, 'patches', 'audit.json'), 'utf8'))
57
+ const harnessPatches = patchAudit.filter(entry => entry.package.startsWith('@deepseek-ai/dsh-'))
58
+ const componentPatches = patchAudit.filter(entry => !entry.package.startsWith('@deepseek-ai/dsh-'))
57
59
  if (!Array.isArray(patchAudit) || patchAudit.length === 0) {
58
60
  throw new Error('The retained patch audit must be a non-empty array.')
59
61
  }
@@ -231,13 +233,14 @@ function renderNotices(components) {
231
233
 
232
234
  ## DeepSeek Harness
233
235
 
234
- \`dsh-edge\` assembles published DeepSeek Harness packages and applies ${String(patchAudit.length)} version-bound adaptations to the pinned \`${edgeManifest.dshEdge.upstreamVersion}\` release. DeepSeek Harness remains under its upstream MIT license:
236
+ \`dsh-edge\` assembles published DeepSeek Harness packages and applies ${String(harnessPatches.length)} version-bound adaptations to the pinned \`${edgeManifest.dshEdge.upstreamVersion}\` release. DeepSeek Harness remains under its upstream MIT license:
235
237
 
236
238
  \`\`\`text
237
239
  ${upstreamLicense}
238
240
  \`\`\`
239
241
 
240
242
  ## Bundled component inventory
243
+ ${componentPatches.length === 0 ? '' : `\n\`dsh-edge\` also applies a version-bound fix to ${componentPatches.map(entry => `\`${entry.package}@${entry.version}\``).join(', ')}, recorded with its reason in \`standalone/patches/audit.json\`; the component's license below is unchanged.`}
241
244
 
242
245
  The following ${components.length} package versions form the conservative, platform-neutral production closure used to assemble the Web and Worker artifacts in this distribution. Platform-specific build binaries that are not distributed in those artifacts are excluded; tree shaking can omit additional code. The inventory and legal texts are generated during packaging rather than referring recipients to a source checkout. License expressions are SPDX identifiers supplied by each package. Dependencies installed separately by npm remain declared in this package's \`package.json\`.
243
246
 
@@ -152,7 +152,7 @@ Known schemas:
152
152
  - `)}`,new Error(Ke)}let wt=`${c}/$ref`,st=Ws(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"?tx(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=>tx(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`;Ws(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=Ws(e,Ke,n,r,i,f===!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=Ws(e,Ke,n,r,i,f===!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=Ws(e,st,n,r,i,f===!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(Ws(e,_,n,r,i,s,o,ze,l).valid){if(T!==void 0){let wt=Ws(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(M!==void 0){let wt=Ws(e,M,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}/${mu(Ke)}`,Oe=Ws(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=Ws(e,O[st],n,r,i,s,o,`${Ke}/${mu(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=Ws(e,yt,n,r,i,s,o,`${st}/${mu(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}/${mu(Ke)}`,Oe=Ws(e[Ke],j[Ke],n,r,i,s,yt,`${st}/${mu(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}/${mu(_t)}`,ht=Ws(e[_t],Oe,n,r,i,s,Gt,`${st}/${mu(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}/${mu(Ke)}`,Oe=Ws(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&&J!==void 0){let st=`${c}/unevaluatedProperties`;for(let Ke in e)if(!l[Ke]){let yt=`${o}/${mu(Ke)}`,Oe=Ws(e[Ke],J,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(P!==void 0){let st=`${c}/prefixItems`,Ke=Math.min(P.length,ze);for(;je<Ke;je++){let yt=Ws(e[je],P[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=Ws(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=Ws(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=Ws(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=Ws(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=Ws(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)&&tx(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:YSe(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."}),D!==void 0&&JK[D]&&!JK[D](e)&&Ee.push({instanceLocation:o,keyword:"format",keywordLocation:`${c}/format`,error:`String does not match format "${D}".`})}return{valid:Ee.length===0,errors:Ee}}var eZ=ce(()=>{YK();zC();XK();BC();QK();a(Ws,"validate")});var HC,JSe=ce(()=>{zC();eZ();HC=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=rm(t)}validate(t){return Ws(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,n){n&&(t={...t,$id:n}),rm(t,this.lookup)}}});var XSe=ce(()=>{YK();zC();XK();BC();ZSe();QK();eZ();JSe()});var WC,QSe=ce(()=>{XSe();WC=class{static{a(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let n=new HC(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 No,VC=ce(()=>{"use strict";No={probeTimeoutMs:3e4,callTimeoutMs:6e4,maxToolsPerServer:128,maxCatalogPages:10,maxCatalogBytes:131072,maxDescriptionLength:512,maxErrorMessageChars:300,maxPublicNameLength:64,maxInstructionsLength:1024,metaToolThreshold:20}});import{createHash as fwt}from"node:crypto";function mwt(e){let t=e.replace(/[.*+?^${}()|[\]\\]/gu,n=>n==="*"?"\0":`\\${n}`);return new RegExp(`^${t.replaceAll("\0",".*")}$`)}function eke(e,t,n){let r=t??"read_only";return r==="allow_all"?"allow":r==="approve_all"?"ask":n===!0?"allow":n===!1?"ask":hwt.some(i=>mwt(i).test(e))?"allow":"ask"}function Cf(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,No.maxErrorMessageChars)}function tke(e,t){let n=`mcp__${e}__${t}`,r=n.replace(/[^A-Za-z0-9_-]/gu,"_");if(r===n&&r.length<=No.maxPublicNameLength)return r;let i=gwt(e,t),s=No.maxPublicNameLength-i.length-1;return`${r.slice(0,s)}_${i}`}function gwt(e,t){return fwt("sha256").update(`${e}\0${t}`).digest("hex").slice(0,12)}function nke(e){if(!(e==null||typeof e!="object"))try{let t=JSON.parse(JSON.stringify(e));return F0(t),t}catch{return}}function wwt(e){return ywt.has(e)}function rke(e){return e.type!=="image"||e.data===void 0||e.mimeType===void 0||!wwt(e.mimeType)||!vwt.test(e.data)?void 0:{data:Uint8Array.from(atob(e.data),n=>n.charCodeAt(0)),mediaType:e.mimeType}}function ike(e){return e.some(t=>t.type==="image"&&t.data!==void 0)}function f6(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 hwt,ywt,vwt,GC=ce(()=>{"use strict";ho();VC();hwt=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a(mwt,"globToRegExp");a(eke,"evaluateMcpToolPolicy");a(Cf,"scrubMcpErrorMessage");a(tke,"publicToolName");a(gwt,"hashSuffix");a(nke,"supportedOutputSchema");ywt=new Set(["image/png","image/jpeg"]),vwt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(wwt,"isImageMediaType");a(rke,"decodeImageBlock");a(ike,"containsImage");a(f6,"mapMcpResultToContentBlocks")});var tZ,ske=ce(()=>{tZ={name:"dsh-edge",version:"0.21.0-alpha.2",description:"Your DeepSeek Harness, anywhere \u2014 deploy a persistent personal coding agent to Cloudflare Workers in one command",author:"pawaca",license:"MIT",type:"module",bin:{"dsh-edge":"scripts/cli.mjs"},files:["dist","worker","scripts/*.d.mts","scripts/*.mjs","wrangler.jsonc","README.md","README.zh.md","LICENSE","THIRD_PARTY_NOTICES.md"],repository:{type:"git",url:"git+https://github.com/pawaca/dsh-edge.git",directory:"apps/dsh-edge"},homepage:"https://github.com/pawaca/dsh-edge#readme",bugs:{url:"https://github.com/pawaca/dsh-edge/issues"},keywords:["deepseek","deepseek-harness","ai-agents","byok","cloudflare-workers","durable-objects","self-hosted"],engines:{node:">=22.14.0"},publishConfig:{access:"public"},dshEdge:{upstreamVersion:"0.2.0-rc.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"},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-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-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-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-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-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 _y,oke,ake,h6=ce(()=>{"use strict";ske();_y=tZ.version,oke=tZ.dshEdge.upstreamVersion,ake=`npx dsh-edge@${_y.includes("-")?"next":"latest"} upgrade`});function Ewt(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 _wt(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function im(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 xwt)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(_wt(i)){let s=Ewt(i),o=s??i;for(let c of Swt)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 kwt)if(c.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function Twt(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function cke(e,t,n){im(e);let r=new UC(new URL(e),{requestInit:{headers:Twt(t),signal:n},fetch:Ty}),i=new FC({name:"dsh-edge",version:_y},{capabilities:{},jsonSchemaValidator:Awt});return await i.connect(r),{client:i,close:a(async()=>{await i.close().catch(()=>{})},"close")}}async function lke(e,t,n){let r=AbortSignal.timeout(No.probeTimeoutMs),i;try{i=await cke(t,n,r)}catch(c){throw new Error(Cf(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 f=0;f<No.maxCatalogPages;f++){let g=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let y of g.tools){if(c.length>=No.maxToolsPerServer)break;let v=tke(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=nke(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>=No.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?.(),h=s.getInstructions?.();return{tools:c,serverInfo:p?{name:p.name,version:p.version}:void 0,instructions:typeof h=="string"&&h.length>0?h.slice(0,No.maxInstructionsLength):void 0}}finally{await o()}}async function KC(e,t,n,r,i,s){let o=s??No.callTimeoutMs,c=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),l;try{l=await cke(e,r,c)}catch(u){throw new Error(Cf(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(Cf(u instanceof Error?u.message:String(u)))}finally{await l.close()}}var xwt,Swt,kwt,Awt,Ty,m6=ce(()=>{"use strict";pSe();WSe();QSe();GC();VC();h6();xwt=[".internal",".local",".localhost"],Swt=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],kwt=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(Ewt,"extractMappedIPv4");a(_wt,"isIpAddress");a(im,"assertSafeUrl");a(Twt,"buildHeaders");Awt=new WC,Ty=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(cke,"connectClient");a(lke,"probe");a(KC,"callTool")});import{Buffer as Iwt}from"node:buffer";function $wt(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Owt.has(e.code)}function dke(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Rwt.has(e.code)}function pke(e,t,n){let r=Iwt.from(e,"base64");if(e.length===0&&t==="reject"||r.toString("base64")!==e)throw new ur(n==="INVALID_IMAGE_BASE64"?"Image upload is not canonical base64.":"File upload is not canonical base64.",n);return new Uint8Array(r)}function Nwt(e){return pke(e,"reject","INVALID_IMAGE_BASE64")}function Pwt(e){return{data:Nwt(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function g6(e,t){return e.saveImages(t.map(Pwt))}async function Dwt(e,t){return e.saveFile({data:pke(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function fke(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 nZ(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 uke,Cwt,Rwt,Owt,ur,rZ,sm=ce(()=>{Yn();uke=["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"],Cwt=[...uke,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],Rwt=new Set(uke),Owt=new Set(Cwt),ur=class extends Error{static{a(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};a($wt,"isAttachmentError");a(dke,"isImageAdmissionError");a(pke,"decodeCanonicalBase64");a(Nwt,"decodeBase64");a(Pwt,"saveInput");a(g6,"admitEncodedImages");a(Dwt,"admitEncodedFile");a(fke,"requestImageDimensions");a(nZ,"longEdgeDimensions");rZ=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 ur("Image batch exceeds the configured image-count limit.","TOO_MANY_IMAGES");if(e.reduce((i,s)=>i+s.data.byteLength,0)>n)throw new ur("Image batch exceeds the configured aggregate image-byte limit.","IMAGES_TOO_LARGE");for(let i of e)if(!r.includes(i.mediaType))throw new ur(`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 g6(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 Dwt(this,e)}isAttachmentError(e){return $wt(e)}imageHostPath(e){}saveFile(e){return Promise.reject(new ur("The mounted attachment provider cannot store verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}saveFileStream(e){return Promise.reject(new ur("The mounted attachment provider cannot stream verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}async*readFileStream(e,t){t?.throwIfAborted(),await Promise.reject(new ur("The mounted attachment provider cannot read verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}fileHostPath(e){}readImageRequest(e,t,n){return n?.throwIfAborted(),Promise.reject(new ur("The mounted attachment provider cannot derive model-request images.","ATTACHMENT_PROJECTION_UNSUPPORTED"))}}});var YC={};Tn(YC,{buildAuthorizationUrl:()=>Hwt,discoverEndpoints:()=>Bwt,exchangeCode:()=>Wwt,isTokenExpired:()=>Gwt,refreshToken:()=>Vwt,registerClient:()=>zwt});function yke(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 Uwt(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 Bwt(e){let t=AbortSignal.timeout(ZC),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);im(i.href);let s=await Ty(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);im(d.href);let p=await Ty(d.href,{signal:t});if(!p.ok)throw new Error(`AS metadata failed: HTTP ${p.status}`);let h=await p.json();if(typeof h.authorization_endpoint!="string"||typeof h.token_endpoint!="string")throw new Error("Missing required endpoints in AS metadata");return{authorization:h.authorization_endpoint,token:h.token_endpoint,registration:h.registration_endpoint}}async function zwt(e,t,n){let r=AbortSignal.timeout(ZC);im(e);let i=await Ty(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 Hwt(e,t,n,r,i){let s=yke(32),o=yke(64),c=await Uwt(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 Wwt(e,t,n,r,i,s){let o=AbortSignal.timeout(ZC),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),im(e);let l=await Ty(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 vke(await l.json())}async function Vwt(e,t,n,r){let i=AbortSignal.timeout(ZC),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),im(e);let o=await Ty(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 vke(await o.json())}function vke(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 Gwt(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var ZC,JC=ce(()=>{"use strict";m6();ZC=1e4;a(yke,"randomString");a(Uwt,"sha256Base64Url");a(Bwt,"discoverEndpoints");a(zwt,"registerClient");a(Hwt,"buildAuthorizationUrl");a(Wwt,"exchangeCode");a(Vwt,"refreshToken");a(vke,"parseTokenResponse");a(Gwt,"isTokenExpired")});var Wn,Tke,y6=ce(()=>{Yn();kr();Wn=class extends zr{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},Tke=class extends Et{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new Wn("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function SZ(e){return c9.test(e)}function l9(e){return e.invocation.modelInvocable}function rx(e){return e.invocation.userInvocable}function kZ(e){let t=Oxt(e);return[`<skill_content name="${$xt(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 hwt,ywt,vwt,GC=ce(()=>{"use strict";ho();VC();hwt=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a(mwt,"globToRegExp");a(eke,"evaluateMcpToolPolicy");a(Cf,"scrubMcpErrorMessage");a(tke,"publicToolName");a(gwt,"hashSuffix");a(nke,"supportedOutputSchema");ywt=new Set(["image/png","image/jpeg"]),vwt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(wwt,"isImageMediaType");a(rke,"decodeImageBlock");a(ike,"containsImage");a(f6,"mapMcpResultToContentBlocks")});var tZ,ske=ce(()=>{tZ={name:"dsh-edge",version:"0.21.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"},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-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-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-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-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-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 _y,oke,ake,h6=ce(()=>{"use strict";ske();_y=tZ.version,oke=tZ.dshEdge.upstreamVersion,ake=`npx dsh-edge@${_y.includes("-")?"next":"latest"} upgrade`});function Ewt(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 _wt(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function im(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 xwt)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(_wt(i)){let s=Ewt(i),o=s??i;for(let c of Swt)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 kwt)if(c.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function Twt(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function cke(e,t,n){im(e);let r=new UC(new URL(e),{requestInit:{headers:Twt(t),signal:n},fetch:Ty}),i=new FC({name:"dsh-edge",version:_y},{capabilities:{},jsonSchemaValidator:Awt});return await i.connect(r),{client:i,close:a(async()=>{await i.close().catch(()=>{})},"close")}}async function lke(e,t,n){let r=AbortSignal.timeout(No.probeTimeoutMs),i;try{i=await cke(t,n,r)}catch(c){throw new Error(Cf(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 f=0;f<No.maxCatalogPages;f++){let g=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let y of g.tools){if(c.length>=No.maxToolsPerServer)break;let v=tke(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=nke(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>=No.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?.(),h=s.getInstructions?.();return{tools:c,serverInfo:p?{name:p.name,version:p.version}:void 0,instructions:typeof h=="string"&&h.length>0?h.slice(0,No.maxInstructionsLength):void 0}}finally{await o()}}async function KC(e,t,n,r,i,s){let o=s??No.callTimeoutMs,c=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),l;try{l=await cke(e,r,c)}catch(u){throw new Error(Cf(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(Cf(u instanceof Error?u.message:String(u)))}finally{await l.close()}}var xwt,Swt,kwt,Awt,Ty,m6=ce(()=>{"use strict";pSe();WSe();QSe();GC();VC();h6();xwt=[".internal",".local",".localhost"],Swt=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],kwt=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(Ewt,"extractMappedIPv4");a(_wt,"isIpAddress");a(im,"assertSafeUrl");a(Twt,"buildHeaders");Awt=new WC,Ty=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(cke,"connectClient");a(lke,"probe");a(KC,"callTool")});import{Buffer as Iwt}from"node:buffer";function $wt(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Owt.has(e.code)}function dke(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Rwt.has(e.code)}function pke(e,t,n){let r=Iwt.from(e,"base64");if(e.length===0&&t==="reject"||r.toString("base64")!==e)throw new ur(n==="INVALID_IMAGE_BASE64"?"Image upload is not canonical base64.":"File upload is not canonical base64.",n);return new Uint8Array(r)}function Nwt(e){return pke(e,"reject","INVALID_IMAGE_BASE64")}function Pwt(e){return{data:Nwt(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function g6(e,t){return e.saveImages(t.map(Pwt))}async function Dwt(e,t){return e.saveFile({data:pke(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function fke(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 nZ(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 uke,Cwt,Rwt,Owt,ur,rZ,sm=ce(()=>{Yn();uke=["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"],Cwt=[...uke,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],Rwt=new Set(uke),Owt=new Set(Cwt),ur=class extends Error{static{a(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};a($wt,"isAttachmentError");a(dke,"isImageAdmissionError");a(pke,"decodeCanonicalBase64");a(Nwt,"decodeBase64");a(Pwt,"saveInput");a(g6,"admitEncodedImages");a(Dwt,"admitEncodedFile");a(fke,"requestImageDimensions");a(nZ,"longEdgeDimensions");rZ=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 ur("Image batch exceeds the configured image-count limit.","TOO_MANY_IMAGES");if(e.reduce((i,s)=>i+s.data.byteLength,0)>n)throw new ur("Image batch exceeds the configured aggregate image-byte limit.","IMAGES_TOO_LARGE");for(let i of e)if(!r.includes(i.mediaType))throw new ur(`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 g6(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 Dwt(this,e)}isAttachmentError(e){return $wt(e)}imageHostPath(e){}saveFile(e){return Promise.reject(new ur("The mounted attachment provider cannot store verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}saveFileStream(e){return Promise.reject(new ur("The mounted attachment provider cannot stream verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}async*readFileStream(e,t){t?.throwIfAborted(),await Promise.reject(new ur("The mounted attachment provider cannot read verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}fileHostPath(e){}readImageRequest(e,t,n){return n?.throwIfAborted(),Promise.reject(new ur("The mounted attachment provider cannot derive model-request images.","ATTACHMENT_PROJECTION_UNSUPPORTED"))}}});var YC={};Tn(YC,{buildAuthorizationUrl:()=>Hwt,discoverEndpoints:()=>Bwt,exchangeCode:()=>Wwt,isTokenExpired:()=>Gwt,refreshToken:()=>Vwt,registerClient:()=>zwt});function yke(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 Uwt(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 Bwt(e){let t=AbortSignal.timeout(ZC),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);im(i.href);let s=await Ty(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);im(d.href);let p=await Ty(d.href,{signal:t});if(!p.ok)throw new Error(`AS metadata failed: HTTP ${p.status}`);let h=await p.json();if(typeof h.authorization_endpoint!="string"||typeof h.token_endpoint!="string")throw new Error("Missing required endpoints in AS metadata");return{authorization:h.authorization_endpoint,token:h.token_endpoint,registration:h.registration_endpoint}}async function zwt(e,t,n){let r=AbortSignal.timeout(ZC);im(e);let i=await Ty(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 Hwt(e,t,n,r,i){let s=yke(32),o=yke(64),c=await Uwt(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 Wwt(e,t,n,r,i,s){let o=AbortSignal.timeout(ZC),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),im(e);let l=await Ty(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 vke(await l.json())}async function Vwt(e,t,n,r){let i=AbortSignal.timeout(ZC),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),im(e);let o=await Ty(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 vke(await o.json())}function vke(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 Gwt(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var ZC,JC=ce(()=>{"use strict";m6();ZC=1e4;a(yke,"randomString");a(Uwt,"sha256Base64Url");a(Bwt,"discoverEndpoints");a(zwt,"registerClient");a(Hwt,"buildAuthorizationUrl");a(Wwt,"exchangeCode");a(Vwt,"refreshToken");a(vke,"parseTokenResponse");a(Gwt,"isTokenExpired")});var Wn,Tke,y6=ce(()=>{Yn();kr();Wn=class extends zr{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},Tke=class extends Et{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new Wn("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function SZ(e){return c9.test(e)}function l9(e){return e.invocation.modelInvocable}function rx(e){return e.invocation.userInvocable}function kZ(e){let t=Oxt(e);return[`<skill_content name="${$xt(e.name)}">`,"<skill_resources>",...t,"</skill_resources>","","<skill_instructions>",e.content,"</skill_instructions>","</skill_content>"].join(`
156
156
  `)}function Oxt(e){let t=e.resourceBase;if(t===void 0)return[`Resources for this skill are managed by provider "${nx(e.provider)}".`,"Load referenced resources only as needed."];switch(t.kind){case"directory":return[`Base directory for this skill: ${nx(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: ${nx(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: ${nx(t.description)}`,"Load referenced resources only as needed."];default:return pi(t,"SkillResourceBase.kind")}}function $xt(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;")}function nx(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Pxt(e,t){if(Array.isArray(e))return{candidates:e,complete:!0};if(e===null||typeof e!="object")throw Gke(t);let n=e;if(!Array.isArray(n.candidates)||typeof n.complete!="boolean")throw Gke(t);return n}function Gke(e){return new TypeError(`skill provider "${e}" list() must return an array or { candidates, complete } observation`)}function Mxt(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:Rxt,locator:e,...e.path!==void 0?{path:e.path}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}function Lxt(e,t){if(typeof e.name!="string")throw new TypeError(`skill provider "${t}" returned a non-string skill name`);if(!c9.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(EZ(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 jxt(e){if(!c9.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`);EZ(e.invocation,`runtime skill "${e.name}"`)}function Fxt(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(!c9.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(EZ(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 qxt(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 EZ(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 Uxt(e,t){return Jke(e.name,t.name)}function Jke(e,t){return e<t?-1:e>t?1:0}function Bxt(e,t){return e.candidate.rank-t.candidate.rank||e.providerOrder-t.providerOrder||e.localOrder-t.localOrder}function zxt(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 Kke(e,t){return t===void 0?e:(x6(t),new Promise((n,r)=>{let i=a(()=>{t.removeEventListener("abort",s)},"cleanup"),s=a(()=>{i(),r(a9(t.reason))},"onAbort");t.addEventListener("abort",s,{once:!0}),e.then(o=>{i(),n(o)},o=>{i(),r(a9(o))})}))}function x6(e){if(e?.aborted===!0)throw a9(e.reason)}function a9(e){try{if(e instanceof Error)return e}catch{}return new Error(o9(e))}function o9(e){try{return String(e)}catch{return"[unrenderable thrown value]"}}var c9,Vke,Cxt,s9,Rxt,Zke,Nxt,Yke,Dxt,ix=ce(()=>{Yn();rs();Kc();hn();c9=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Vke=128,Cxt=2,s9="runtime",Rxt=250,Zke=600;a(SZ,"isSkillName");a(l9,"isModelInvocable");a(rx,"isUserInvocable");a(kZ,"renderSkillContent");a(Oxt,"renderResourceHint");a($xt,"escapeAttr");a(nx,"escapeText");Nxt=class{static{a(this,"SkillLayer")}providers;runtime=new Map;constructor(e){this.providers=new df(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}},Yke=class extends Et{static{a(this,"SkillRegistry")}static Config=q.object({collectCacheMaxEntries:q.number().default(Vke)});collectCacheMaxEntries;layers=new pf(e=>new Nxt(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??Vke,zxt("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===s9)throw new Error(`"${s9}" 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){jxt(e);let t=Gc(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??s9};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=>qxt(n.candidate)).sort(Uxt),complete:t.cacheable}}async get(e,t={}){if(!SZ(e))return;let n=await this.collect(t);x6(t.signal);let r=n.entries.get(e);if(r===void 0)return;let i=await Kke(r.provider.get(r.candidate,t),t.signal);if(i!==void 0){if(Fxt(i),i.name!==r.candidate.name){this.invalidateEntry(r);return}return i}}async collect(e){x6(e.signal);let t=1;for(;;){let n=this.revision,r=this.collectCacheKey(e.cwd,zk(e.scope),n),i=this.collectCache.get(r);if(i!==void 0)return{entries:i,cacheable:!0};let s=await this.collectFresh(e);if(x6(e.signal),n!==this.revision){if(t<Cxt){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(Bxt);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){x6(t.signal);let n=[],r=!0,i=0;for(let s of[...e.runtime.values()].sort((o,c)=>Jke(o.name,c.name)))n.push({candidate:Mxt(s),provider:Dxt,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 Kke(s.list(t),t.signal)}catch(d){if(t.signal?.aborted===!0)throw a9(t.signal.reason);r=!1,this.ctx.logger.warn(`skill provider "${s.name}" skipped: ${o9(d)}`)}if(l===void 0)continue;let u=Pxt(l,s.name);u.complete||(r=!1);for(let d of u.candidates)Lxt(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: ${o9(n)}`)})}catch(t){this.ctx.logger.warn(`skills/change listener threw: ${o9(t)}`)}}};a(Pxt,"normalizeProviderObservation");a(Gke,"invalidProviderObservation");Dxt={name:s9,list(){return Promise.resolve([])},get(e){return Promise.resolve(e.locator)}};a(Mxt,"runtimeCandidate");a(Lxt,"validateCandidate");a(jxt,"validateRuntimeSkill");a(Fxt,"validateDefinition");a(qxt,"toSummary");a(EZ,"validateInvocation");a(Uxt,"compareSkillSummary");a(Jke,"compareCodePoints");a(Bxt,"compareIndexedCandidates");a(zxt,"assertPositiveInteger");a(Kke,"waitWithAbort");a(x6,"throwIfAborted");a(a9,"toError");a(o9,"errorMessage")});var dd,ox=ce(()=>{dd=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 am,y_e,rY=ce(()=>{Yn();am=class extends Error{static{a(this,"DirectoryPickerError")}code;path;constructor(e,t,n){super(n),this.code=e,this.path=t,this.name="DirectoryPickerError"}},y_e=class extends Et{static{a(this,"DirectoryPicker")}constructor(e){super(e,"directoryPicker")}}});var dTe=be((dUn,hR)=>{var uTe=uTe||function(e){return Buffer.from(e).toString("base64")};function STt(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,h=new Array(65535),f=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),M,D=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],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],J=[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[D[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[D[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[D[Ke]]*st[yt]*st[Oe]*8),c[Ke]=1/(s[D[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 P(){l=N(j,$),u=N(I,U),d=N(W,J),p=N(C,R)}a(P,"initHuffmanTbl");function G(){for(var oe=1,Le=2,Ee=1;Ee<=15;Ee++){for(var ut=oe;ut<Le;ut++)f[32767+ut]=Ee,h[32767+ut]=[],h[32767+ut][1]=Ee,h[32767+ut][0]=ut;for(var ze=-(Le-1);ze<=-oe;ze++)f[32767+ze]=Ee,h[32767+ze]=[],h[32767+ze][1]=Ee,h[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 vn=Ee+yt,Vt=Ee-yt,Ut=ut+Ke,ae=ut-Ke,Pe=ze+st,Ge=ze-st,ct=je+wt,Ot=je-wt,Xe=vn+ct,cn=vn-ct,rn=Ut+Pe,wn=Ut-Pe;oe[Oe]=Xe+rn,oe[Oe+4]=Xe-rn;var jt=(wn+cn)*.707106781;oe[Oe+2]=cn+jt,oe[Oe+6]=cn-jt,Xe=Ot+Ge,rn=Ge+ae,wn=ae+Vt;var Lr=(Xe-wn)*.382683433,Ur=.5411961*Xe+Lr,ms=1.306562965*wn+Lr,Ni=rn*.707106781,pr=Vt+Ni,gs=Vt-Ni;oe[Oe+5]=gs+Ur,oe[Oe+3]=gs-Ur,oe[Oe+1]=pr+ms,oe[Oe+7]=pr-ms,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 Bs=Ee+yt,lo=Ee-yt,To=ut+Ke,Bt=ut-Ke,jn=ze+st,Ao=ze-st,Aa=je+wt,Ho=je-wt,Wo=Bs+Aa,ea=Bs-Aa,Ia=To+jn,nc=To-jn;oe[Oe]=Wo+Ia,oe[Oe+32]=Wo-Ia;var eu=(nc+ea)*.707106781;oe[Oe+16]=ea+eu,oe[Oe+48]=ea-eu,Wo=Ho+Ao,Ia=Ao+Bt,nc=Bt+lo;var cl=(Wo-nc)*.382683433,Fd=.5411961*Wo+cl,qd=1.306562965*nc+cl,Ud=Ia*.707106781,Bd=lo+Ud,yh=lo-Ud;oe[Oe+40]=yh+Fd,oe[Oe+24]=yh-Fd,oe[Oe+8]=Bd+qd,oe[Oe+56]=Bd-qd,Oe++}var Vp;for(_t=0;_t<ht;++_t)Vp=oe[_t]*Le[_t],g[_t]=Vp>0?Vp+.5|0:Vp-.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(J[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[D[Gt]]=_t[Gt];var ht=y[0]-Ee;Ee=y[0],ht==0?Q(ut[0]):(st=32767+ht,Q(ut[f[st]]),Q(h[st]));for(var vn=63;vn>0&&y[vn]==0;vn--);if(vn==0)return Q(je),Ee;for(var Vt=1,Ut;Vt<=vn;){for(var ae=Vt;y[Vt]==0&&Vt<=vn;++Vt);var Pe=Vt-ae;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)+f[st]]),Q(h[st]),Vt++}return vn!=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,vn,Vt,Ut,ae,Pe,Ge,ct;Gt<Ke;){for(_t=0;_t<yt;){for(Ut=yt*Gt+_t,ae=Ut,Pe=-1,Ge=0,ct=0;ct<64;ct++)Ge=ct>>3,Pe=(ct&7)*4,ae=Ut+Ge*yt+Pe,Gt+Ge>=Ke&&(ae-=yt*(Gt+1+Ge-Ke)),_t+Pe>=yt&&(ae-=_t+Pe-yt+4),ht=wt[ae++],vn=wt[ae++],Vt=wt[ae++],S[ct]=(T[ht]+T[vn+256>>0]+T[Vt+512>>0]>>16)-128,k[ct]=(T[ht+768>>0]+T[vn+1024>>0]+T[Vt+1280>>0]>>16)-128,E[ct]=(T[ht+1280>>0]+T[vn+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 Ot=[];Ot[1]=b+1,Ot[0]=(1<<b+1)-1,Q(Ot)}if(ne(65497),typeof hR>"u")return new Uint8Array(v);return Buffer.from(v);var Xe,cn};function Ce(oe){if(oe<=0&&(oe=1),oe>100&&(oe=100),M!=oe){var Le=0;oe<50?Le=Math.floor(5e3/oe):Le=Math.floor(200-oe*2),O(Le),M=oe}}a(Ce,"setQuality");function ke(){var oe=new Date().getTime();e||(e=50),it(),P(),G(),X(),Ce(e);var Le=new Date().getTime()-oe}a(ke,"init"),ke()}a(STt,"JPEGEncoder");typeof hR<"u"?hR.exports=lTe:typeof window<"u"&&(window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=lTe);function lTe(e,t){typeof t>"u"&&(t=50);var n=new STt(t),r=n.encode(e,t);return{data:r,width:e.width,height:e.height}}a(lTe,"encode")});var fTe=be((fUn,fJ)=>{var pJ=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,M=16;M>0&&!b[M-1];)M--;E.push({children:[],index:0});var D=E[0],j;for(_=0;_<M;_++){for(T=0;T<b[_];T++){for(D=E.pop(),D.children[D.index]=S[k];D.index>0;){if(E.length===0)throw new Error("Could not recreate Huffman Table");D=E.pop()}for(D.index++,E.push(D);E.length<=_;)E.push(j={children:[],index:0}),D.children[D.index]=j.children,D=j;k++}_+1<M&&(E.push(j={children:[],index:0}),D.children[D.index]=j.children,D=j)}return E[0].children}a(p,"buildHuffmanTable");function h(b,S,k,E,_,T,M,D,j,$){var W=k.precision,J=k.samplesPerLine,I=k.scanLines,U=k.mcusPerLine,C=k.progressive,R=k.maxH,O=k.maxV,N=S,P=0,G=0;function X(){if(G>0)return G--,P>>G&1;if(P=b[S++],P==255){var Oe=b[S++];if(Oe)throw new Error("unexpected marker: "+(P<<8|Oe).toString(16))}return G=7,P>>>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 vn=1;vn<64;){var Vt=Q(Oe.huffmanTableAC),Ut=Vt&15,ae=Vt>>4;if(Ut===0){if(ae<15)break;vn+=16;continue}vn+=ae;var Pe=t[vn];_t[Pe]=ne(Ut),vn++}}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=M;Gt<=ht;){var vn=Q(Oe.huffmanTableAC),Vt=vn&15,Ut=vn>>4;if(Vt===0){if(Ut<15){Se=z(Ut)+(1<<Ut)-1;break}Gt+=16;continue}Gt+=Ut;var ae=t[Gt];_t[ae]=ne(Vt)*(1<<j),Gt++}}a(_e,"decodeACFirst");var ue=0,de;function ot(Oe,_t){for(var Gt=T,ht=M,vn=0;Gt<=ht;){var Vt=t[Gt],Ut=_t[Vt]<0?-1:1;switch(ue){case 0:var ae=Q(Oe.huffmanTableAC),Pe=ae&15,vn=ae>>4;if(Pe===0)vn<15?(Se=z(vn)+(1<<vn),ue=4):(vn=16,ue=1);else{if(Pe!==1)throw new Error("invalid ACn encoding");de=ne(Pe),ue=vn?2:3}continue;case 1:case 2:_t[Vt]?_t[Vt]+=(X()<<j)*Ut:(vn--,vn===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,vn){var Vt=Gt/U|0,Ut=Gt%U,ae=Vt*Oe.v+ht,Pe=Ut*Oe.h+vn;Oe.blocks[ae]===void 0&&$.tolerantDecoding||_t(Oe,Oe.blocks[ae][Pe])}a(Ve,"decodeMcu");function it(Oe,_t,Gt){var ht=Gt/Oe.blocksPerLine|0,vn=Gt%Oe.blocksPerLine;Oe.blocks[ht]===void 0&&$.tolerantDecoding||_t(Oe,Oe.blocks[ht][vn])}a(it,"decodeBlock");var Ce=E.length,ke,oe,Le,Ee,ut,ze;C?T===0?ze=D===0?we:le:ze=D===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(h,"decodeScan");function f(b,S){var k=[],E=S.blocksPerLine,_=S.blocksPerColumn,T=E<<3,M=new Int32Array(64),D=new Uint8Array(64);function j(N,P,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);P[ot]=Ce<0?0:Ce>255?255:Ce}}a(j,"quantizeAndInverse"),w(T*_*8);for(var $,W,J=0;J<_;J++){var I=J<<3;for($=0;$<8;$++)k.push(new Uint8Array(T));for(var U=0;U<E;U++){j(S.blocks[J][U],D,M);var C=0,R=U<<3;for(W=0;W<8;W++){var O=k[I+W];for($=0;$<8;$++)O[R+$]=D[C++]}}}return k}a(f,"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 ae=S[E]<<8|S[E+1];return E+=2,ae}a(T,"readUint16");function M(){var ae=T(),Pe=S.subarray(E,E+ae-2);return E+=Pe.length,Pe}a(M,"readDataBlock");function D(ae){var Pe=1,Ge=1,ct,Ot;for(Ot in ae.components)ae.components.hasOwnProperty(Ot)&&(ct=ae.components[Ot],Pe<ct.h&&(Pe=ct.h),Ge<ct.v&&(Ge=ct.v));var Xe=Math.ceil(ae.samplesPerLine/8/Pe),cn=Math.ceil(ae.scanLines/8/Ge);for(Ot in ae.components)if(ae.components.hasOwnProperty(Ot)){ct=ae.components[Ot];var rn=Math.ceil(Math.ceil(ae.samplesPerLine/8)*ct.h/Pe),wn=Math.ceil(Math.ceil(ae.scanLines/8)*ct.v/Ge),jt=Xe*ct.h,Lr=cn*ct.v,Ur=Lr*jt,ms=[];w(Ur*256);for(var Ni=0;Ni<Lr;Ni++){for(var pr=[],gs=0;gs<jt;gs++)pr.push(new Int32Array(64));ms.push(pr)}ct.blocksPerLine=rn,ct.blocksPerColumn=wn,ct.blocks=ms}ae.maxH=Pe,ae.maxV=Ge,ae.mcusPerLine=Xe,ae.mcusPerColumn=cn}a(D,"prepareComponents");var j=null,$=null,W=null,J,I,U=[],C=[],R=[],O=[],N=T(),P=-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=M();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(),J={},J.extended=N===65473,J.progressive=N===65474,J.precision=S[E++],J.scanLines=T(),J.samplesPerLine=T(),J.components={},J.componentsOrder=[];var ue=J.scanLines*J.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");J.componentsOrder.push(Ve),J.components[Ve]={h:ke,v:oe,quantizationIdx:Le},E+=3}D(J),C.push(J);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=J.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++],vn=S[E++],Vt=h(S,E,J,yt,I,Gt,ht,vn>>4,vn&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(P!==-1)throw new Error(`first unknown JPEG marker at offset ${P.toString(16)}, second unknown JPEG marker ${N.toString(16)} at offset ${(E-1).toString(16)}`);P=E-1;let ae=T();if(S[E+ae-2]===255){E+=ae-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=J.samplesPerLine,this.height=J.scanLines,this.jfif=j,this.adobe=$,this.components=[];for(var G=0;G<J.componentsOrder.length;G++){var Oe=J.components[J.componentsOrder[G]];this.components.push({lines:f(J,Oe),scaleX:Oe.h/J.maxH,scaleY:Oe.v/J.maxV})}},"parse"),getData:a(function(S,k){var E=this.width/S,_=this.height/k,T,M,D,j,$,W,J,I,U,C,R=0,O,N,P,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],M=this.components[1],C=0;C<k;C++)for($=T.lines[0|C*T.scaleY*_],W=M.lines[0|C*M.scaleY*_],U=0;U<S;U++)O=$[0|U*T.scaleX*E],_e[R++]=O,O=W[0|U*M.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],M=this.components[1],D=this.components[2],C=0;C<k;C++)for($=T.lines[0|C*T.scaleY*_],W=M.lines[0|C*M.scaleY*_],J=D.lines[0|C*D.scaleY*_],U=0;U<S;U++)le?(O=$[0|U*T.scaleX*E],N=W[0|U*M.scaleX*E],P=J[0|U*D.scaleX*E],ne=g(O+1.402*(P-128)),ge=g(O-.3441363*(N-128)-.71413636*(P-128)),we=g(O+1.772*(N-128))):(ne=$[0|U*T.scaleX*E],ge=W[0|U*M.scaleX*E],we=J[0|U*D.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],M=this.components[1],D=this.components[2],j=this.components[3],C=0;C<k;C++)for($=T.lines[0|C*T.scaleY*_],W=M.lines[0|C*M.scaleY*_],J=D.lines[0|C*D.scaleY*_],I=j.lines[0|C*j.scaleY*_],U=0;U<S;U++)le?(O=$[0|U*T.scaleX*E],N=W[0|U*M.scaleX*E],P=J[0|U*D.scaleX*E],G=I[0|U*j.scaleX*E],X=255-g(O+1.402*(P-128)),Q=255-g(O-.3441363*(N-128)-.71413636*(P-128)),z=255-g(O+1.772*(N-128))):(X=$[0|U*T.scaleX*E],Q=W[0|U*M.scaleX*E],z=J[0|U*D.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,M=this.getData(E,_),D=0,j=0,$,W,J,I,U,C,R,O,N;switch(this.components.length){case 1:for(W=0;W<_;W++)for($=0;$<E;$++)J=M[D++],T[j++]=J,T[j++]=J,T[j++]=J,k&&(T[j++]=255);break;case 3:for(W=0;W<_;W++)for($=0;$<E;$++)R=M[D++],O=M[D++],N=M[D++],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=M[D++],C=M[D++],J=M[D++],I=M[D++],R=255-g(U*(1-I/255)+I),O=255-g(C*(1-I/255)+I),N=255-g(J*(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 fJ<"u"?fJ.exports=pTe:typeof window<"u"&&(window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=pTe);function pTe(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 pJ;s.opts=r,pJ.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),s.parse(i);var o=r.formatAsRGBA?4:3,c=s.width*s.height*o;try{pJ.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(pTe,"decode")});var mTe=be((mUn,hTe)=>{var kTt=dTe(),ETt=fTe();hTe.exports={encode:kTt,decode:ETt}});function G4e(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 yn({...e,content:s})}var K4e=ce(()=>{rs();a(G4e,"offloadMessageImages")});function Z4e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Y4e(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0&&!Object.is(e,-0)}var NR,aX=ce(()=>{K4e();a(Z4e,"isRecord");a(Y4e,"isIndex");NR={type:"image/offload",project(e,t){let n=e.data;if(!Z4e(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(!Z4e(s)||Object.keys(s).length!==2||!Y4e(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(!Y4e(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,G4e(u,s.imageIndexes))}return r}}});var KR,mAe=ce(()=>{aX();KR=[NR]});async function SAe(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,...d7(o)]}}function zX(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 Pr(`session source headers conflict for session "${e.id}"`,"SESSION_QUERY_SOURCE_CONFLICT")}function ZR(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 HX(e){return{header:e.header,events:e.snapshotEvents()}}function YR(e,t){return e.map(n=>t.get(n))}async function WX(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 Pr(`session persistence listing failed: ${KX(n)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:n})}}async function gAe(e,t,n){try{return await SAe(e,t,n)}catch(r){throw n?.aborted&&n.throwIfAborted(),r instanceof Error&&r.name==="SessionPersistenceCorruptionError"?new Pr(`stored session "${t}" is corrupt: ${KX(r)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:r}):new Pr(`failed to read stored session "${t}": ${KX(r)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:r})}}function yAe(e){return{header:structuredClone(e.header),inheritedEventCount:e.inheritedEventCount,events:e.snapshotEvents().map(t=>structuredClone(t))}}function CIt(e,t){return t.header.createdAt-e.header.createdAt||e.header.id.localeCompare(t.header.id)}function JR(e){return new Pr(`session "${e}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND")}function KX(e){return e instanceof Error?e.message:"unknown error"}function hT(e){if(e?.aborted===!0)throw new Pr("session observation was aborted","SESSION_QUERY_ABORTED",{cause:e.reason})}function vAe(e,t){return wAe(t,"SessionPersistenceNotFoundError")?ZX(e,t):wAe(t,"SessionPersistenceCorruptionError")?new Pr(`stored session "${e}" is corrupt: ${t.message}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:t}):new Pr(`failed to observe session "${e}": ${XR(t)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:t})}function ZX(e,t){return new Pr(`session "${e}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND",t===void 0?void 0:{cause:t})}function XR(e){return e instanceof Error?e.message:"unknown error"}function wAe(e,t){return e instanceof Error&&e.name===t}function OIt(e){switch(e.type){case"user/message":return VX(e.data.content);case"assistant/message":return VX(e.data.message.content);case"tool/call":return mT([e.data.name,e.data.arguments]);case"tool/result":return mT([VX(e.data.message.content),e.data.error?.name??"",e.data.error?.code??""]);case"todo/write":return mT(e.data.todos.flatMap(t=>[t.status,t.content]));case"turn/end":return $It(e.data.reason);case"turn/start":case"step/start":case"step/end":case"assistant/attempt":case"request/header":return"";default:return""}}function $It(e){switch(e.kind){case"error":return mT(["error",e.error.message]);case"aborted":return"aborted";case"max-tokens":case"interrupted":return e.kind;case"completed":return"";default:return""}}function VX(e){return mT(e.flatMap(NIt))}function NIt(e){switch(e.type){case"text":return[e.text];case"reasoning":return[];case"tool-call":return[e.name,e.arguments];default:return[]}}function mT(e){return e.map(t=>t.trim()).filter(Boolean).join(`
157
157
  `)}function JX(e,t){let n=PIt(t),r=[];for(let i of t){let s=OIt(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 PIt(e){let t;try{t=YL(e,KR)}catch(r){throw new Pr(`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 XX(e,t=[]){let n=t.map(MIt);return e.filter(r=>n.every(i=>i(r)))}function n5(e,t=[]){let n=t.map(LIt);return e.filter(r=>n.every(i=>i(r)))}function QX(e){return kAe(e),e.map(t=>{switch(t.kind){case"id":return{kind:t.kind,values:e5(t.kind,t.values)};case"cwd":return{kind:t.kind,values:bAe(t.kind,t.values)};case"created-at":return EAe(t.kind,t);case"parent":return{kind:t.kind,values:bAe(t.kind,t.values)};case"availability":{let n=e5(t.kind,t.values);return s5(t.kind,n,["live","persisted"]),{kind:t.kind,values:n}}default:return i5(t)}})}function r5(e){return kAe(e),e.map(t=>{switch(t.kind){case"seq":case"time":return EAe(t.kind,t);case"type":return{kind:t.kind,values:e5(t.kind,t.values)};case"surface":{let n=e5(t.kind,t.values);return s5(t.kind,n,["current","shadowed","log-only"]),{kind:t.kind,values:n}}case"text":if(typeof t.text!="string")throw Lx("text filter text must be a string");return{kind:t.kind,text:t.text};default:return i5(t)}})}function DIt(e){let t=e.trim();if(t.length===0)throw new Pr("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 MIt(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=t5(e.kind,e);return n=>YX(n.header.createdAt,t)}case"parent":return t=>e.values.includes(t.header.parentSession??null);case"availability":return s5(e.kind,e.values,["live","persisted"]),t=>e.values.some(n=>n==="live"?t.live:t.persisted);default:return i5(e)}}function LIt(e){switch(e.kind){case"seq":{let t=t5(e.kind,e);return n=>YX(n.seq,t)}case"time":{let t=t5(e.kind,e);return n=>YX(n.time,t)}case"type":return t=>e.values.includes(t.type);case"surface":return s5(e.kind,e.values,["current","shadowed","log-only"]),t=>e.values.includes(t.surface);case"text":{let t=DIt(e.text);return n=>t.test(n.text)}default:return i5(e)}}function e5(e,t){if(!_Ae(t)||t.some(n=>typeof n!="string"))throw Lx(`${e} filter values must be an array of strings`);return[...t]}function kAe(e){if(!Array.isArray(e))throw Lx("filters must be an array")}function bAe(e,t){if(!_Ae(t)||t.some(n=>n!==null&&typeof n!="string"))throw Lx(`${e} filter values must be an array of strings or null`);return[...t]}function EAe(e,t){let n={kind:e,...t.from===void 0?{}:{from:t.from},...t.to===void 0?{}:{to:t.to}};return t5(e,n),n}function i5(e){let t=e.kind;throw Lx(`unknown filter kind ${typeof t=="string"?`"${t}"`:"(missing)"}`)}function s5(e,t,n){for(let r of t)if(!n.includes(r))throw new Pr(`session ${e} filter contains unknown value "${r}"`,"SESSION_QUERY_INVALID_FILTER")}function t5(e,t){if(t.from!==void 0&&!Number.isFinite(t.from))throw GX(e,"from must be finite");if(t.to!==void 0&&!Number.isFinite(t.to))throw GX(e,"to must be finite");if(t.from!==void 0&&t.to!==void 0&&t.from>t.to)throw GX(e,"from must be less than or equal to to");return t}function YX(e,t){return(t.from===void 0||e>=t.from)&&(t.to===void 0||e<=t.to)}function GX(e,t){return Lx(`${e} filter ${t}`)}function Lx(e){return new Pr(`session ${e}`,"SESSION_QUERY_INVALID_FILTER")}function _Ae(e){return Array.isArray(e)}function jIt(e,t){return eQ(e,t).records}function FIt(e,t){return eQ(e,t).currentSeqs.map(n=>{let r=t[n];if(r===void 0||r.seq!==n||!wg(r))throw new Pr(`invalid session surface: current node ${n} is not a surface event`,"SESSION_QUERY_INVALID_SURFACE");return Vk(r)})}function qIt(e,t,n){let r=t[n];if(r===void 0||r.seq!==n)throw new Pr(`session "${e}" has no event at seq ${n}`,"SESSION_QUERY_EVENT_NOT_FOUND");let i=eQ(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||xAe(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:[...xAe(r)],derivedEventSeqs:c}}function UIt(e,t){let n=new Map(e.map(p=>[p.header.id,p])),r=n.get(t);if(r===void 0)throw new Pr(`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 Pr(`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 h=p.header.parentSession;if(h===void 0)continue;let f=l.get(h)??[];f.push(p),l.set(h,f)}for(let p of l.values())p.sort((h,f)=>h.header.createdAt-f.header.createdAt||h.header.id.localeCompare(f.header.id));let u=BIt(l,t),d={target:QR(r),ancestors:i.map(QR),descendants:u};return o!==void 0?{...d,complete:!1,unresolvedParentId:o}:{...d,complete:!0,root:QR(i.at(-1)??r)}}function eQ(e,t){let n;try{n=YL(t,KR)}catch(o){throw new Pr(`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 xAe(e){return e.sourceEventSeqs??[]}function BIt(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:QR(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 QR(e){return{...e,header:structuredClone(e.header)}}var Pr,IIt,RIt,TAe,tQ=ce(()=>{mAe();Yn();Hs();Fg();kr();Pr=class extends zr{static{a(this,"SessionQueryError")}constructor(e,t,n){super(e,t,n)}};a(SAe,"readColdSessionLog");a(zX,"assertSessionHeadersCompatible");IIt=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 WX(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&&zX(i.header,s.header),r.set(i.id,{header:structuredClone(i.header),live:!0,persisted:s!==void 0})}return[...r.values()].sort(CIt)}async load(e,t){t?.throwIfAborted();let n=this._ctx.sessions.get(e);if(n!==void 0){let l=yAe(n);return t?.throwIfAborted(),l}let r=this._persistence;if(r===void 0)throw JR(e);let i=(await WX(r,t)).find(l=>l.id===e);if(t?.throwIfAborted(),i===void 0)throw JR(e);let s=await gAe(r,e,t);t?.throwIfAborted();let o=this._ctx.sessions.get(e);if(o!==void 0){let l=yAe(o);return t?.throwIfAborted(),l}zX(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,ZR(g,HX(y),t,n))}if(s.length===0)return YR(r,i);let o=this._persistence;if(o===void 0){for(let g of s)i.set(g,{sessionId:g,status:"rejected",reason:JR(g)});return YR(r,i)}let c;try{c=await WX(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 YR(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:JR(g)}:ZR(g,HX(v),t,n));return}try{n?.throwIfAborted();let v=await gAe(o,g,n);n?.throwIfAborted();let w=this._ctx.sessions.get(g);if(w!==void 0){i.set(g,ZR(g,HX(w),t,n));return}zX(v.header,y),i.set(g,ZR(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"),h=Math.min(this._persistedReadConcurrency,s.length),f=await Promise.allSettled(Array.from({length:h},()=>p()));n?.aborted&&n.throwIfAborted();for(let g of f)if(g.status==="rejected")throw g.reason;return n?.throwIfAborted(),YR(r,i)}};a(ZR,"projectSource");a(HX,"sourceLive");a(YR,"orderedResults");a(WX,"listPersisted");a(gAe,"inspectPersisted");a(yAe,"snapshotLive");a(CIt,"compareSessions");a(JR,"notFound$1");a(KX,"errorMessage$1");RIt=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(;;){hT(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 ZX(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);hT(n);let p=this.ctx.sessions.get(e);if(p!==void 0)return this.live(p,r);let h=d.events,f;try{f=this.ctx.sessions.prepare(e,{seed:h,meta:structuredClone(d.header),inheritedEventCount:d.inheritedEventCount,eventState:d.eventState})}catch(g){if(this.ctx.sessions.get(e)!==void 0)continue;throw new Pr(`stored session "${e}" is corrupt: ${XR(g)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:g})}l={persistenceIdentity:s.identity,revision:o.revision,session:f,events:Object.freeze(h),refs:0},this.store(e,l)}let u;try{u=r==="none"?void 0:this.preparedProjections(l)}catch(d){throw new Pr(`failed to project session "${e}": ${XR(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 hT(n),vAe(t,i)}if(hT(n),r===void 0)throw ZX(t);if(r.header.id!==t)throw new Pr(`session persistence returned "${r.header.id}" for "${t}"`,"SESSION_QUERY_SOURCE_CONFLICT");return r}async loadSource(e,t,n){try{return await SAe(e,t,n)}catch(r){throw hT(n),vAe(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 Pr(`failed to project session "${e.id}": ${XR(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(An(0),n),r},cursor:n===0?-1:ln(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,An(0)):n.hydratePrepared(e.session,e.events)}};a(hT,"throwIfObservationAborted");a(vAe,"mapPersistenceFailure");a(ZX,"notFound");a(XR,"errorMessage");a(wAe,"hasErrorName");a(OIt,"extractSessionEventText");a($It,"turnEndText");a(VX,"contentText");a(NIt,"blockText");a(mT,"joinText");a(JX,"buildSessionEventSearchDocuments");a(PIt,"classifySurface");a(XX,"filterSessionResults");a(n5,"filterSessionEventDocuments");a(QX,"materializeSessionResultFilters");a(r5,"materializeSessionEventResultFilters");a(DIt,"compileSessionTextFilter");a(MIt,"sessionPredicate");a(LIt,"eventPredicate");a(e5,"copyStrings");a(kAe,"assertArray");a(bAe,"copyNullableStrings");a(EAe,"copyRange");a(i5,"unknownFilter");a(s5,"assertAllowedValues");a(t5,"validateRange");a(YX,"matchesRange");a(GX,"invalidRange");a(Lx,"invalidFilter");a(_Ae,"isRuntimeArray");a(jIt,"eventRecords");a(FIt,"currentSurfaceEvents");a(qIt,"traceEvent");a(UIt,"traceSession");a(eQ,"analyzeEventLog");a(xAe,"eventSources");a(BIt,"buildDescendants");a(QR,"cloneRecord");TAe=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 Pr("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 Pr("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 Pr("session-query: preparedSessionCacheSize must be a positive safe integer","SESSION_QUERY_INVALID_CONFIG");this._corpus=new IIt(e,n),this._observations=new RIt(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 D0.create(e,t.events,t.header,t.inheritedEventCount,KR),{session:structuredClone(t.header),inheritedEventCount:t.inheritedEventCount,events:t.events.map(Vk)}}async filterSessions(e,t){let n=QX(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=jg(n.events);return{session:structuredClone(n.header),...r===void 0?{}:{title:r}}},t)}async listEvents(e){return jIt(e,(await this._corpus.load(e)).events)}async filterEvents(e,t){let n=r5(t);return this._filterEvents(e,n)}async _filterSessions(e,t){return XX(await this._corpus.listSessions(t),e)}async _filterEvents(e,t){return n5(JX(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:FIt(e,t.events)}}async traceSession(e,t){let n=await this._corpus.listSessions(t);return t?.throwIfAborted(),UIt(n,e)}async traceEvent(e,t){let n=await this._corpus.load(e.sessionId,t);return t?.throwIfAborted(),{session:n.header,...qIt(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 Pr(`session "${e}" has no event at seq ${t}`,"SESSION_QUERY_EVENT_NOT_FOUND");let c=ln(Math.max(0,t-n)),l=ln(Math.min(s.events.length-1,t+r)),u=Vk(o),d=s.events.slice(c,l+1).map(p=>p===o?u:Vk(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 Pr(`${e} must be an integer between 0 and ${this._readWindowMax}`,"SESSION_QUERY_INVALID_WINDOW");return t}}});var jx=be((nWn,jAe)=>{"use strict";jAe.exports=Vy;Vy.CAPTURING_PHASE=1;Vy.AT_TARGET=2;Vy.BUBBLING_PHASE=3;function Vy(e,t){if(this.type="",this.target=null,this.currentTarget=null,this.eventPhase=Vy.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(Vy,"Event");Vy.prototype=Object.create(Object.prototype,{constructor:{value:Vy},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 cQ=be((iWn,qAe)=>{"use strict";var FAe=jx();qAe.exports=aQ;function aQ(){FAe.call(this),this.view=null,this.detail=0}a(aQ,"UIEvent");aQ.prototype=Object.create(FAe.prototype,{constructor:{value:aQ},initUIEvent:{value:a(function(e,t,n,r,i){this.initEvent(e,t,n),this.view=r,this.detail=i},"value")}})});var uQ=be((oWn,BAe)=>{"use strict";var UAe=cQ();BAe.exports=lQ;function lQ(){UAe.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(lQ,"MouseEvent");lQ.prototype=Object.create(UAe.prototype,{constructor:{value:lQ},initMouseEvent:{value:a(function(e,t,n,r,i,s,o,c,l,u,d,p,h,f,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=h,this.button=f,f){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 d5=be((cWn,HAe)=>{"use strict";HAe.exports=u5;var s8t=1,o8t=3,a8t=4,c8t=5,l8t=7,u8t=8,d8t=9,p8t=11,f8t=12,h8t=13,m8t=14,g8t=15,y8t=17,v8t=18,w8t=19,b8t=20,x8t=21,S8t=22,k8t=23,E8t=24,_8t=25,T8t=[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"],A8t=[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."],zAe={INDEX_SIZE_ERR:s8t,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:o8t,WRONG_DOCUMENT_ERR:a8t,INVALID_CHARACTER_ERR:c8t,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:l8t,NOT_FOUND_ERR:u8t,NOT_SUPPORTED_ERR:d8t,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:p8t,SYNTAX_ERR:f8t,INVALID_MODIFICATION_ERR:h8t,NAMESPACE_ERR:m8t,INVALID_ACCESS_ERR:g8t,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:y8t,SECURITY_ERR:v8t,NETWORK_ERR:w8t,ABORT_ERR:b8t,URL_MISMATCH_ERR:x8t,QUOTA_EXCEEDED_ERR:S8t,TIMEOUT_ERR:k8t,INVALID_NODE_TYPE_ERR:E8t,DATA_CLONE_ERR:_8t};function u5(e){Error.call(this),Error.captureStackTrace(this,this.constructor),this.code=e,this.message=A8t[e],this.name=T8t[e]}a(u5,"DOMException");u5.prototype.__proto__=Error.prototype;for(l5 in zAe)dQ={value:zAe[l5]},Object.defineProperty(u5,l5,dQ),Object.defineProperty(u5.prototype,l5,dQ);var dQ,l5});var p5=be(WAe=>{WAe.isApiWritable=!globalThis.__domino_frozen__});var vo=be(ji=>{"use strict";var yo=d5(),Po=yo,I8t=p5().isApiWritable;ji.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"};ji.IndexSizeError=function(){throw new yo(Po.INDEX_SIZE_ERR)};ji.HierarchyRequestError=function(){throw new yo(Po.HIERARCHY_REQUEST_ERR)};ji.WrongDocumentError=function(){throw new yo(Po.WRONG_DOCUMENT_ERR)};ji.InvalidCharacterError=function(){throw new yo(Po.INVALID_CHARACTER_ERR)};ji.NoModificationAllowedError=function(){throw new yo(Po.NO_MODIFICATION_ALLOWED_ERR)};ji.NotFoundError=function(){throw new yo(Po.NOT_FOUND_ERR)};ji.NotSupportedError=function(){throw new yo(Po.NOT_SUPPORTED_ERR)};ji.InvalidStateError=function(){throw new yo(Po.INVALID_STATE_ERR)};ji.SyntaxError=function(){throw new yo(Po.SYNTAX_ERR)};ji.InvalidModificationError=function(){throw new yo(Po.INVALID_MODIFICATION_ERR)};ji.NamespaceError=function(){throw new yo(Po.NAMESPACE_ERR)};ji.InvalidAccessError=function(){throw new yo(Po.INVALID_ACCESS_ERR)};ji.TypeMismatchError=function(){throw new yo(Po.TYPE_MISMATCH_ERR)};ji.SecurityError=function(){throw new yo(Po.SECURITY_ERR)};ji.NetworkError=function(){throw new yo(Po.NETWORK_ERR)};ji.AbortError=function(){throw new yo(Po.ABORT_ERR)};ji.UrlMismatchError=function(){throw new yo(Po.URL_MISMATCH_ERR)};ji.QuotaExceededError=function(){throw new yo(Po.QUOTA_EXCEEDED_ERR)};ji.TimeoutError=function(){throw new yo(Po.TIMEOUT_ERR)};ji.InvalidNodeTypeError=function(){throw new yo(Po.INVALID_NODE_TYPE_ERR)};ji.DataCloneError=function(){throw new yo(Po.DATA_CLONE_ERR)};ji.nyi=function(){throw new Error("NotYetImplemented")};ji.shouldOverride=function(){throw new Error("Abstract function; should be overriding in subclass.")};ji.assert=function(e,t){if(!e)throw new Error("Assertion failed: "+(t||"")+`
158
158
  `+new Error().stack)};ji.expose=function(e,t){for(var n in e)Object.defineProperty(t.prototype,n,{value:e[n],writable:I8t})};ji.merge=function(e,t){for(var n in t)e[n]=t[n]};ji.documentOrder=function(e,t){return 3-(e.compareDocumentPosition(t)&6)};ji.toASCIILowerCase=function(e){return e.replace(/[A-Z]+/g,function(t){return t.toLowerCase()})};ji.toASCIIUpperCase=function(e){return e.replace(/[a-z]+/g,function(t){return t.toUpperCase()})}});var pQ=be((pWn,GAe)=>{"use strict";var Gy=jx(),C8t=uQ(),R8t=vo();GAe.exports=VAe;function VAe(){}a(VAe,"EventTarget");VAe.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,h=d.eventPhase;if(d.currentTarget=u,h!==Gy.CAPTURING_PHASE&&u._handlers&&u._handlers[p]){var f=u._handlers[p],g;if(typeof f=="function")g=f.call(d.currentTarget,d);else{var y=f.handleEvent;if(typeof y!="function")throw new TypeError("handleEvent property of event handler object isnot a function.");g=y.call(f,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(!(h===Gy.CAPTURING_PHASE&&!S.capture||h===Gy.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)&&R8t.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=Gy.CAPTURING_PHASE;for(var o=i.length-1;o>=0&&(r(i[o],t),!t._propagationStopped);o--);if(t._propagationStopped||(t.eventPhase=Gy.AT_TARGET,r(this,t)),t.bubbles&&!t._propagationStopped){t.eventPhase=Gy.BUBBLING_PHASE;for(var c=0,l=i.length;c<l&&(r(i[c],t),!t._propagationStopped);c++);}if(t._dispatching=!1,t.eventPhase=Gy.AT_TARGET,t.currentTarget=null,n&&!t.defaultPrevented&&t instanceof C8t)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 fQ=be((hWn,KAe)=>{"use strict";var mm=vo(),md=KAe.exports={valid:a(function(e){return mm.assert(e,"list falsy"),mm.assert(e._previousSibling,"previous falsy"),mm.assert(e._nextSibling,"next falsy"),!0},"valid"),insertBefore:a(function(e,t){mm.assert(md.valid(e)&&md.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,mm.assert(md.valid(e)&&md.valid(t))},"insertBefore"),replace:a(function(e,t){mm.assert(md.valid(e)&&(t===null||md.valid(t))),t!==null&&md.insertBefore(t,e),md.remove(e),mm.assert(md.valid(e)&&(t===null||md.valid(t)))},"replace"),remove:a(function(e){mm.assert(md.valid(e));var t=e._previousSibling;if(t!==e){var n=e._nextSibling;t._nextSibling=n,n._previousSibling=t,e._previousSibling=e._nextSibling=e,mm.assert(md.valid(e))}},"remove")}});var hQ=be((gWn,n7e)=>{"use strict";n7e.exports={serializeOne:L8t,\u0275escapeMatchingClosingTag:QAe,\u0275escapeClosingCommentTag:e7e,\u0275escapeProcessingInstructionContent:t7e};var XAe=vo(),Ky=XAe.NAMESPACE,ZAe={STYLE:!0,SCRIPT:!0,XMP:!0,IFRAME:!0,NOEMBED:!0,NOFRAMES:!0,PLAINTEXT:!0},O8t={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},$8t={},YAe=/[&<>\u00A0]/g,JAe=/[&"<>\u00A0]/g;function N8t(e){return YAe.test(e)?e.replace(YAe,t=>{switch(t){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case"\xA0":return"&nbsp;"}}):e}a(N8t,"escape");function P8t(e){return JAe.test(e)?e.replace(JAe,t=>{switch(t){case"<":return"&lt;";case">":return"&gt;";case"&":return"&amp;";case'"':return"&quot;";case"\xA0":return"&nbsp;"}}):e}a(P8t,"escapeAttr");function D8t(e){var t=e.namespaceURI;return t?t===Ky.XML?"xml:"+e.localName:t===Ky.XLINK?"xlink:"+e.localName:t===Ky.XMLNS?e.localName==="xmlns"?"xmlns":"xmlns:"+e.localName:e.name:e.localName}a(D8t,"attrname");function QAe(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(QAe,"escapeMatchingClosingTag");var M8t=/--!?>/;function e7e(e){return M8t.test(e)?e.replace(/(--\!?)>/g,"$1&gt;"):e}a(e7e,"escapeClosingCommentTag");function t7e(e){return e.includes(">")?e.replaceAll(">","&gt;"):e}a(t7e,"escapeProcessingInstructionContent");function L8t(e,t){var n="";switch(e.nodeType){case 1:var r=e.namespaceURI,i=r===Ky.HTML,s=i||r===Ky.SVG||r===Ky.MATHML?e.localName:e.tagName;n+="<"+s;for(var o=0,c=e._numattrs;o<c;o++){var l=e._attr(o);n+=" "+D8t(l),l.value!==void 0&&(n+='="'+P8t(l.value)+'"')}if(n+=">",!(i&&O8t[s])){var u=e.serialize();ZAe[s.toUpperCase()]&&(u=QAe(u,s)),i&&$8t[s]&&u.charAt(0)===`
@@ -5136,10 +5136,11 @@ Example:
5136
5136
  UNION ALL
5137
5137
  SELECT w.level + 1, n.inode, n.type, n.mode, n.mtime, n.size, n.link_target
5138
5138
  FROM walk w
5139
- JOIN segs s ON s.level = w.level
5140
- JOIN vfs_dirents d ON d.parent_inode = w.inode AND d.name = s.name
5139
+ CROSS JOIN segs s
5140
+ CROSS JOIN vfs_dirents d
5141
5141
  JOIN vfs_nodes n ON n.inode = d.child_inode
5142
- WHERE w.type = 'dir'
5142
+ WHERE s.level = w.level AND d.parent_inode = w.inode AND d.name = s.name
5143
+ AND w.type = 'dir'
5143
5144
  )
5144
5145
  SELECT level, inode, type, mode, mtime, size, link_target
5145
5146
  FROM walk
@@ -5839,7 +5840,7 @@ The web search request used endpoint ${JSON.stringify(e)}. Search endpoint confi
5839
5840
  .error { padding: .75rem; border-radius: .5rem; background: #461d2b; color: #ffd6df; }
5840
5841
  .hint { margin: 1.5rem 0 0; font-size: .875rem; }
5841
5842
  code { padding: .1rem .3rem; border-radius: .3rem; background: #0c1222; color: #edf2ff; }
5842
- `}a(ODe,"pageStyles");h6();var Iie="enabled",Cie=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")}),A4=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")}),Rie=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===Iie?"available":"needs-binding","probe")}),UJt=Object.freeze([Rie,A4,Cie]);function Oie(e,t=UJt){return t.filter(n=>n.probe(e)==="available")}a(Oie,"availableEdgeRuntimeProviders");function $ie(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($ie,"resolveEdgeRuntimeSelection");function U$(e){let t=Oie(e),{bash:n,container:r}=$ie(t);return t.find(i=>i.id===(r??n)).shell}a(U$,"resolveEdgeRuntimeShell");function BJt(){return"dsh-edge@0.21.0-alpha.2/direct"}a(BJt,"resolveEdgeDeploymentId");function I4(e){return{baseURL:AY(e.DEEPSEEK_BASE_URL),maxTokens:RY(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Oy(e.DEEPSEEK_MODEL),reasoningEffort:IY(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:J5(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:CY(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:U1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(I4,"resolveEdgeDeploymentConfig");function zJt(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(zJt,"edgeDeploymentApiKeyConfigured");function HJt(e){let t=AY(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(HJt,"projectedEdgeBaseURL");function Nie(e,t){return{shell:U$(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:BJt(),apiKeyConfigured:zJt(e),baseURL:HJt(e.DEEPSEEK_BASE_URL),maxTokens:RY(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Oy(e.DEEPSEEK_MODEL),reasoningEffort:IY(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:J5(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:CY(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:U1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(Nie,"resolveEdgeDeploymentProfile");function B$(e){I4(e);let t=Nie(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:_y,upstreamVersion:oke,status:"ready"}}a(B$,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as emn}from"node:async_hooks";import{RpcTarget as WJt}from"cloudflare:workers";function VJt(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(VJt,"startHeartbeat");async function GJt(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(GJt,"probeComputerdHealth");var KJt="computer.internal",ZJt="/health",Pie="/api",YJt=8080,JJt=3e4,XJt=2e4,QJt=1,eXt=2e3,tXt=250,nXt=2e3;function rXt(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(rXt,"bearerMatches");var H$=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??KJt,containerPort:e.containerPort??YJt,connectTimeoutMs:e.connectTimeoutMs??JJt,heartbeatIntervalMs:e.heartbeatIntervalMs??XJt,restartAttempts:e.restartAttempts??QJt,healthProbeTimeoutMs:e.healthProbeTimeoutMs??eXt,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??tXt,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??nXt}}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 Cc(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 Cc(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=yD(o),l,u=new Promise(p=>{let h=!1,f=a(()=>{h||(h=!0,l?.(),p(),this.#c=void 0)},"onClose");o.addEventListener("close",f,{once:!0}),o.addEventListener("error",f,{once:!0}),c.onRpcBroken(f)});this.#e.heartbeatIntervalMs>0&&(l=VJt({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(wS),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(q3),i.delete(wS);let c=new Request(e,{headers:i});return this.#t.gateway.fetch(new Request(o,c))}if(new URL(e.url).pathname!==Pie)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${Pie} requires a websocket upgrade`,{status:400});if(!rXt(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 h=Math.min(n,Date.now()+c);if(await this.#m(e,h).then(()=>!0,f=>(d=f,!1)))return p;if(l<s)try{({runtimeId:p}=await e.restart({env:t,enableInternet:this.#t.mode==="direct"})),u++}catch(f){throw this.#a?.(f),this.#o(),new Cc(this.#d("restart",{attempt:l,maxAttempts:s,restarts:u,lastError:f}),{cause:f})}}throw this.#a?.(new Error("computerd never became healthy")),this.#o(),new Cc(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 GJt(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 iXt(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=${$De(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 Cc(`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:ZJt,api:Pie,healthTimeoutMs:r})})}catch(s){throw this.#a?.(s),this.#o(),new Cc(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${$De(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 Cc(`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 Cc(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#o()}}};function iXt(e){return new Promise(t=>setTimeout(t,e))}a(iXt,"sleep");function $De(e){return e instanceof Error?e.message:String(e)}a($De,"describeError");var NDe="computer:container-client-secret",sXt=16;function oXt(){let e=crypto.getRandomValues(new Uint8Array(sXt));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(oXt,"generate");var aXt=class{static{a(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(NDe);if(typeof e=="string"&&e.length>0)return e;let t=oXt();return await this.storage.put(NDe,t),t}},PDe="computer:container-launch-record";async function DDe(e){return{enableInternet:e.enableInternet,envDigest:await lXt(e.env)}}a(DDe,"launchRecordFor");function cXt(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}a(cXt,"sameLaunch");async function lXt(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(lXt,"digestEnv");var uXt=class{static{a(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(PDe)??null}async set(e){await this.storage.put(PDe,e)}},MDe=new WeakMap;function Lie(e){let t=MDe.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},MDe.set(e,t)),t}a(Lie,"getContainerLifecycle");function z$(e){return Lie(e).exit}a(z$,"containerExitInfo");function LDe(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}a(LDe,"formatExitReason");function jDe(e,t,n){let r=Lie(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>FDe(r,i,void 0,n),s=>FDe(r,i,s,n))}a(jDe,"installContainerMonitor");async function Die(e,t){let n=Lie(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}a(Die,"destroyContainerExpectingExit");async function FDe(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=LDe(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:LDe(c),exitedAt:Date.now()})}}a(FDe,"recordExit");var Mie="computer:container-runtime-identity",dXt=class{static{a(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(Mie)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(Mie,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(Mie)}},pXt=class extends WJt{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 dXt(e.storage),this.#n=new aXt(e.storage),this.#i=new uXt(e.storage)}async start(e){let t=z$(this.#t),n=await this.#n.ensure(),r=await DDe(e);if(t!==null){try{await Die(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||!cXt(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 Die(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return jDe(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await Die(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await DDe(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),jDe(this.#t,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:z$(this.#t)}}async exitInfo(){return z$(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=z$(this.#t);if(r!==null)throw new Cc(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function qDe(e){class t extends e{static{a(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new pXt(this.ctx)}}return t}a(qDe,"withWorkspaceContainer");var fXt={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function BDe(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=fXt[s]??s,l=e[c];if(l===void 0)return;let u=l[o];return typeof u=="function"?u:void 0}a(BDe,"resolve");function hXt(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}a(hXt,"errorResponse");async function jie(e,t,n,r,i){let s=BDe(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}a(jie,"callEdgeApi");async function zDe(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(BDe(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 jie(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 hXt(o,{code:"internal",message:String(l),details:{}})}}a(zDe,"dispatchEdgeApi");kr();Hs();Fg();import{DurableObject as tmn}from"cloudflare:workers";var W$=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 mXt(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 mXt(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(mXt,"untilAborted");import{WorkerEntrypoint as Mir}from"cloudflare:workers";var Gv=dl(HDe(),1);import{gunzipSync as ben}from"node:zlib";var C4=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,h=Date.now()+p,f=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(f[0],n,t,0,r);if(f[0].oldPos+1>=l&&g+1>=c)return o(this.buildValues(f[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=f[b-1],E=f[b+1];k&&(f[b-1]=void 0);let _=!1;if(E){let M=E.oldPos-b;_=E&&0<=M&&M<c}let T=k&&k.oldPos+1<l;if(!_&&!T){f[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;f[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()>h)return i(void 0);w()||b()},0)},"exec")();else for(;u<=d&&Date.now()<=h;){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(h,f){let g=r[u+f];return g.length>h.length?g:h}),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 Fie=class extends C4{static{a(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=yXt}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
5843
+ `}a(ODe,"pageStyles");h6();var Iie="enabled",Cie=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")}),A4=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")}),Rie=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===Iie?"available":"needs-binding","probe")}),UJt=Object.freeze([Rie,A4,Cie]);function Oie(e,t=UJt){return t.filter(n=>n.probe(e)==="available")}a(Oie,"availableEdgeRuntimeProviders");function $ie(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($ie,"resolveEdgeRuntimeSelection");function U$(e){let t=Oie(e),{bash:n,container:r}=$ie(t);return t.find(i=>i.id===(r??n)).shell}a(U$,"resolveEdgeRuntimeShell");function BJt(){return"dsh-edge@0.21.0/direct"}a(BJt,"resolveEdgeDeploymentId");function I4(e){return{baseURL:AY(e.DEEPSEEK_BASE_URL),maxTokens:RY(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Oy(e.DEEPSEEK_MODEL),reasoningEffort:IY(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:J5(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:CY(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:U1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(I4,"resolveEdgeDeploymentConfig");function zJt(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(zJt,"edgeDeploymentApiKeyConfigured");function HJt(e){let t=AY(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(HJt,"projectedEdgeBaseURL");function Nie(e,t){return{shell:U$(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:BJt(),apiKeyConfigured:zJt(e),baseURL:HJt(e.DEEPSEEK_BASE_URL),maxTokens:RY(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Oy(e.DEEPSEEK_MODEL),reasoningEffort:IY(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:J5(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:CY(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:U1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(Nie,"resolveEdgeDeploymentProfile");function B$(e){I4(e);let t=Nie(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:_y,upstreamVersion:oke,status:"ready"}}a(B$,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as emn}from"node:async_hooks";import{RpcTarget as WJt}from"cloudflare:workers";function VJt(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(VJt,"startHeartbeat");async function GJt(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(GJt,"probeComputerdHealth");var KJt="computer.internal",ZJt="/health",Pie="/api",YJt=8080,JJt=3e4,XJt=2e4,QJt=1,eXt=2e3,tXt=250,nXt=2e3;function rXt(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(rXt,"bearerMatches");var H$=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??KJt,containerPort:e.containerPort??YJt,connectTimeoutMs:e.connectTimeoutMs??JJt,heartbeatIntervalMs:e.heartbeatIntervalMs??XJt,restartAttempts:e.restartAttempts??QJt,healthProbeTimeoutMs:e.healthProbeTimeoutMs??eXt,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??tXt,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??nXt}}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 Cc(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 Cc(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=yD(o),l,u=new Promise(p=>{let h=!1,f=a(()=>{h||(h=!0,l?.(),p(),this.#c=void 0)},"onClose");o.addEventListener("close",f,{once:!0}),o.addEventListener("error",f,{once:!0}),c.onRpcBroken(f)});this.#e.heartbeatIntervalMs>0&&(l=VJt({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(wS),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(q3),i.delete(wS);let c=new Request(e,{headers:i});return this.#t.gateway.fetch(new Request(o,c))}if(new URL(e.url).pathname!==Pie)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${Pie} requires a websocket upgrade`,{status:400});if(!rXt(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 h=Math.min(n,Date.now()+c);if(await this.#m(e,h).then(()=>!0,f=>(d=f,!1)))return p;if(l<s)try{({runtimeId:p}=await e.restart({env:t,enableInternet:this.#t.mode==="direct"})),u++}catch(f){throw this.#a?.(f),this.#o(),new Cc(this.#d("restart",{attempt:l,maxAttempts:s,restarts:u,lastError:f}),{cause:f})}}throw this.#a?.(new Error("computerd never became healthy")),this.#o(),new Cc(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 GJt(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 iXt(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=${$De(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 Cc(`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:ZJt,api:Pie,healthTimeoutMs:r})})}catch(s){throw this.#a?.(s),this.#o(),new Cc(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${$De(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 Cc(`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 Cc(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#o()}}};function iXt(e){return new Promise(t=>setTimeout(t,e))}a(iXt,"sleep");function $De(e){return e instanceof Error?e.message:String(e)}a($De,"describeError");var NDe="computer:container-client-secret",sXt=16;function oXt(){let e=crypto.getRandomValues(new Uint8Array(sXt));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(oXt,"generate");var aXt=class{static{a(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(NDe);if(typeof e=="string"&&e.length>0)return e;let t=oXt();return await this.storage.put(NDe,t),t}},PDe="computer:container-launch-record";async function DDe(e){return{enableInternet:e.enableInternet,envDigest:await lXt(e.env)}}a(DDe,"launchRecordFor");function cXt(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}a(cXt,"sameLaunch");async function lXt(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(lXt,"digestEnv");var uXt=class{static{a(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(PDe)??null}async set(e){await this.storage.put(PDe,e)}},MDe=new WeakMap;function Lie(e){let t=MDe.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},MDe.set(e,t)),t}a(Lie,"getContainerLifecycle");function z$(e){return Lie(e).exit}a(z$,"containerExitInfo");function LDe(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}a(LDe,"formatExitReason");function jDe(e,t,n){let r=Lie(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>FDe(r,i,void 0,n),s=>FDe(r,i,s,n))}a(jDe,"installContainerMonitor");async function Die(e,t){let n=Lie(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}a(Die,"destroyContainerExpectingExit");async function FDe(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=LDe(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:LDe(c),exitedAt:Date.now()})}}a(FDe,"recordExit");var Mie="computer:container-runtime-identity",dXt=class{static{a(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(Mie)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(Mie,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(Mie)}},pXt=class extends WJt{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 dXt(e.storage),this.#n=new aXt(e.storage),this.#i=new uXt(e.storage)}async start(e){let t=z$(this.#t),n=await this.#n.ensure(),r=await DDe(e);if(t!==null){try{await Die(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||!cXt(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 Die(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return jDe(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await Die(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await DDe(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),jDe(this.#t,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:z$(this.#t)}}async exitInfo(){return z$(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=z$(this.#t);if(r!==null)throw new Cc(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function qDe(e){class t extends e{static{a(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new pXt(this.ctx)}}return t}a(qDe,"withWorkspaceContainer");var fXt={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function BDe(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=fXt[s]??s,l=e[c];if(l===void 0)return;let u=l[o];return typeof u=="function"?u:void 0}a(BDe,"resolve");function hXt(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}a(hXt,"errorResponse");async function jie(e,t,n,r,i){let s=BDe(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}a(jie,"callEdgeApi");async function zDe(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(BDe(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 jie(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 hXt(o,{code:"internal",message:String(l),details:{}})}}a(zDe,"dispatchEdgeApi");kr();Hs();Fg();import{DurableObject as tmn}from"cloudflare:workers";var W$=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 mXt(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 mXt(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(mXt,"untilAborted");import{WorkerEntrypoint as Mir}from"cloudflare:workers";var Gv=dl(HDe());import{gunzipSync as ben}from"node:zlib";var C4=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,h=Date.now()+p,f=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(f[0],n,t,0,r);if(f[0].oldPos+1>=l&&g+1>=c)return o(this.buildValues(f[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=f[b-1],E=f[b+1];k&&(f[b-1]=void 0);let _=!1;if(E){let M=E.oldPos-b;_=E&&0<=M&&M<c}let T=k&&k.oldPos+1<l;if(!_&&!T){f[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;f[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()>h)return i(void 0);w()||b()},0)},"exec")();else for(;u<=d&&Date.now()<=h;){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(h,f){let g=r[u+f];return g.length>h.length?g:h}),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 Fie=class extends C4{static{a(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=yXt}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
5843
5844
  `))&&(t=t.trim()),(!r.newlineIsToken||!n.includes(`
5844
5845
  `))&&(n=n.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
5845
5846
  `)&&(t=t.slice(0,-1)),n.endsWith(`
@@ -152,7 +152,7 @@ Known schemas:
152
152
  - `)}`,new Error(Ge)}let yt=`${l}/$ref`,it=Es(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"?y3(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=>y3(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`;Es(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=Es(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=Es(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=Es(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(Es(e,T,n,r,i,s,a,Be,c).valid){if(R!==void 0){let yt=Es(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(W!==void 0){let yt=Es(e,W,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.`}),B!==void 0&&Be.length>B&&ke.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${l}/maxProperties`,error:`Instance does not have at least ${B} properties.`}),A!==void 0){let it=`${l}/propertyNames`;for(let Ge in e){let mt=`${a}/${Ic(Ge)}`,Re=Es(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=Es(e,N[it],n,r,i,s,a,`${Ge}/${Ic(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=Es(e,mt,n,r,i,s,a,`${it}/${Ic(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(q!==void 0){let it=`${l}/properties`;for(let Ge in q){if(!(Ge in e))continue;let mt=`${a}/${Ic(Ge)}`,Re=Es(e[Ge],q[Ge],n,r,i,s,mt,`${it}/${Ic(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}/${Ic(kt)}`,pt=Es(e[kt],Re,n,r,i,s,zt,`${it}/${Ic(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&&Z!==void 0){let it=`${l}/additionalProperties`;for(let Ge in e){if(Le[Ge])continue;let mt=`${a}/${Ic(Ge)}`,Re=Es(e[Ge],Z,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}/${Ic(Ge)}`,Re=Es(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=Es(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(H!==void 0){let it=`${l}/items`;if(Array.isArray(H)){let Ge=Math.min(H.length,Be);for(;Le<Ge;Le++){let mt=Es(e[Le],H[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=Es(e[Le],H,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=Es(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=Es(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=Es(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)&&y3(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:G2e(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."}),G!==void 0&&NH[G]&&!NH[G](e)&&ke.push({instanceLocation:a,keyword:"format",keywordLocation:`${l}/format`,error:`String does not match format "${G}".`})}return{valid:ke.length===0,errors:ke}}var DH=oe(()=>{OH();m8();$H();h8();PH();o(Es,"validate")});var g8,Z2e=oe(()=>{m8();DH();g8=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=Zf(t)}validate(t){return Es(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,n){n&&(t={...t,$id:n}),Zf(t,this.lookup)}}});var K2e=oe(()=>{OH();m8();$H();h8();V2e();PH();DH();Z2e()});var y8,J2e=oe(()=>{K2e();y8=class{static{o(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let n=new g8(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 oa,v8=oe(()=>{"use strict";oa={probeTimeoutMs:3e4,callTimeoutMs:6e4,maxToolsPerServer:128,maxCatalogPages:10,maxCatalogBytes:131072,maxDescriptionLength:512,maxErrorMessageChars:300,maxPublicNameLength:64,maxInstructionsLength:1024,metaToolThreshold:20}});import{createHash as Udt}from"node:crypto";function Bdt(e){let t=e.replace(/[.*+?^${}()|[\]\\]/gu,n=>n==="*"?"\0":`\\${n}`);return new RegExp(`^${t.replaceAll("\0",".*")}$`)}function Y2e(e,t,n){let r=t??"read_only";return r==="allow_all"?"allow":r==="approve_all"?"ask":n===!0?"allow":n===!1?"ask":qdt.some(i=>Bdt(i).test(e))?"allow":"ask"}function Tp(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,oa.maxErrorMessageChars)}function X2e(e,t){let n=`mcp__${e}__${t}`,r=n.replace(/[^A-Za-z0-9_-]/gu,"_");if(r===n&&r.length<=oa.maxPublicNameLength)return r;let i=zdt(e,t),s=oa.maxPublicNameLength-i.length-1;return`${r.slice(0,s)}_${i}`}function zdt(e,t){return Udt("sha256").update(`${e}\0${t}`).digest("hex").slice(0,12)}function Q2e(e){if(!(e==null||typeof e!="object"))try{let t=JSON.parse(JSON.stringify(e));return mg(t),t}catch{return}}function Vdt(e){return Wdt.has(e)}function e3e(e){return e.type!=="image"||e.data===void 0||e.mimeType===void 0||!Vdt(e.mimeType)||!Hdt.test(e.data)?void 0:{data:Uint8Array.from(atob(e.data),n=>n.charCodeAt(0)),mediaType:e.mimeType}}function t3e(e){return e.some(t=>t.type==="image"&&t.data!==void 0)}function iS(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 qdt,Wdt,Hdt,w8=oe(()=>{"use strict";zs();v8();qdt=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];o(Bdt,"globToRegExp");o(Y2e,"evaluateMcpToolPolicy");o(Tp,"scrubMcpErrorMessage");o(X2e,"publicToolName");o(zdt,"hashSuffix");o(Q2e,"supportedOutputSchema");Wdt=new Set(["image/png","image/jpeg"]),Hdt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;o(Vdt,"isImageMediaType");o(e3e,"decodeImageBlock");o(t3e,"containsImage");o(iS,"mapMcpResultToContentBlocks")});var MH,n3e=oe(()=>{MH={name:"dsh-edge",version:"0.21.0-alpha.2",description:"Your DeepSeek Harness, anywhere \u2014 deploy a persistent personal coding agent to Cloudflare Workers in one command",author:"pawaca",license:"MIT",type:"module",bin:{"dsh-edge":"scripts/cli.mjs"},files:["dist","worker","scripts/*.d.mts","scripts/*.mjs","wrangler.jsonc","README.md","README.zh.md","LICENSE","THIRD_PARTY_NOTICES.md"],repository:{type:"git",url:"git+https://github.com/pawaca/dsh-edge.git",directory:"apps/dsh-edge"},homepage:"https://github.com/pawaca/dsh-edge#readme",bugs:{url:"https://github.com/pawaca/dsh-edge/issues"},keywords:["deepseek","deepseek-harness","ai-agents","byok","cloudflare-workers","durable-objects","self-hosted"],engines:{node:">=22.14.0"},publishConfig:{access:"public"},dshEdge:{upstreamVersion:"0.2.0-rc.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"},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-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-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-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-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-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 t0,r3e,i3e,sS=oe(()=>{"use strict";n3e();t0=MH.version,r3e=MH.dshEdge.upstreamVersion,i3e=`npx dsh-edge@${t0.includes("-")?"next":"latest"} upgrade`});function Ydt(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 Xdt(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function Kf(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 Zdt)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(Xdt(i)){let s=Ydt(i),a=s??i;for(let l of Kdt)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 Jdt)if(l.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function Qdt(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function s3e(e,t,n){Kf(e);let r=new f8(new URL(e),{requestInit:{headers:Qdt(t),signal:n},fetch:n0}),i=new d8({name:"dsh-edge",version:t0},{capabilities:{},jsonSchemaValidator:ept});return await i.connect(r),{client:i,close:o(async()=>{await i.close().catch(()=>{})},"close")}}async function a3e(e,t,n){let r=AbortSignal.timeout(oa.probeTimeoutMs),i;try{i=await s3e(t,n,r)}catch(l){throw new Error(Tp(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<oa.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>=oa.maxToolsPerServer)break;let v=X2e(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=Q2e(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>=oa.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,oa.maxInstructionsLength):void 0}}finally{await a()}}async function b8(e,t,n,r,i,s){let a=s??oa.callTimeoutMs,l=i?AbortSignal.any([i,AbortSignal.timeout(a)]):AbortSignal.timeout(a),c;try{c=await s3e(e,r,l)}catch(u){throw new Error(Tp(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(Tp(u instanceof Error?u.message:String(u)))}finally{await c.close()}}var Zdt,Kdt,Jdt,ept,n0,aS=oe(()=>{"use strict";c2e();B2e();J2e();w8();v8();sS();Zdt=[".internal",".local",".localhost"],Kdt=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],Jdt=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];o(Ydt,"extractMappedIPv4");o(Xdt,"isIpAddress");o(Kf,"assertSafeUrl");o(Qdt,"buildHeaders");ept=new y8,n0=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(s3e,"connectClient");o(a3e,"probe");o(b8,"callTool")});import{Buffer as tpt}from"node:buffer";function spt(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&ipt.has(e.code)}function l3e(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&rpt.has(e.code)}function c3e(e,t,n){let r=tpt.from(e,"base64");if(e.length===0&&t==="reject"||r.toString("base64")!==e)throw new ar(n==="INVALID_IMAGE_BASE64"?"Image upload is not canonical base64.":"File upload is not canonical base64.",n);return new Uint8Array(r)}function apt(e){return c3e(e,"reject","INVALID_IMAGE_BASE64")}function opt(e){return{data:apt(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function oS(e,t){return e.saveImages(t.map(opt))}async function lpt(e,t){return e.saveFile({data:c3e(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function u3e(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 LH(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 o3e,npt,rpt,ipt,ar,jH,Jf=oe(()=>{Vn();o3e=["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"],npt=[...o3e,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],rpt=new Set(o3e),ipt=new Set(npt),ar=class extends Error{static{o(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};o(spt,"isAttachmentError");o(l3e,"isImageAdmissionError");o(c3e,"decodeCanonicalBase64");o(apt,"decodeBase64");o(opt,"saveInput");o(oS,"admitEncodedImages");o(lpt,"admitEncodedFile");o(u3e,"requestImageDimensions");o(LH,"longEdgeDimensions");jH=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 ar("Image batch exceeds the configured image-count limit.","TOO_MANY_IMAGES");if(e.reduce((i,s)=>i+s.data.byteLength,0)>n)throw new ar("Image batch exceeds the configured aggregate image-byte limit.","IMAGES_TOO_LARGE");for(let i of e)if(!r.includes(i.mediaType))throw new ar(`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 oS(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 lpt(this,e)}isAttachmentError(e){return spt(e)}imageHostPath(e){}saveFile(e){return Promise.reject(new ar("The mounted attachment provider cannot store verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}saveFileStream(e){return Promise.reject(new ar("The mounted attachment provider cannot stream verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}async*readFileStream(e,t){t?.throwIfAborted(),await Promise.reject(new ar("The mounted attachment provider cannot read verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}fileHostPath(e){}readImageRequest(e,t,n){return n?.throwIfAborted(),Promise.reject(new ar("The mounted attachment provider cannot derive model-request images.","ATTACHMENT_PROJECTION_UNSUPPORTED"))}}});var S8={};kn(S8,{buildAuthorizationUrl:()=>ypt,discoverEndpoints:()=>mpt,exchangeCode:()=>vpt,isTokenExpired:()=>bpt,refreshToken:()=>wpt,registerClient:()=>gpt});function h3e(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 hpt(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 mpt(e){let t=AbortSignal.timeout(x8),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);Kf(i.href);let s=await n0(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);Kf(d.href);let p=await n0(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 gpt(e,t,n){let r=AbortSignal.timeout(x8);Kf(e);let i=await n0(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 ypt(e,t,n,r,i){let s=h3e(32),a=h3e(64),l=await hpt(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 vpt(e,t,n,r,i,s){let a=AbortSignal.timeout(x8),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),Kf(e);let c=await n0(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 m3e(await c.json())}async function wpt(e,t,n,r){let i=AbortSignal.timeout(x8),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),Kf(e);let a=await n0(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 m3e(await a.json())}function m3e(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 bpt(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var x8,k8=oe(()=>{"use strict";aS();x8=1e4;o(h3e,"randomString");o(hpt,"sha256Base64Url");o(mpt,"discoverEndpoints");o(gpt,"registerClient");o(ypt,"buildAuthorizationUrl");o(vpt,"exchangeCode");o(wpt,"refreshToken");o(m3e,"parseTokenResponse");o(bpt,"isTokenExpired")});var qn,k3e,lS=oe(()=>{Vn();vr();qn=class extends Lr{static{o(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},k3e=class extends St{static{o(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new qn("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function rV(e){return P8.test(e)}function D8(e){return e.invocation.modelInvocable}function w3(e){return e.invocation.userInvocable}function iV(e){let t=iht(e);return[`<skill_content name="${sht(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 qdt,Wdt,Hdt,w8=oe(()=>{"use strict";zs();v8();qdt=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];o(Bdt,"globToRegExp");o(Y2e,"evaluateMcpToolPolicy");o(Tp,"scrubMcpErrorMessage");o(X2e,"publicToolName");o(zdt,"hashSuffix");o(Q2e,"supportedOutputSchema");Wdt=new Set(["image/png","image/jpeg"]),Hdt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;o(Vdt,"isImageMediaType");o(e3e,"decodeImageBlock");o(t3e,"containsImage");o(iS,"mapMcpResultToContentBlocks")});var MH,n3e=oe(()=>{MH={name:"dsh-edge",version:"0.21.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"},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-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-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-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-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-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 t0,r3e,i3e,sS=oe(()=>{"use strict";n3e();t0=MH.version,r3e=MH.dshEdge.upstreamVersion,i3e=`npx dsh-edge@${t0.includes("-")?"next":"latest"} upgrade`});function Ydt(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 Xdt(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function Kf(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 Zdt)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(Xdt(i)){let s=Ydt(i),a=s??i;for(let l of Kdt)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 Jdt)if(l.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function Qdt(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function s3e(e,t,n){Kf(e);let r=new f8(new URL(e),{requestInit:{headers:Qdt(t),signal:n},fetch:n0}),i=new d8({name:"dsh-edge",version:t0},{capabilities:{},jsonSchemaValidator:ept});return await i.connect(r),{client:i,close:o(async()=>{await i.close().catch(()=>{})},"close")}}async function a3e(e,t,n){let r=AbortSignal.timeout(oa.probeTimeoutMs),i;try{i=await s3e(t,n,r)}catch(l){throw new Error(Tp(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<oa.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>=oa.maxToolsPerServer)break;let v=X2e(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=Q2e(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>=oa.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,oa.maxInstructionsLength):void 0}}finally{await a()}}async function b8(e,t,n,r,i,s){let a=s??oa.callTimeoutMs,l=i?AbortSignal.any([i,AbortSignal.timeout(a)]):AbortSignal.timeout(a),c;try{c=await s3e(e,r,l)}catch(u){throw new Error(Tp(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(Tp(u instanceof Error?u.message:String(u)))}finally{await c.close()}}var Zdt,Kdt,Jdt,ept,n0,aS=oe(()=>{"use strict";c2e();B2e();J2e();w8();v8();sS();Zdt=[".internal",".local",".localhost"],Kdt=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],Jdt=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];o(Ydt,"extractMappedIPv4");o(Xdt,"isIpAddress");o(Kf,"assertSafeUrl");o(Qdt,"buildHeaders");ept=new y8,n0=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(s3e,"connectClient");o(a3e,"probe");o(b8,"callTool")});import{Buffer as tpt}from"node:buffer";function spt(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&ipt.has(e.code)}function l3e(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&rpt.has(e.code)}function c3e(e,t,n){let r=tpt.from(e,"base64");if(e.length===0&&t==="reject"||r.toString("base64")!==e)throw new ar(n==="INVALID_IMAGE_BASE64"?"Image upload is not canonical base64.":"File upload is not canonical base64.",n);return new Uint8Array(r)}function apt(e){return c3e(e,"reject","INVALID_IMAGE_BASE64")}function opt(e){return{data:apt(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function oS(e,t){return e.saveImages(t.map(opt))}async function lpt(e,t){return e.saveFile({data:c3e(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function u3e(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 LH(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 o3e,npt,rpt,ipt,ar,jH,Jf=oe(()=>{Vn();o3e=["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"],npt=[...o3e,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],rpt=new Set(o3e),ipt=new Set(npt),ar=class extends Error{static{o(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};o(spt,"isAttachmentError");o(l3e,"isImageAdmissionError");o(c3e,"decodeCanonicalBase64");o(apt,"decodeBase64");o(opt,"saveInput");o(oS,"admitEncodedImages");o(lpt,"admitEncodedFile");o(u3e,"requestImageDimensions");o(LH,"longEdgeDimensions");jH=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 ar("Image batch exceeds the configured image-count limit.","TOO_MANY_IMAGES");if(e.reduce((i,s)=>i+s.data.byteLength,0)>n)throw new ar("Image batch exceeds the configured aggregate image-byte limit.","IMAGES_TOO_LARGE");for(let i of e)if(!r.includes(i.mediaType))throw new ar(`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 oS(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 lpt(this,e)}isAttachmentError(e){return spt(e)}imageHostPath(e){}saveFile(e){return Promise.reject(new ar("The mounted attachment provider cannot store verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}saveFileStream(e){return Promise.reject(new ar("The mounted attachment provider cannot stream verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}async*readFileStream(e,t){t?.throwIfAborted(),await Promise.reject(new ar("The mounted attachment provider cannot read verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}fileHostPath(e){}readImageRequest(e,t,n){return n?.throwIfAborted(),Promise.reject(new ar("The mounted attachment provider cannot derive model-request images.","ATTACHMENT_PROJECTION_UNSUPPORTED"))}}});var S8={};kn(S8,{buildAuthorizationUrl:()=>ypt,discoverEndpoints:()=>mpt,exchangeCode:()=>vpt,isTokenExpired:()=>bpt,refreshToken:()=>wpt,registerClient:()=>gpt});function h3e(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 hpt(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 mpt(e){let t=AbortSignal.timeout(x8),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);Kf(i.href);let s=await n0(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);Kf(d.href);let p=await n0(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 gpt(e,t,n){let r=AbortSignal.timeout(x8);Kf(e);let i=await n0(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 ypt(e,t,n,r,i){let s=h3e(32),a=h3e(64),l=await hpt(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 vpt(e,t,n,r,i,s){let a=AbortSignal.timeout(x8),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),Kf(e);let c=await n0(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 m3e(await c.json())}async function wpt(e,t,n,r){let i=AbortSignal.timeout(x8),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),Kf(e);let a=await n0(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 m3e(await a.json())}function m3e(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 bpt(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var x8,k8=oe(()=>{"use strict";aS();x8=1e4;o(h3e,"randomString");o(hpt,"sha256Base64Url");o(mpt,"discoverEndpoints");o(gpt,"registerClient");o(ypt,"buildAuthorizationUrl");o(vpt,"exchangeCode");o(wpt,"refreshToken");o(m3e,"parseTokenResponse");o(bpt,"isTokenExpired")});var qn,k3e,lS=oe(()=>{Vn();vr();qn=class extends Lr{static{o(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},k3e=class extends St{static{o(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new qn("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function rV(e){return P8.test(e)}function D8(e){return e.invocation.modelInvocable}function w3(e){return e.invocation.userInvocable}function iV(e){let t=iht(e);return[`<skill_content name="${sht(e.name)}">`,"<skill_resources>",...t,"</skill_resources>","","<skill_instructions>",e.content,"</skill_instructions>","</skill_content>"].join(`
156
156
  `)}function iht(e){let t=e.resourceBase;if(t===void 0)return[`Resources for this skill are managed by provider "${v3(e.provider)}".`,"Load referenced resources only as needed."];switch(t.kind){case"directory":return[`Base directory for this skill: ${v3(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: ${v3(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: ${v3(t.description)}`,"Load referenced resources only as needed."];default:return ri(t,"SkillResourceBase.kind")}}function sht(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;")}function v3(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function oht(e,t){if(Array.isArray(e))return{candidates:e,complete:!0};if(e===null||typeof e!="object")throw W3e(t);let n=e;if(!Array.isArray(n.candidates)||typeof n.complete!="boolean")throw W3e(t);return n}function W3e(e){return new TypeError(`skill provider "${e}" list() must return an array or { candidates, complete } observation`)}function cht(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:rht,locator:e,...e.path!==void 0?{path:e.path}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}function uht(e,t){if(typeof e.name!="string")throw new TypeError(`skill provider "${t}" returned a non-string skill name`);if(!P8.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(sV(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 dht(e){if(!P8.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`);sV(e.invocation,`runtime skill "${e.name}"`)}function pht(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(!P8.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(sV(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 fht(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 sV(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 hht(e,t){return Z3e(e.name,t.name)}function Z3e(e,t){return e<t?-1:e>t?1:0}function mht(e,t){return e.candidate.rank-t.candidate.rank||e.providerOrder-t.providerOrder||e.localOrder-t.localOrder}function ght(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 H3e(e,t){return t===void 0?e:(pS(t),new Promise((n,r)=>{let i=o(()=>{t.removeEventListener("abort",s)},"cleanup"),s=o(()=>{i(),r($8(t.reason))},"onAbort");t.addEventListener("abort",s,{once:!0}),e.then(a=>{i(),n(a)},a=>{i(),r($8(a))})}))}function pS(e){if(e?.aborted===!0)throw $8(e.reason)}function $8(e){try{if(e instanceof Error)return e}catch{}return new Error(N8(e))}function N8(e){try{return String(e)}catch{return"[unrenderable thrown value]"}}var P8,z3e,nht,O8,rht,V3e,aht,G3e,lht,b3=oe(()=>{Vn();Wi();hl();dn();P8=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,z3e=128,nht=2,O8="runtime",rht=250,V3e=600;o(rV,"isSkillName");o(D8,"isModelInvocable");o(w3,"isUserInvocable");o(iV,"renderSkillContent");o(iht,"renderResourceHint");o(sht,"escapeAttr");o(v3,"escapeText");aht=class{static{o(this,"SkillLayer")}providers;runtime=new Map;constructor(e){this.providers=new lp(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}},G3e=class extends St{static{o(this,"SkillRegistry")}static Config=L.object({collectCacheMaxEntries:L.number().default(z3e)});collectCacheMaxEntries;layers=new cp(e=>new aht(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??z3e,ght("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===O8)throw new Error(`"${O8}" 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){dht(e);let t=fl(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??O8};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=>fht(n.candidate)).sort(hht),complete:t.cacheable}}async get(e,t={}){if(!rV(e))return;let n=await this.collect(t);pS(t.signal);let r=n.entries.get(e);if(r===void 0)return;let i=await H3e(r.provider.get(r.candidate,t),t.signal);if(i!==void 0){if(pht(i),i.name!==r.candidate.name){this.invalidateEntry(r);return}return i}}async collect(e){pS(e.signal);let t=1;for(;;){let n=this.revision,r=this.collectCacheKey(e.cwd,Pb(e.scope),n),i=this.collectCache.get(r);if(i!==void 0)return{entries:i,cacheable:!0};let s=await this.collectFresh(e);if(pS(e.signal),n!==this.revision){if(t<nht){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(mht);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){pS(t.signal);let n=[],r=!0,i=0;for(let s of[...e.runtime.values()].sort((a,l)=>Z3e(a.name,l.name)))n.push({candidate:cht(s),provider:lht,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 H3e(s.list(t),t.signal)}catch(d){if(t.signal?.aborted===!0)throw $8(t.signal.reason);r=!1,this.ctx.logger.warn(`skill provider "${s.name}" skipped: ${N8(d)}`)}if(c===void 0)continue;let u=oht(c,s.name);u.complete||(r=!1);for(let d of u.candidates)uht(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: ${N8(n)}`)})}catch(t){this.ctx.logger.warn(`skills/change listener threw: ${N8(t)}`)}}};o(oht,"normalizeProviderObservation");o(W3e,"invalidProviderObservation");lht={name:O8,list(){return Promise.resolve([])},get(e){return Promise.resolve(e.locator)}};o(cht,"runtimeCandidate");o(uht,"validateCandidate");o(dht,"validateRuntimeSkill");o(pht,"validateDefinition");o(fht,"toSummary");o(sV,"validateInvocation");o(hht,"compareSkillSummary");o(Z3e,"compareCodePoints");o(mht,"compareIndexedCandidates");o(ght,"assertPositiveInteger");o(H3e,"waitWithAbort");o(pS,"throwIfAborted");o($8,"toError");o(N8,"errorMessage")});var bu,S3=oe(()=>{bu=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 Xf,hwe,jV=oe(()=>{Vn();Xf=class extends Error{static{o(this,"DirectoryPickerError")}code;path;constructor(e,t,n){super(n),this.code=e,this.path=t,this.name="DirectoryPickerError"}},hwe=class extends St{static{o(this,"DirectoryPicker")}constructor(e){super(e,"directoryPicker")}}});var cxe=we((ZTn,FA)=>{var lxe=lxe||function(e){return Buffer.from(e).toString("base64")};function K2t(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),W,G=[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],q=[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],Z=[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],B=[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[G[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[G[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[G[Ge]]*it[mt]*it[Re]*8),l[Ge]=1/(s[G[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(q,$),u=D(I,B),d=D(Z,X),p=D(A,C)}o(P,"initHuffmanTbl");function H(){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(H,"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 mn=ke+mt,Bt=ke-mt,jt=lt+Ge,ae=lt-Ge,$e=Be+it,Ve=Be-it,at=Le+yt,Ct=Le-yt,Ye=mn+at,rn=mn-at,Qt=jt+$e,gn=jt-$e;ie[Re]=Ye+Qt,ie[Re+4]=Ye-Qt;var Dt=(gn+rn)*.707106781;ie[Re+2]=rn+Dt,ie[Re+6]=rn-Dt,Ye=Ct+Ve,Qt=Ve+ae,gn=ae+Bt;var Rr=(Ye-gn)*.382683433,Dr=.5411961*Ye+Rr,Qi=1.306562965*gn+Rr,Ei=Qt*.707106781,lr=Bt+Ei,es=Bt-Ei;ie[Re+5]=es+Dr,ie[Re+3]=es-Dr,ie[Re+1]=lr+Qi,ie[Re+7]=lr-Qi,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 xs=ke+mt,Fs=ke-mt,ea=lt+Ge,Ft=lt-Ge,Pn=Be+it,ta=Be-it,Za=Le+yt,ma=Le-yt,ga=xs+Za,_a=xs-Za,Ka=ea+Pn,ko=ea-Pn;ie[Re]=ga+Ka,ie[Re+32]=ga-Ka;var fc=(ko+_a)*.707106781;ie[Re+16]=_a+fc,ie[Re+48]=_a-fc,ga=ma+ta,Ka=ta+Ft,ko=Ft+Fs;var Al=(ga-ko)*.382683433,Bu=.5411961*ga+Al,zu=1.306562965*ko+Al,Wu=Ka*.707106781,Hu=Fs+Wu,lf=Fs-Wu;ie[Re+40]=lf+Bu,ie[Re+24]=lf-Bu,ie[Re+8]=Hu+zu,ie[Re+56]=Hu-zu,Re++}var Wd;for(kt=0;kt<pt;++kt)Wd=ie[kt]*Me[kt],g[kt]=Wd>0?Wd+.5|0:Wd-.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(q[ie+1]);for(var Me=0;Me<=11;Me++)F($[Me]);F(16);for(var ke=0;ke<16;ke++)F(Z[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(B[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[G[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 mn=63;mn>0&&y[mn]==0;mn--);if(mn==0)return K(Le),ke;for(var Bt=1,jt;Bt<=mn;){for(var ae=Bt;y[Bt]==0&&Bt<=mn;++Bt);var $e=Bt-ae;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 mn!=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,mn,Bt,jt,ae,$e,Ve,at;zt<Ge;){for(kt=0;kt<mt;){for(jt=mt*zt+kt,ae=jt,$e=-1,Ve=0,at=0;at<64;at++)Ve=at>>3,$e=(at&7)*4,ae=jt+Ve*mt+$e,zt+Ve>=Ge&&(ae-=mt*(zt+1+Ve-Ge)),kt+$e>=mt&&(ae-=kt+$e-mt+4),pt=yt[ae++],mn=yt[ae++],Bt=yt[ae++],k[at]=(R[pt]+R[mn+256>>0]+R[Bt+512>>0]>>16)-128,x[at]=(R[pt+768>>0]+R[mn+1024>>0]+R[Bt+1280>>0]>>16)-128,E[at]=(R[pt+1280>>0]+R[mn+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 Ct=[];Ct[1]=S+1,Ct[0]=(1<<S+1)-1,K(Ct)}if(ee(65497),typeof FA>"u")return new Uint8Array(v);return Buffer.from(v);var Ye,rn};function Ie(ie){if(ie<=0&&(ie=1),ie>100&&(ie=100),W!=ie){var Me=0;ie<50?Me=Math.floor(5e3/ie):Me=Math.floor(200-ie*2),N(Me),W=ie}}o(Ie,"setQuality");function Se(){var ie=new Date().getTime();e||(e=50),rt(),P(),H(),J(),Ie(e);var Me=new Date().getTime()-ie}o(Se,"init"),Se()}o(K2t,"JPEGEncoder");typeof FA<"u"?FA.exports=oxe:typeof window<"u"&&(window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=oxe);function oxe(e,t){typeof t>"u"&&(t=50);var n=new K2t(t),r=n.encode(e,t);return{data:r,width:e.width,height:e.height}}o(oxe,"encode")});var dxe=we((JTn,KG)=>{var ZG=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,W=16;W>0&&!S[W-1];)W--;E.push({children:[],index:0});var G=E[0],q;for(T=0;T<W;T++){for(R=0;R<S[T];R++){for(G=E.pop(),G.children[G.index]=k[x];G.index>0;){if(E.length===0)throw new Error("Could not recreate Huffman Table");G=E.pop()}for(G.index++,E.push(G);E.length<=T;)E.push(q={children:[],index:0}),G.children[G.index]=q.children,G=q;x++}T+1<W&&(E.push(q={children:[],index:0}),G.children[G.index]=q.children,G=q)}return E[0].children}o(p,"buildHuffmanTable");function m(S,k,x,E,T,R,W,G,q,$){var Z=x.precision,X=x.samplesPerLine,I=x.scanLines,B=x.mcusPerLine,A=x.progressive,C=x.maxH,N=x.maxV,D=k,P=0,H=0;function J(){if(H>0)return H--,P>>H&1;if(P=S[k++],P==255){var Re=S[k++];if(Re)throw new Error("unexpected marker: "+(P<<8|Re).toString(16))}return H=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 mn=1;mn<64;){var Bt=K(Re.huffmanTableAC),jt=Bt&15,ae=Bt>>4;if(jt===0){if(ae<15)break;mn+=16;continue}mn+=ae;var $e=t[mn];kt[$e]=ee(jt),mn++}}o(ge,"decodeBaseline");function ve(Re,kt){var zt=K(Re.huffmanTableDC),pt=zt===0?0:ee(zt)<<q;kt[0]=Re.pred+=pt}o(ve,"decodeDCFirst");function le(Re,kt){kt[0]|=J()<<q}o(le,"decodeDCSuccessive");var xe=0;function Ee(Re,kt){if(xe>0){xe--;return}for(var zt=R,pt=W;zt<=pt;){var mn=K(Re.huffmanTableAC),Bt=mn&15,jt=mn>>4;if(Bt===0){if(jt<15){xe=F(jt)+(1<<jt)-1;break}zt+=16;continue}zt+=jt;var ae=t[zt];kt[ae]=ee(Bt)*(1<<q),zt++}}o(Ee,"decodeACFirst");var ce=0,ue;function st(Re,kt){for(var zt=R,pt=W,mn=0;zt<=pt;){var Bt=t[zt],jt=kt[Bt]<0?-1:1;switch(ce){case 0:var ae=K(Re.huffmanTableAC),$e=ae&15,mn=ae>>4;if($e===0)mn<15?(xe=F(mn)+(1<<mn),ce=4):(mn=16,ce=1);else{if($e!==1)throw new Error("invalid ACn encoding");ue=ee($e),ce=mn?2:3}continue;case 1:case 2:kt[Bt]?kt[Bt]+=(J()<<q)*jt:(mn--,mn===0&&(ce=ce==2?3:0));break;case 3:kt[Bt]?kt[Bt]+=(J()<<q)*jt:(kt[Bt]=ue<<q,ce=0);break;case 4:kt[Bt]&&(kt[Bt]+=(J()<<q)*jt);break}zt++}ce===4&&(xe--,xe===0&&(ce=0))}o(st,"decodeACSuccessive");function He(Re,kt,zt,pt,mn){var Bt=zt/B|0,jt=zt%B,ae=Bt*Re.v+pt,$e=jt*Re.h+mn;Re.blocks[ae]===void 0&&$.tolerantDecoding||kt(Re,Re.blocks[ae][$e])}o(He,"decodeMcu");function rt(Re,kt,zt){var pt=zt/Re.blocksPerLine|0,mn=zt%Re.blocksPerLine;Re.blocks[pt]===void 0&&$.tolerantDecoding||kt(Re,Re.blocks[pt][mn])}o(rt,"decodeBlock");var Ie=E.length,Se,ie,Me,ke,lt,Be;A?R===0?Be=G===0?ve:le:Be=G===0?Ee:st:Be=ge;var Le=0,yt,it;Ie==1?it=E[0].blocksPerLine*E[0].blocksPerColumn:it=B*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(H=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,W=new Int32Array(64),G=new Uint8Array(64);function q(D,P,H){var J=k.quantizationTable,K,F,ee,ge,ve,le,xe,Ee,ce,ue=H,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*H[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(q,"quantizeAndInverse"),b(R*T*8);for(var $,Z,X=0;X<T;X++){var I=X<<3;for($=0;$<8;$++)x.push(new Uint8Array(R));for(var B=0;B<E;B++){q(k.blocks[X][B],G,W);var A=0,C=B<<3;for(Z=0;Z<8;Z++){var N=x[I+Z];for($=0;$<8;$++)N[C+$]=G[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 ae=k[E]<<8|k[E+1];return E+=2,ae}o(R,"readUint16");function W(){var ae=R(),$e=k.subarray(E,E+ae-2);return E+=$e.length,$e}o(W,"readDataBlock");function G(ae){var $e=1,Ve=1,at,Ct;for(Ct in ae.components)ae.components.hasOwnProperty(Ct)&&(at=ae.components[Ct],$e<at.h&&($e=at.h),Ve<at.v&&(Ve=at.v));var Ye=Math.ceil(ae.samplesPerLine/8/$e),rn=Math.ceil(ae.scanLines/8/Ve);for(Ct in ae.components)if(ae.components.hasOwnProperty(Ct)){at=ae.components[Ct];var Qt=Math.ceil(Math.ceil(ae.samplesPerLine/8)*at.h/$e),gn=Math.ceil(Math.ceil(ae.scanLines/8)*at.v/Ve),Dt=Ye*at.h,Rr=rn*at.v,Dr=Rr*Dt,Qi=[];b(Dr*256);for(var Ei=0;Ei<Rr;Ei++){for(var lr=[],es=0;es<Dt;es++)lr.push(new Int32Array(64));Qi.push(lr)}at.blocksPerLine=Qt,at.blocksPerColumn=gn,at.blocks=Qi}ae.maxH=$e,ae.maxV=Ve,ae.mcusPerLine=Ye,ae.mcusPerColumn=rn}o(G,"prepareComponents");var q=null,$=null,Z=null,X,I,B=[],A=[],C=[],N=[],D=R(),P=-1;if(this.comments=[],D!=65496)throw new Error("SOI not found");for(D=R();D!=65497;){var H,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=W();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&&(q={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");B[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(H=0;H<st;H++){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}G(X),A.push(X);break;case 65476:var ke=R();for(H=2;H<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];H+=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(H=0;H<Ge;H++){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++],mn=k[E++],Bt=m(k,E,X,mt,I,zt,pt,mn>>4,mn&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 ae=R();if(k[E+ae-2]===255){E+=ae-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 H=0;H<A.length;H++){var jt=A[H].components;for(var J in jt)jt[J].quantizationTable=B[jt[J].quantizationIdx],delete jt[J].quantizationIdx}this.width=X.samplesPerLine,this.height=X.scanLines,this.jfif=q,this.adobe=$,this.components=[];for(var H=0;H<X.componentsOrder.length;H++){var Re=X.components[X.componentsOrder[H]];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,W,G,q,$,Z,X,I,B,A,C=0,N,D,P,H,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],B=0;B<k;B++)N=$[0|B*R.scaleX*E],Ee[C++]=N;break;case 2:for(R=this.components[0],W=this.components[1],A=0;A<x;A++)for($=R.lines[0|A*R.scaleY*T],Z=W.lines[0|A*W.scaleY*T],B=0;B<k;B++)N=$[0|B*R.scaleX*E],Ee[C++]=N,N=Z[0|B*W.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],W=this.components[1],G=this.components[2],A=0;A<x;A++)for($=R.lines[0|A*R.scaleY*T],Z=W.lines[0|A*W.scaleY*T],X=G.lines[0|A*G.scaleY*T],B=0;B<k;B++)le?(N=$[0|B*R.scaleX*E],D=Z[0|B*W.scaleX*E],P=X[0|B*G.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|B*R.scaleX*E],ge=Z[0|B*W.scaleX*E],ve=X[0|B*G.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],W=this.components[1],G=this.components[2],q=this.components[3],A=0;A<x;A++)for($=R.lines[0|A*R.scaleY*T],Z=W.lines[0|A*W.scaleY*T],X=G.lines[0|A*G.scaleY*T],I=q.lines[0|A*q.scaleY*T],B=0;B<k;B++)le?(N=$[0|B*R.scaleX*E],D=Z[0|B*W.scaleX*E],P=X[0|B*G.scaleX*E],H=I[0|B*q.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|B*R.scaleX*E],K=Z[0|B*W.scaleX*E],F=X[0|B*G.scaleX*E],H=I[0|B*q.scaleX*E]),Ee[C++]=255-J,Ee[C++]=255-K,Ee[C++]=255-F,Ee[C++]=255-H;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,W=this.getData(E,T),G=0,q=0,$,Z,X,I,B,A,C,N,D;switch(this.components.length){case 1:for(Z=0;Z<T;Z++)for($=0;$<E;$++)X=W[G++],R[q++]=X,R[q++]=X,R[q++]=X,x&&(R[q++]=255);break;case 3:for(Z=0;Z<T;Z++)for($=0;$<E;$++)C=W[G++],N=W[G++],D=W[G++],R[q++]=C,R[q++]=N,R[q++]=D,x&&(R[q++]=255);break;case 4:for(Z=0;Z<T;Z++)for($=0;$<E;$++)B=W[G++],A=W[G++],X=W[G++],I=W[G++],C=255-g(B*(1-I/255)+I),N=255-g(A*(1-I/255)+I),D=255-g(X*(1-I/255)+I),R[q++]=C,R[q++]=N,R[q++]=D,x&&(R[q++]=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 KG<"u"?KG.exports=uxe:typeof window<"u"&&(window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=uxe);function uxe(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 ZG;s.opts=r,ZG.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),s.parse(i);var a=r.formatAsRGBA?4:3,l=s.width*s.height*a;try{ZG.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(uxe,"decode")});var fxe=we((XTn,pxe)=>{var J2t=cxe(),Y2t=dxe();pxe.exports={encode:J2t,decode:Y2t}});function H6e(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 hn({...e,content:s})}var V6e=oe(()=>{Wi();o(H6e,"offloadMessageImages")});function G6e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Z6e(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0&&!Object.is(e,-0)}var i9,zZ=oe(()=>{V6e();o(G6e,"isRecord");o(Z6e,"isIndex");i9={type:"image/offload",project(e,t){let n=e.data;if(!G6e(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(!G6e(s)||Object.keys(s).length!==2||!Z6e(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(!Z6e(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,H6e(u,s.imageIndexes))}return r}}});var w9,fke=oe(()=>{zZ();w9=[i9]});async function bke(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,...L_(a)]}}function _K(e,t){if(e.id!==t.id||e.createdAt!==t.createdAt||e.cwd!==t.cwd||e.parentSession!==t.parentSession||e.isSeeded!==t.isSeeded||(e.delegationDepth??0)!==(t.delegationDepth??0))throw new Ir(`session source headers conflict for session "${e.id}"`,"SESSION_QUERY_SOURCE_CONFLICT")}function b9(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 TK(e){return{header:e.header,events:e.snapshotEvents()}}function x9(e,t){return e.map(n=>t.get(n))}async function AK(e,t){try{return(await e.list(t===void 0?void 0:{signal:t})).map(n=>n.header)}catch(n){throw t?.aborted&&t.throwIfAborted(),new Ir(`session persistence listing failed: ${RK(n)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:n})}}async function hke(e,t,n){try{return await bke(e,t,n)}catch(r){throw n?.aborted&&n.throwIfAborted(),r instanceof Error&&r.name==="SessionPersistenceCorruptionError"?new Ir(`stored session "${t}" is corrupt: ${RK(r)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:r}):new Ir(`failed to read stored session "${t}": ${RK(r)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:r})}}function mke(e){return{header:structuredClone(e.header),inheritedEventCount:e.inheritedEventCount,events:e.snapshotEvents().map(t=>structuredClone(t))}}function n6t(e,t){return t.header.createdAt-e.header.createdAt||e.header.id.localeCompare(t.header.id)}function S9(e){return new Ir(`session "${e}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND")}function RK(e){return e instanceof Error?e.message:"unknown error"}function sk(e){if(e?.aborted===!0)throw new Ir("session observation was aborted","SESSION_QUERY_ABORTED",{cause:e.reason})}function gke(e,t){return yke(t,"SessionPersistenceNotFoundError")?OK(e,t):yke(t,"SessionPersistenceCorruptionError")?new Ir(`stored session "${e}" is corrupt: ${t.message}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:t}):new Ir(`failed to observe session "${e}": ${k9(t)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:t})}function OK(e,t){return new Ir(`session "${e}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND",t===void 0?void 0:{cause:t})}function k9(e){return e instanceof Error?e.message:"unknown error"}function yke(e,t){return e instanceof Error&&e.name===t}function i6t(e){switch(e.type){case"user/message":return IK(e.data.content);case"assistant/message":return IK(e.data.message.content);case"tool/call":return ak([e.data.name,e.data.arguments]);case"tool/result":return ak([IK(e.data.message.content),e.data.error?.name??"",e.data.error?.code??""]);case"todo/write":return ak(e.data.todos.flatMap(t=>[t.status,t.content]));case"turn/end":return s6t(e.data.reason);case"turn/start":case"step/start":case"step/end":case"assistant/attempt":case"request/header":return"";default:return""}}function s6t(e){switch(e.kind){case"error":return ak(["error",e.error.message]);case"aborted":return"aborted";case"max-tokens":case"interrupted":return e.kind;case"completed":return"";default:return""}}function IK(e){return ak(e.flatMap(a6t))}function a6t(e){switch(e.type){case"text":return[e.text];case"reasoning":return[];case"tool-call":return[e.name,e.arguments];default:return[]}}function ak(e){return e.map(t=>t.trim()).filter(Boolean).join(`
157
157
  `)}function $K(e,t){let n=o6t(t),r=[];for(let i of t){let s=i6t(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 o6t(e){let t;try{t=OP(e,w9)}catch(r){throw new Ir(`invalid session surface: ${r instanceof Error?r.message:"unknown error"}`,"SESSION_QUERY_INVALID_SURFACE",{cause:r})}let n=new Map;for(let r of t.nodes)n.set(r,"current");for(let r of t.replacements)for(let i of r.shadowedSeqs)n.set(i,"shadowed");return n}function PK(e,t=[]){let n=t.map(c6t);return e.filter(r=>n.every(i=>i(r)))}function A9(e,t=[]){let n=t.map(u6t);return e.filter(r=>n.every(i=>i(r)))}function DK(e){return xke(e),e.map(t=>{switch(t.kind){case"id":return{kind:t.kind,values:_9(t.kind,t.values)};case"cwd":return{kind:t.kind,values:vke(t.kind,t.values)};case"created-at":return Ske(t.kind,t);case"parent":return{kind:t.kind,values:vke(t.kind,t.values)};case"availability":{let n=_9(t.kind,t.values);return R9(t.kind,n,["live","persisted"]),{kind:t.kind,values:n}}default:return C9(t)}})}function I9(e){return xke(e),e.map(t=>{switch(t.kind){case"seq":case"time":return Ske(t.kind,t);case"type":return{kind:t.kind,values:_9(t.kind,t.values)};case"surface":{let n=_9(t.kind,t.values);return R9(t.kind,n,["current","shadowed","log-only"]),{kind:t.kind,values:n}}case"text":if(typeof t.text!="string")throw Q3("text filter text must be a string");return{kind:t.kind,text:t.text};default:return C9(t)}})}function l6t(e){let t=e.trim();if(t.length===0)throw new Ir("session text filter must contain non-whitespace text","SESSION_QUERY_INVALID_FILTER");let n=t.split(/\s+/u).map(r=>r.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")).join("\\s+");return new RegExp(n,"iu")}function c6t(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=T9(e.kind,e);return n=>NK(n.header.createdAt,t)}case"parent":return t=>e.values.includes(t.header.parentSession??null);case"availability":return R9(e.kind,e.values,["live","persisted"]),t=>e.values.some(n=>n==="live"?t.live:t.persisted);default:return C9(e)}}function u6t(e){switch(e.kind){case"seq":{let t=T9(e.kind,e);return n=>NK(n.seq,t)}case"time":{let t=T9(e.kind,e);return n=>NK(n.time,t)}case"type":return t=>e.values.includes(t.type);case"surface":return R9(e.kind,e.values,["current","shadowed","log-only"]),t=>e.values.includes(t.surface);case"text":{let t=l6t(e.text);return n=>t.test(n.text)}default:return C9(e)}}function _9(e,t){if(!kke(t)||t.some(n=>typeof n!="string"))throw Q3(`${e} filter values must be an array of strings`);return[...t]}function xke(e){if(!Array.isArray(e))throw Q3("filters must be an array")}function vke(e,t){if(!kke(t)||t.some(n=>n!==null&&typeof n!="string"))throw Q3(`${e} filter values must be an array of strings or null`);return[...t]}function Ske(e,t){let n={kind:e,...t.from===void 0?{}:{from:t.from},...t.to===void 0?{}:{to:t.to}};return T9(e,n),n}function C9(e){let t=e.kind;throw Q3(`unknown filter kind ${typeof t=="string"?`"${t}"`:"(missing)"}`)}function R9(e,t,n){for(let r of t)if(!n.includes(r))throw new Ir(`session ${e} filter contains unknown value "${r}"`,"SESSION_QUERY_INVALID_FILTER")}function T9(e,t){if(t.from!==void 0&&!Number.isFinite(t.from))throw CK(e,"from must be finite");if(t.to!==void 0&&!Number.isFinite(t.to))throw CK(e,"to must be finite");if(t.from!==void 0&&t.to!==void 0&&t.from>t.to)throw CK(e,"from must be less than or equal to to");return t}function NK(e,t){return(t.from===void 0||e>=t.from)&&(t.to===void 0||e<=t.to)}function CK(e,t){return Q3(`${e} filter ${t}`)}function Q3(e){return new Ir(`session ${e}`,"SESSION_QUERY_INVALID_FILTER")}function kke(e){return Array.isArray(e)}function d6t(e,t){return MK(e,t).records}function p6t(e,t){return MK(e,t).currentSeqs.map(n=>{let r=t[n];if(r===void 0||r.seq!==n||!em(r))throw new Ir(`invalid session surface: current node ${n} is not a surface event`,"SESSION_QUERY_INVALID_SURFACE");return Lb(r)})}function f6t(e,t,n){let r=t[n];if(r===void 0||r.seq!==n)throw new Ir(`session "${e}" has no event at seq ${n}`,"SESSION_QUERY_EVENT_NOT_FOUND");let i=MK(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||wke(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:[...wke(r)],derivedEventSeqs:l}}function h6t(e,t){let n=new Map(e.map(p=>[p.header.id,p])),r=n.get(t);if(r===void 0)throw new Ir(`session "${t}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND");let i=[],s=new Set([t]),a,l=r.header.parentSession;for(;l!==void 0;){if(s.has(l))throw new Ir(`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=m6t(c,t),d={target:E9(r),ancestors:i.map(E9),descendants:u};return a!==void 0?{...d,complete:!1,unresolvedParentId:a}:{...d,complete:!0,root:E9(i.at(-1)??r)}}function MK(e,t){let n;try{n=OP(t,w9)}catch(a){throw new Ir(`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 wke(e){return e.sourceEventSeqs??[]}function m6t(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:E9(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 E9(e){return{...e,header:structuredClone(e.header)}}var Ir,t6t,r6t,Eke,LK=oe(()=>{fke();Vn();ks();bm();vr();Ir=class extends Lr{static{o(this,"SessionQueryError")}constructor(e,t,n){super(e,t,n)}};o(bke,"readColdSessionLog");o(_K,"assertSessionHeadersCompatible");t6t=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 AK(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&&_K(i.header,s.header),r.set(i.id,{header:structuredClone(i.header),live:!0,persisted:s!==void 0})}return[...r.values()].sort(n6t)}async load(e,t){t?.throwIfAborted();let n=this._ctx.sessions.get(e);if(n!==void 0){let c=mke(n);return t?.throwIfAborted(),c}let r=this._persistence;if(r===void 0)throw S9(e);let i=(await AK(r,t)).find(c=>c.id===e);if(t?.throwIfAborted(),i===void 0)throw S9(e);let s=await hke(r,e,t);t?.throwIfAborted();let a=this._ctx.sessions.get(e);if(a!==void 0){let c=mke(a);return t?.throwIfAborted(),c}_K(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,b9(g,TK(y),t,n))}if(s.length===0)return x9(r,i);let a=this._persistence;if(a===void 0){for(let g of s)i.set(g,{sessionId:g,status:"rejected",reason:S9(g)});return x9(r,i)}let l;try{l=await AK(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 x9(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:S9(g)}:b9(g,TK(v),t,n));return}try{n?.throwIfAborted();let v=await hke(a,g,n);n?.throwIfAborted();let b=this._ctx.sessions.get(g);if(b!==void 0){i.set(g,b9(g,TK(b),t,n));return}_K(v.header,y),i.set(g,b9(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(),x9(r,i)}};o(b9,"projectSource");o(TK,"sourceLive");o(x9,"orderedResults");o(AK,"listPersisted");o(hke,"inspectPersisted");o(mke,"snapshotLive");o(n6t,"compareSessions");o(S9,"notFound$1");o(RK,"errorMessage$1");r6t=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(;;){sk(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 OK(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);sk(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 Ir(`stored session "${e}" is corrupt: ${k9(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 Ir(`failed to project session "${e}": ${k9(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 sk(n),gke(t,i)}if(sk(n),r===void 0)throw OK(t);if(r.header.id!==t)throw new Ir(`session persistence returned "${r.header.id}" for "${t}"`,"SESSION_QUERY_SOURCE_CONFLICT");return r}async loadSource(e,t,n){try{return await bke(e,t,n)}catch(r){throw sk(n),gke(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 Ir(`failed to project session "${e.id}": ${k9(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(En(0),n),r},cursor:n===0?-1:sn(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,En(0)):n.hydratePrepared(e.session,e.events)}};o(sk,"throwIfObservationAborted");o(gke,"mapPersistenceFailure");o(OK,"notFound");o(k9,"errorMessage");o(yke,"hasErrorName");o(i6t,"extractSessionEventText");o(s6t,"turnEndText");o(IK,"contentText");o(a6t,"blockText");o(ak,"joinText");o($K,"buildSessionEventSearchDocuments");o(o6t,"classifySurface");o(PK,"filterSessionResults");o(A9,"filterSessionEventDocuments");o(DK,"materializeSessionResultFilters");o(I9,"materializeSessionEventResultFilters");o(l6t,"compileSessionTextFilter");o(c6t,"sessionPredicate");o(u6t,"eventPredicate");o(_9,"copyStrings");o(xke,"assertArray");o(vke,"copyNullableStrings");o(Ske,"copyRange");o(C9,"unknownFilter");o(R9,"assertAllowedValues");o(T9,"validateRange");o(NK,"matchesRange");o(CK,"invalidRange");o(Q3,"invalidFilter");o(kke,"isRuntimeArray");o(d6t,"eventRecords");o(p6t,"currentSurfaceEvents");o(f6t,"traceEvent");o(h6t,"traceSession");o(MK,"analyzeEventLog");o(wke,"eventSources");o(m6t,"buildDescendants");o(E9,"cloneRecord");Eke=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 Ir("session-query: readWindowMax must be a non-negative integer","SESSION_QUERY_INVALID_CONFIG");let n=t.persistedReadConcurrency??4;if(!Number.isSafeInteger(n)||n<1)throw new Ir("session-query: persistedReadConcurrency must be a positive safe integer","SESSION_QUERY_INVALID_CONFIG");let r=t.preparedSessionCacheSize??5;if(!Number.isSafeInteger(r)||r<1)throw new Ir("session-query: preparedSessionCacheSize must be a positive safe integer","SESSION_QUERY_INVALID_CONFIG");this._corpus=new t6t(e,n),this._observations=new r6t(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 dg.create(e,t.events,t.header,t.inheritedEventCount,w9),{session:structuredClone(t.header),inheritedEventCount:t.inheritedEventCount,events:t.events.map(Lb)}}async filterSessions(e,t){let n=DK(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=wm(n.events);return{session:structuredClone(n.header),...r===void 0?{}:{title:r}}},t)}async listEvents(e){return d6t(e,(await this._corpus.load(e)).events)}async filterEvents(e,t){let n=I9(t);return this._filterEvents(e,n)}async _filterSessions(e,t){return PK(await this._corpus.listSessions(t),e)}async _filterEvents(e,t){return A9($K(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:p6t(e,t.events)}}async traceSession(e,t){let n=await this._corpus.listSessions(t);return t?.throwIfAborted(),h6t(n,e)}async traceEvent(e,t){let n=await this._corpus.load(e.sessionId,t);return t?.throwIfAborted(),{session:n.header,...f6t(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 Ir(`session "${e}" has no event at seq ${t}`,"SESSION_QUERY_EVENT_NOT_FOUND");let l=sn(Math.max(0,t-n)),c=sn(Math.min(s.events.length-1,t+r)),u=Lb(a),d=s.events.slice(l,c+1).map(p=>p===a?u:Lb(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 Ir(`${e} must be an integer between 0 and ${this._readWindowMax}`,"SESSION_QUERY_INVALID_WINDOW");return t}}});var ev=we((FIn,Mke)=>{"use strict";Mke.exports=x0;x0.CAPTURING_PHASE=1;x0.AT_TARGET=2;x0.BUBBLING_PHASE=3;function x0(e,t){if(this.type="",this.target=null,this.currentTarget=null,this.eventPhase=x0.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(x0,"Event");x0.prototype=Object.create(Object.prototype,{constructor:{value:x0},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 WK=we((qIn,jke)=>{"use strict";var Lke=ev();jke.exports=zK;function zK(){Lke.call(this),this.view=null,this.detail=0}o(zK,"UIEvent");zK.prototype=Object.create(Lke.prototype,{constructor:{value:zK},initUIEvent:{value:o(function(e,t,n,r,i){this.initEvent(e,t,n),this.view=r,this.detail=i},"value")}})});var VK=we((zIn,Uke)=>{"use strict";var Fke=WK();Uke.exports=HK;function HK(){Fke.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(HK,"MouseEvent");HK.prototype=Object.create(Fke.prototype,{constructor:{value:HK},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 M9=we((HIn,Bke)=>{"use strict";Bke.exports=D9;var N6t=1,$6t=3,P6t=4,D6t=5,M6t=7,L6t=8,j6t=9,F6t=11,U6t=12,q6t=13,B6t=14,z6t=15,W6t=17,H6t=18,V6t=19,G6t=20,Z6t=21,K6t=22,J6t=23,Y6t=24,X6t=25,Q6t=[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"],eSt=[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."],qke={INDEX_SIZE_ERR:N6t,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:$6t,WRONG_DOCUMENT_ERR:P6t,INVALID_CHARACTER_ERR:D6t,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:M6t,NOT_FOUND_ERR:L6t,NOT_SUPPORTED_ERR:j6t,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:F6t,SYNTAX_ERR:U6t,INVALID_MODIFICATION_ERR:q6t,NAMESPACE_ERR:B6t,INVALID_ACCESS_ERR:z6t,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:W6t,SECURITY_ERR:H6t,NETWORK_ERR:V6t,ABORT_ERR:G6t,URL_MISMATCH_ERR:Z6t,QUOTA_EXCEEDED_ERR:K6t,TIMEOUT_ERR:J6t,INVALID_NODE_TYPE_ERR:Y6t,DATA_CLONE_ERR:X6t};function D9(e){Error.call(this),Error.captureStackTrace(this,this.constructor),this.code=e,this.message=eSt[e],this.name=Q6t[e]}o(D9,"DOMException");D9.prototype.__proto__=Error.prototype;for(P9 in qke)GK={value:qke[P9]},Object.defineProperty(D9,P9,GK),Object.defineProperty(D9.prototype,P9,GK);var GK,P9});var L9=we(zke=>{zke.isApiWritable=!globalThis.__domino_frozen__});var Gs=we(Ci=>{"use strict";var Vs=M9(),la=Vs,tSt=L9().isApiWritable;Ci.NAMESPACE={HTML:"http://www.w3.org/1999/xhtml",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/",MATHML:"http://www.w3.org/1998/Math/MathML",SVG:"http://www.w3.org/2000/svg",XLINK:"http://www.w3.org/1999/xlink"};Ci.IndexSizeError=function(){throw new Vs(la.INDEX_SIZE_ERR)};Ci.HierarchyRequestError=function(){throw new Vs(la.HIERARCHY_REQUEST_ERR)};Ci.WrongDocumentError=function(){throw new Vs(la.WRONG_DOCUMENT_ERR)};Ci.InvalidCharacterError=function(){throw new Vs(la.INVALID_CHARACTER_ERR)};Ci.NoModificationAllowedError=function(){throw new Vs(la.NO_MODIFICATION_ALLOWED_ERR)};Ci.NotFoundError=function(){throw new Vs(la.NOT_FOUND_ERR)};Ci.NotSupportedError=function(){throw new Vs(la.NOT_SUPPORTED_ERR)};Ci.InvalidStateError=function(){throw new Vs(la.INVALID_STATE_ERR)};Ci.SyntaxError=function(){throw new Vs(la.SYNTAX_ERR)};Ci.InvalidModificationError=function(){throw new Vs(la.INVALID_MODIFICATION_ERR)};Ci.NamespaceError=function(){throw new Vs(la.NAMESPACE_ERR)};Ci.InvalidAccessError=function(){throw new Vs(la.INVALID_ACCESS_ERR)};Ci.TypeMismatchError=function(){throw new Vs(la.TYPE_MISMATCH_ERR)};Ci.SecurityError=function(){throw new Vs(la.SECURITY_ERR)};Ci.NetworkError=function(){throw new Vs(la.NETWORK_ERR)};Ci.AbortError=function(){throw new Vs(la.ABORT_ERR)};Ci.UrlMismatchError=function(){throw new Vs(la.URL_MISMATCH_ERR)};Ci.QuotaExceededError=function(){throw new Vs(la.QUOTA_EXCEEDED_ERR)};Ci.TimeoutError=function(){throw new Vs(la.TIMEOUT_ERR)};Ci.InvalidNodeTypeError=function(){throw new Vs(la.INVALID_NODE_TYPE_ERR)};Ci.DataCloneError=function(){throw new Vs(la.DATA_CLONE_ERR)};Ci.nyi=function(){throw new Error("NotYetImplemented")};Ci.shouldOverride=function(){throw new Error("Abstract function; should be overriding in subclass.")};Ci.assert=function(e,t){if(!e)throw new Error("Assertion failed: "+(t||"")+`
158
158
  `+new Error().stack)};Ci.expose=function(e,t){for(var n in e)Object.defineProperty(t.prototype,n,{value:e[n],writable:tSt})};Ci.merge=function(e,t){for(var n in t)e[n]=t[n]};Ci.documentOrder=function(e,t){return 3-(e.compareDocumentPosition(t)&6)};Ci.toASCIILowerCase=function(e){return e.replace(/[A-Z]+/g,function(t){return t.toLowerCase()})};Ci.toASCIIUpperCase=function(e){return e.replace(/[a-z]+/g,function(t){return t.toUpperCase()})}});var ZK=we((KIn,Hke)=>{"use strict";var S0=ev(),nSt=VK(),rSt=Gs();Hke.exports=Wke;function Wke(){}o(Wke,"EventTarget");Wke.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!==S0.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===S0.CAPTURING_PHASE&&!k.capture||m===S0.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)&&rSt.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=S0.CAPTURING_PHASE;for(var a=i.length-1;a>=0&&(r(i[a],t),!t._propagationStopped);a--);if(t._propagationStopped||(t.eventPhase=S0.AT_TARGET,r(this,t)),t.bubbles&&!t._propagationStopped){t.eventPhase=S0.BUBBLING_PHASE;for(var l=0,c=i.length;l<c&&(r(i[l],t),!t._propagationStopped);l++);}if(t._dispatching=!1,t.eventPhase=S0.AT_TARGET,t.currentTarget=null,n&&!t.defaultPrevented&&t instanceof nSt)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 KK=we((YIn,Vke)=>{"use strict";var ah=Gs(),Eu=Vke.exports={valid:o(function(e){return ah.assert(e,"list falsy"),ah.assert(e._previousSibling,"previous falsy"),ah.assert(e._nextSibling,"next falsy"),!0},"valid"),insertBefore:o(function(e,t){ah.assert(Eu.valid(e)&&Eu.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,ah.assert(Eu.valid(e)&&Eu.valid(t))},"insertBefore"),replace:o(function(e,t){ah.assert(Eu.valid(e)&&(t===null||Eu.valid(t))),t!==null&&Eu.insertBefore(t,e),Eu.remove(e),ah.assert(Eu.valid(e)&&(t===null||Eu.valid(t)))},"replace"),remove:o(function(e){ah.assert(Eu.valid(e));var t=e._previousSibling;if(t!==e){var n=e._nextSibling;t._nextSibling=n,n._previousSibling=t,e._previousSibling=e._nextSibling=e,ah.assert(Eu.valid(e))}},"remove")}});var JK=we((QIn,e4e)=>{"use strict";e4e.exports={serializeOne:uSt,\u0275escapeMatchingClosingTag:Yke,\u0275escapeClosingCommentTag:Xke,\u0275escapeProcessingInstructionContent:Qke};var Jke=Gs(),k0=Jke.NAMESPACE,Gke={STYLE:!0,SCRIPT:!0,XMP:!0,IFRAME:!0,NOEMBED:!0,NOFRAMES:!0,PLAINTEXT:!0},iSt={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},sSt={},Zke=/[&<>\u00A0]/g,Kke=/[&"<>\u00A0]/g;function aSt(e){return Zke.test(e)?e.replace(Zke,t=>{switch(t){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case"\xA0":return"&nbsp;"}}):e}o(aSt,"escape");function oSt(e){return Kke.test(e)?e.replace(Kke,t=>{switch(t){case"<":return"&lt;";case">":return"&gt;";case"&":return"&amp;";case'"':return"&quot;";case"\xA0":return"&nbsp;"}}):e}o(oSt,"escapeAttr");function lSt(e){var t=e.namespaceURI;return t?t===k0.XML?"xml:"+e.localName:t===k0.XLINK?"xlink:"+e.localName:t===k0.XMLNS?e.localName==="xmlns"?"xmlns":"xmlns:"+e.localName:e.name:e.localName}o(lSt,"attrname");function Yke(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(Yke,"escapeMatchingClosingTag");var cSt=/--!?>/;function Xke(e){return cSt.test(e)?e.replace(/(--\!?)>/g,"$1&gt;"):e}o(Xke,"escapeClosingCommentTag");function Qke(e){return e.includes(">")?e.replaceAll(">","&gt;"):e}o(Qke,"escapeProcessingInstructionContent");function uSt(e,t){var n="";switch(e.nodeType){case 1:var r=e.namespaceURI,i=r===k0.HTML,s=i||r===k0.SVG||r===k0.MATHML?e.localName:e.tagName;n+="<"+s;for(var a=0,l=e._numattrs;a<l;a++){var c=e._attr(a);n+=" "+lSt(c),c.value!==void 0&&(n+='="'+oSt(c.value)+'"')}if(n+=">",!(i&&iSt[s])){var u=e.serialize();Gke[s.toUpperCase()]&&(u=Yke(u,s)),i&&sSt[s]&&u.charAt(0)===`
@@ -5136,10 +5136,11 @@ Example:
5136
5136
  UNION ALL
5137
5137
  SELECT w.level + 1, n.inode, n.type, n.mode, n.mtime, n.size, n.link_target
5138
5138
  FROM walk w
5139
- JOIN segs s ON s.level = w.level
5140
- JOIN vfs_dirents d ON d.parent_inode = w.inode AND d.name = s.name
5139
+ CROSS JOIN segs s
5140
+ CROSS JOIN vfs_dirents d
5141
5141
  JOIN vfs_nodes n ON n.inode = d.child_inode
5142
- WHERE w.type = 'dir'
5142
+ WHERE s.level = w.level AND d.parent_inode = w.inode AND d.name = s.name
5143
+ AND w.type = 'dir'
5143
5144
  )
5144
5145
  SELECT level, inode, type, mode, mtime, size, link_target
5145
5146
  FROM walk
@@ -5839,7 +5840,7 @@ The web search request used endpoint ${JSON.stringify(e)}. Search endpoint confi
5839
5840
  .error { padding: .75rem; border-radius: .5rem; background: #461d2b; color: #ffd6df; }
5840
5841
  .hint { margin: 1.5rem 0 0; font-size: .875rem; }
5841
5842
  code { padding: .1rem .3rem; border-radius: .3rem; background: #0c1222; color: #edf2ff; }
5842
- `}o(CRe,"pageStyles");sS();var ute="enabled",dte=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")}),v4=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")}),pte=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:o(e=>e.DSH_EDGE_CONTAINER_RUNTIME===ute?"available":"needs-binding","probe")}),hBt=Object.freeze([pte,v4,dte]);function fte(e,t=hBt){return t.filter(n=>n.probe(e)==="available")}o(fte,"availableEdgeRuntimeProviders");function hte(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(hte,"resolveEdgeRuntimeSelection");function pR(e){let t=fte(e),{bash:n,container:r}=hte(t);return t.find(i=>i.id===(r??n)).shell}o(pR,"resolveEdgeRuntimeShell");function mBt(){return"dsh-edge@0.21.0-alpha.2/isolated"}o(mBt,"resolveEdgeDeploymentId");function w4(e){return{baseURL:cG(e.DEEPSEEK_BASE_URL),maxTokens:pG(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:a0(e.DEEPSEEK_MODEL),reasoningEffort:uG(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:SI(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:dG(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:S1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}o(w4,"resolveEdgeDeploymentConfig");function gBt(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}o(gBt,"edgeDeploymentApiKeyConfigured");function yBt(e){let t=cG(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}o(yBt,"projectedEdgeBaseURL");function mte(e,t){return{shell:pR(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:mBt(),apiKeyConfigured:gBt(e),baseURL:yBt(e.DEEPSEEK_BASE_URL),maxTokens:pG(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:a0(e.DEEPSEEK_MODEL),reasoningEffort:uG(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:SI(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:dG(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:S1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}o(mte,"resolveEdgeDeploymentProfile");function fR(e){w4(e);let t=mte(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:t0,upstreamVersion:r3e,status:"ready"}}o(fR,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as LXt}from"node:async_hooks";import{RpcTarget as vBt}from"cloudflare:workers";function wBt(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(wBt,"startHeartbeat");async function bBt(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(bBt,"probeComputerdHealth");var xBt="computer.internal",SBt="/health",gte="/api",kBt=8080,EBt=3e4,_Bt=2e4,TBt=1,ABt=2e3,IBt=250,CBt=2e3;function RBt(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(RBt,"bearerMatches");var mR=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??xBt,containerPort:e.containerPort??kBt,connectTimeoutMs:e.connectTimeoutMs??EBt,heartbeatIntervalMs:e.heartbeatIntervalMs??_Bt,restartAttempts:e.restartAttempts??TBt,healthProbeTimeoutMs:e.healthProbeTimeoutMs??ABt,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??IBt,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??CBt}}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 Ko(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 Ko(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=XO(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=wBt({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(uw),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(pE),i.delete(uw);let l=new Request(e,{headers:i});return this.#t.gateway.fetch(new Request(a,l))}if(new URL(e.url).pathname!==gte)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${gte} requires a websocket upgrade`,{status:400});if(!RBt(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 Ko(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 Ko(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 bBt(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 OBt(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=${RRe(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 Ko(`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:SBt,api:gte,healthTimeoutMs:r})})}catch(s){throw this.#o?.(s),this.#a(),new Ko(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${RRe(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 Ko(`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 Ko(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#a()}}};function OBt(e){return new Promise(t=>setTimeout(t,e))}o(OBt,"sleep");function RRe(e){return e instanceof Error?e.message:String(e)}o(RRe,"describeError");var ORe="computer:container-client-secret",NBt=16;function $Bt(){let e=crypto.getRandomValues(new Uint8Array(NBt));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}o($Bt,"generate");var PBt=class{static{o(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(ORe);if(typeof e=="string"&&e.length>0)return e;let t=$Bt();return await this.storage.put(ORe,t),t}},NRe="computer:container-launch-record";async function $Re(e){return{enableInternet:e.enableInternet,envDigest:await MBt(e.env)}}o($Re,"launchRecordFor");function DBt(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}o(DBt,"sameLaunch");async function MBt(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(MBt,"digestEnv");var LBt=class{static{o(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(NRe)??null}async set(e){await this.storage.put(NRe,e)}},PRe=new WeakMap;function wte(e){let t=PRe.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},PRe.set(e,t)),t}o(wte,"getContainerLifecycle");function hR(e){return wte(e).exit}o(hR,"containerExitInfo");function DRe(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}o(DRe,"formatExitReason");function MRe(e,t,n){let r=wte(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>LRe(r,i,void 0,n),s=>LRe(r,i,s,n))}o(MRe,"installContainerMonitor");async function yte(e,t){let n=wte(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}o(yte,"destroyContainerExpectingExit");async function LRe(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=DRe(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:DRe(l),exitedAt:Date.now()})}}o(LRe,"recordExit");var vte="computer:container-runtime-identity",jBt=class{static{o(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(vte)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(vte,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(vte)}},FBt=class extends vBt{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 jBt(e.storage),this.#n=new PBt(e.storage),this.#i=new LBt(e.storage)}async start(e){let t=hR(this.#t),n=await this.#n.ensure(),r=await $Re(e);if(t!==null){try{await yte(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||!DBt(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 yte(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return MRe(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await yte(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await $Re(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),MRe(this.#t,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:hR(this.#t)}}async exitInfo(){return hR(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=hR(this.#t);if(r!==null)throw new Ko(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function jRe(e){class t extends e{static{o(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new FBt(this.ctx)}}return t}o(jRe,"withWorkspaceContainer");var UBt={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function URe(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=UBt[s]??s,c=e[l];if(c===void 0)return;let u=c[a];return typeof u=="function"?u:void 0}o(URe,"resolve");function qBt(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}o(qBt,"errorResponse");async function bte(e,t,n,r,i){let s=URe(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}o(bte,"callEdgeApi");async function qRe(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(URe(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 bte(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 qBt(a,{code:"internal",message:String(c),details:{}})}}o(qRe,"dispatchEdgeApi");vr();ks();bm();import{DurableObject as jXt}from"cloudflare:workers";var gR=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 BBt(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 BBt(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(BBt,"untilAborted");import{WorkerEntrypoint as Lzn}from"cloudflare:workers";var ly=Rl(BRe(),1);import{gunzipSync as pHt}from"node:zlib";var b4=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 W=E.oldPos-S;T=E&&0<=W&&W<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 xte=class extends b4{static{o(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=WBt}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
5843
+ `}o(CRe,"pageStyles");sS();var ute="enabled",dte=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")}),v4=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")}),pte=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:o(e=>e.DSH_EDGE_CONTAINER_RUNTIME===ute?"available":"needs-binding","probe")}),hBt=Object.freeze([pte,v4,dte]);function fte(e,t=hBt){return t.filter(n=>n.probe(e)==="available")}o(fte,"availableEdgeRuntimeProviders");function hte(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(hte,"resolveEdgeRuntimeSelection");function pR(e){let t=fte(e),{bash:n,container:r}=hte(t);return t.find(i=>i.id===(r??n)).shell}o(pR,"resolveEdgeRuntimeShell");function mBt(){return"dsh-edge@0.21.0/isolated"}o(mBt,"resolveEdgeDeploymentId");function w4(e){return{baseURL:cG(e.DEEPSEEK_BASE_URL),maxTokens:pG(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:a0(e.DEEPSEEK_MODEL),reasoningEffort:uG(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:SI(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:dG(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:S1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}o(w4,"resolveEdgeDeploymentConfig");function gBt(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}o(gBt,"edgeDeploymentApiKeyConfigured");function yBt(e){let t=cG(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}o(yBt,"projectedEdgeBaseURL");function mte(e,t){return{shell:pR(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:mBt(),apiKeyConfigured:gBt(e),baseURL:yBt(e.DEEPSEEK_BASE_URL),maxTokens:pG(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:a0(e.DEEPSEEK_MODEL),reasoningEffort:uG(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:SI(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:dG(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:S1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}o(mte,"resolveEdgeDeploymentProfile");function fR(e){w4(e);let t=mte(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:t0,upstreamVersion:r3e,status:"ready"}}o(fR,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as LXt}from"node:async_hooks";import{RpcTarget as vBt}from"cloudflare:workers";function wBt(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(wBt,"startHeartbeat");async function bBt(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(bBt,"probeComputerdHealth");var xBt="computer.internal",SBt="/health",gte="/api",kBt=8080,EBt=3e4,_Bt=2e4,TBt=1,ABt=2e3,IBt=250,CBt=2e3;function RBt(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(RBt,"bearerMatches");var mR=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??xBt,containerPort:e.containerPort??kBt,connectTimeoutMs:e.connectTimeoutMs??EBt,heartbeatIntervalMs:e.heartbeatIntervalMs??_Bt,restartAttempts:e.restartAttempts??TBt,healthProbeTimeoutMs:e.healthProbeTimeoutMs??ABt,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??IBt,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??CBt}}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 Ko(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 Ko(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=XO(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=wBt({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(uw),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(pE),i.delete(uw);let l=new Request(e,{headers:i});return this.#t.gateway.fetch(new Request(a,l))}if(new URL(e.url).pathname!==gte)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${gte} requires a websocket upgrade`,{status:400});if(!RBt(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 Ko(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 Ko(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 bBt(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 OBt(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=${RRe(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 Ko(`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:SBt,api:gte,healthTimeoutMs:r})})}catch(s){throw this.#o?.(s),this.#a(),new Ko(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${RRe(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 Ko(`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 Ko(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#a()}}};function OBt(e){return new Promise(t=>setTimeout(t,e))}o(OBt,"sleep");function RRe(e){return e instanceof Error?e.message:String(e)}o(RRe,"describeError");var ORe="computer:container-client-secret",NBt=16;function $Bt(){let e=crypto.getRandomValues(new Uint8Array(NBt));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}o($Bt,"generate");var PBt=class{static{o(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(ORe);if(typeof e=="string"&&e.length>0)return e;let t=$Bt();return await this.storage.put(ORe,t),t}},NRe="computer:container-launch-record";async function $Re(e){return{enableInternet:e.enableInternet,envDigest:await MBt(e.env)}}o($Re,"launchRecordFor");function DBt(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}o(DBt,"sameLaunch");async function MBt(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(MBt,"digestEnv");var LBt=class{static{o(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(NRe)??null}async set(e){await this.storage.put(NRe,e)}},PRe=new WeakMap;function wte(e){let t=PRe.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},PRe.set(e,t)),t}o(wte,"getContainerLifecycle");function hR(e){return wte(e).exit}o(hR,"containerExitInfo");function DRe(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}o(DRe,"formatExitReason");function MRe(e,t,n){let r=wte(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>LRe(r,i,void 0,n),s=>LRe(r,i,s,n))}o(MRe,"installContainerMonitor");async function yte(e,t){let n=wte(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}o(yte,"destroyContainerExpectingExit");async function LRe(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=DRe(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:DRe(l),exitedAt:Date.now()})}}o(LRe,"recordExit");var vte="computer:container-runtime-identity",jBt=class{static{o(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(vte)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(vte,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(vte)}},FBt=class extends vBt{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 jBt(e.storage),this.#n=new PBt(e.storage),this.#i=new LBt(e.storage)}async start(e){let t=hR(this.#t),n=await this.#n.ensure(),r=await $Re(e);if(t!==null){try{await yte(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||!DBt(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 yte(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return MRe(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await yte(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await $Re(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),MRe(this.#t,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:hR(this.#t)}}async exitInfo(){return hR(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=hR(this.#t);if(r!==null)throw new Ko(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function jRe(e){class t extends e{static{o(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new FBt(this.ctx)}}return t}o(jRe,"withWorkspaceContainer");var UBt={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function URe(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=UBt[s]??s,c=e[l];if(c===void 0)return;let u=c[a];return typeof u=="function"?u:void 0}o(URe,"resolve");function qBt(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}o(qBt,"errorResponse");async function bte(e,t,n,r,i){let s=URe(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}o(bte,"callEdgeApi");async function qRe(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(URe(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 bte(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 qBt(a,{code:"internal",message:String(c),details:{}})}}o(qRe,"dispatchEdgeApi");vr();ks();bm();import{DurableObject as jXt}from"cloudflare:workers";var gR=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 BBt(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 BBt(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(BBt,"untilAborted");import{WorkerEntrypoint as Lzn}from"cloudflare:workers";var ly=Rl(BRe(),1);import{gunzipSync as pHt}from"node:zlib";var b4=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 W=E.oldPos-S;T=E&&0<=W&&W<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 xte=class extends b4{static{o(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=WBt}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
5843
5844
  `))&&(t=t.trim()),(!r.newlineIsToken||!n.includes(`
5844
5845
  `))&&(n=n.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
5845
5846
  `)&&(t=t.slice(0,-1)),n.endsWith(`