dsh-edge 0.22.0-alpha.1 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
package/worker/direct/index.js
CHANGED
|
@@ -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"?ex(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=>ex(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)&&ex(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:tke(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();WC();XK();HC();QK();a(Ws,"validate")});var VC,nke=ce(()=>{WC();eZ();VC=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 rke=ce(()=>{YK();WC();XK();HC();eke();QK();eZ();nke()});var GC,ike=ce(()=>{rke();GC=class{static{a(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let n=new VC(t,this.draft,this.shortcircuit);return r=>{let i=n.validate(r);return i.valid?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:i.errors.map(s=>`${s.instanceLocation}: ${s.error}`).join("; ")}}}}});var Do,KC=ce(()=>{"use strict";Do={probeTimeoutMs:3e4,callTimeoutMs:6e4,maxToolsPerServer:128,maxCatalogPages:10,maxCatalogBytes:131072,maxDescriptionLength:512,maxErrorMessageChars:300,maxPublicNameLength:64,maxInstructionsLength:1024,metaToolThreshold:20}});import{createHash as vwt}from"node:crypto";function bwt(e){let t=e.replace(/[.*+?^${}()|[\]\\]/gu,n=>n==="*"?"\0":`\\${n}`);return new RegExp(`^${t.replaceAll("\0",".*")}$`)}function ske(e,t,n){let r=t??"read_only";return r==="allow_all"?"allow":r==="approve_all"?"ask":n===!0?"allow":n===!1?"ask":wwt.some(i=>bwt(i).test(e))?"allow":"ask"}function Rf(e){return e.replace(/Bearer\s+[^\s"']+/giu,"Bearer ***").replace(/(https?:\/\/[^\s"'?]+)\?[^\s"']*/giu,"$1?***").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/gu,"").slice(0,Do.maxErrorMessageChars)}function oke(e,t){let n=`mcp__${e}__${t}`,r=n.replace(/[^A-Za-z0-9_-]/gu,"_");if(r===n&&r.length<=Do.maxPublicNameLength)return r;let i=xwt(e,t),s=Do.maxPublicNameLength-i.length-1;return`${r.slice(0,s)}_${i}`}function xwt(e,t){return vwt("sha256").update(`${e}\0${t}`).digest("hex").slice(0,12)}function ake(e){if(!(e==null||typeof e!="object"))try{let t=JSON.parse(JSON.stringify(e));return F0(t),t}catch{return}}function Ewt(e){return Swt.has(e)}function cke(e){return e.type!=="image"||e.data===void 0||e.mimeType===void 0||!Ewt(e.mimeType)||!kwt.test(e.data)?void 0:{data:Uint8Array.from(atob(e.data),n=>n.charCodeAt(0)),mediaType:e.mimeType}}function lke(e){return e.some(t=>t.type==="image"&&t.data!==void 0)}function g6(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(``);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 wwt,Swt,kwt,ZC=ce(()=>{"use strict";ao();KC();wwt=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a(bwt,"globToRegExp");a(ske,"evaluateMcpToolPolicy");a(Rf,"scrubMcpErrorMessage");a(oke,"publicToolName");a(xwt,"hashSuffix");a(ake,"supportedOutputSchema");Swt=new Set(["image/png","image/jpeg"]),kwt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(Ewt,"isImageMediaType");a(cke,"decodeImageBlock");a(lke,"containsImage");a(g6,"mapMcpResultToContentBlocks")});var tZ,uke=ce(()=>{tZ={name:"dsh-edge",version:"0.22.0-alpha.1",description:"Your DeepSeek Harness, anywhere \u2014 deploy a persistent personal coding agent to Cloudflare Workers in one command",author:"pawaca",license:"MIT",type:"module",bin:{"dsh-edge":"scripts/cli.mjs"},files:["dist","worker","scripts/*.d.mts","scripts/*.mjs","wrangler.jsonc","README.md","README.zh.md","LICENSE","THIRD_PARTY_NOTICES.md"],repository:{type:"git",url:"git+https://github.com/pawaca/dsh-edge.git",directory:"apps/dsh-edge"},homepage:"https://github.com/pawaca/dsh-edge#readme",bugs:{url:"https://github.com/pawaca/dsh-edge/issues"},keywords:["deepseek","deepseek-harness","ai-agents","byok","cloudflare-workers","durable-objects","self-hosted"],engines:{node:">=22.14.0"},publishConfig:{access:"public"},dshEdge:{upstreamVersion:"0.2.0-rc.2"},scripts:{"bundle:direct":"pnpm run web:build && pnpm --dir standalone run build:worker:direct && node standalone/scripts/promote.mjs direct","bundle:isolated":"pnpm run web:build && pnpm --dir standalone run build:worker:isolated && node standalone/scripts/promote.mjs isolated","bundle:workers":"pnpm --dir standalone run build && pnpm --dir standalone run verify && node standalone/scripts/promote.mjs all",dev:"pnpm run bundle:direct && node scripts/dev.mjs direct","dev:isolated":"pnpm run bundle:isolated && node scripts/dev.mjs isolated","dev:container":"pnpm run bundle:isolated && node scripts/dev.mjs container","dsh-edge":"node scripts/cli.mjs","example:install":"node examples/install-keyless.mjs","install:cloudflare":"pnpm run bundle:workers && node scripts/cli.mjs install","legal:write":"node scripts/legal-files.mjs write","pack:verify":"node scripts/verify-packed.mjs",prepack:"node scripts/legal-files.mjs verify && pnpm run bundle:workers","web:build":"pnpm --dir standalone run build:web && node standalone/scripts/promote.mjs web",test:"vitest run --root ../.. --project edge-runtime","test:integration":"pnpm run bundle:workers && node tests/run-session-integration.mjs","test:container":"pnpm run bundle:isolated && node tests/container.integration.mjs","test:snapshot":"vitest run --root ../.. --config apps/dsh-edge/vitest.snapshot.config.ts",typecheck:"tsc --noEmit"},dependencies:{"@clack/prompts":"1.7.0","compare-versions":"6.1.1",execa:"^10.0.1","jsonc-parser":"^3.3.1",wrangler:"4.129.0"},devDependencies:{"@cfworker/json-schema":"^4.1.1","@cloudflare/computer":"0.3.1","@cloudflare/workers-types":"5.20260904.1","@deepseek-ai/cordis":"4.0.4","@deepseek-ai/cosmokit":"1.8.5","@deepseek-ai/dsh-agent":"0.2.0-rc.2","@deepseek-ai/dsh-agent-instructions":"0.2.0-rc.2","@deepseek-ai/dsh-agent-loop":"0.2.0-rc.2","@deepseek-ai/dsh-anonymous-user-id":"0.2.0-rc.2","@deepseek-ai/dsh-api-gateway":"0.2.0-rc.2","@deepseek-ai/dsh-api-job-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-remotes":"0.2.0-rc.2","@deepseek-ai/dsh-api-session-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-settings-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-workspace-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-workspace-files":"0.2.0-rc.2","@deepseek-ai/dsh-attachment":"0.2.0-rc.2","@deepseek-ai/dsh-brand":"0.2.0-rc.2","@deepseek-ai/dsh-client-locale":"0.2.0-rc.2","@deepseek-ai/dsh-client-store":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-chat":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-conversation":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-settings":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-settings-general":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-theme":"0.2.0-rc.2","@deepseek-ai/dsh-command-compact":"0.2.0-rc.2","@deepseek-ai/dsh-command-goal":"0.2.0-rc.2","@deepseek-ai/dsh-commands":"0.2.0-rc.2","@deepseek-ai/dsh-compaction":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-basic":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-tool-result-pruner":"0.2.0-rc.2","@deepseek-ai/dsh-credentials":"0.2.0-rc.2","@deepseek-ai/dsh-file-reference":"0.2.0-rc.2","@deepseek-ai/dsh-fs":"0.2.0-rc.2","@deepseek-ai/dsh-fs-observation-policy":"0.2.0-rc.2","@deepseek-ai/dsh-goal":"0.2.0-rc.2","@deepseek-ai/dsh-goal-round-driver":"0.2.0-rc.2","@deepseek-ai/dsh-home-paths":"0.2.0-rc.2","@deepseek-ai/dsh-host-directory-picker":"0.2.0-rc.2","@deepseek-ai/dsh-host-plugin-inventory":"0.2.0-rc.2","@deepseek-ai/dsh-invariants":"0.2.0-rc.2","@deepseek-ai/dsh-jobs":"0.2.0-rc.2","@deepseek-ai/dsh-jobs-local":"0.2.0-rc.2","@deepseek-ai/dsh-launch-environment":"0.2.0-rc.2","@deepseek-ai/dsh-llm":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek-api-key":"0.2.0-rc.2","@deepseek-ai/dsh-llm-retry":"0.2.0-rc.2","@deepseek-ai/dsh-message-feedback":"0.2.0-rc.2","@deepseek-ai/dsh-output-retention":"0.2.0-rc.2","@deepseek-ai/dsh-plan-mode":"0.2.0-rc.2","@deepseek-ai/dsh-ptc-runtime":"0.2.0-rc.2","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.0-rc.2","@deepseek-ai/dsh-sandbox":"0.2.0-rc.2","@deepseek-ai/dsh-schedule":"0.2.0-rc.2","@deepseek-ai/dsh-scope":"0.2.0-rc.2","@deepseek-ai/dsh-session":"0.2.0-rc.2","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.0-rc.2","@deepseek-ai/dsh-session-format":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-catalog":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.0-rc.2","@deepseek-ai/dsh-session-persistence":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection-cache":"0.2.0-rc.2","@deepseek-ai/dsh-session-stats":"0.2.0-rc.2","@deepseek-ai/dsh-session-query":"0.2.0-rc.2","@deepseek-ai/dsh-session-reference":"0.2.0-rc.2","@deepseek-ai/dsh-session-title":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-llm":"0.2.0-rc.2","@deepseek-ai/dsh-settings":"0.2.0-rc.2","@deepseek-ai/dsh-skill":"0.2.0-rc.2","@deepseek-ai/dsh-spill":"0.2.0-rc.2","@deepseek-ai/dsh-spill-policy":"0.2.0-rc.2","@deepseek-ai/dsh-storage":"0.2.0-rc.2","@deepseek-ai/dsh-storage-domain":"0.2.0-rc.2","@deepseek-ai/dsh-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-in-process-driver":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-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-present":"0.2.0-rc.2","@deepseek-ai/dsh-tool-todo":"0.2.0-rc.2","@deepseek-ai/dsh-tool-web":"0.2.0-rc.2","@deepseek-ai/dsh-tool-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-tools":"0.2.0-rc.2","@deepseek-ai/dsh-typert-protocol":"0.2.0-rc.2","@deepseek-ai/dsh-typert-registry":"0.2.0-rc.2","@deepseek-ai/dsh-user-approval":"0.2.0-rc.2","@deepseek-ai/dsh-user-questions":"0.2.0-rc.2","@deepseek-ai/dsh-util-values":"0.2.0-rc.2","@deepseek-ai/dsh-web":"0.2.0-rc.2","@deepseek-ai/dsh-web-fetch-http":"0.2.0-rc.2","@deepseek-ai/dsh-web-search-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-workspace":"0.2.0-rc.2","@deepseek-ai/schemastery":"3.18.4","@mixmark-io/domino":"2.2.0","@modelcontextprotocol/sdk":"1.30.0",acorn:"8.18.0","fast-png":"8.0.0","jpeg-js":"0.4.4","just-bash":"3.4.2",minimatch:"10.2.6",playwright:"^1.49.0",re2js:"1.3.3",sucrase:"3.35.1",typescript:"^6.0.3",vitest:"^4.1.8",ws:"^8.21.0"}}});var _y,dke,pke,y6=ce(()=>{"use strict";uke();_y=tZ.version,dke=tZ.dshEdge.upstreamVersion,pke=`npx dsh-edge@${_y.includes("-")?"next":"latest"} upgrade`});function Cwt(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 Rwt(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 Twt)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(Rwt(i)){let s=Cwt(i),o=s??i;for(let c of Awt)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 Iwt)if(c.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function Owt(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function fke(e,t,n){im(e);let r=new zC(new URL(e),{requestInit:{headers:Owt(t),signal:n},fetch:Ty}),i=new UC({name:"dsh-edge",version:_y},{capabilities:{},jsonSchemaValidator:$wt});return await i.connect(r),{client:i,close:a(async()=>{await i.close().catch(()=>{})},"close")}}async function hke(e,t,n){let r=AbortSignal.timeout(Do.probeTimeoutMs),i;try{i=await fke(t,n,r)}catch(c){throw new Error(Rf(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<Do.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>=Do.maxToolsPerServer)break;let v=oke(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=ake(y.outputSchema);c.push({name:y.name,publicName:v,description:y.description??"",inputSchema:y.inputSchema??{type:"object"},...b!==void 0?{outputSchema:b}:{},...w!==void 0?{annotations:{readOnlyHint:w}}:{}})}if(c.length>=Do.maxToolsPerServer||(d=g.nextCursor??void 0,d===void 0))break;if(u.has(d))throw new Error("Server repeated a tools/list continuation cursor");u.add(d)}let p=s.getServerVersion?.(),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,Do.maxInstructionsLength):void 0}}finally{await o()}}async function YC(e,t,n,r,i,s){let o=s??Do.callTimeoutMs,c=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),l;try{l=await fke(e,r,c)}catch(u){throw new Error(Rf(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(Rf(u instanceof Error?u.message:String(u)))}finally{await l.close()}}var Twt,Awt,Iwt,$wt,Ty,v6=ce(()=>{"use strict";ySe();YSe();ike();ZC();KC();y6();Twt=[".internal",".local",".localhost"],Awt=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],Iwt=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(Cwt,"extractMappedIPv4");a(Rwt,"isIpAddress");a(im,"assertSafeUrl");a(Owt,"buildHeaders");$wt=new GC,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(fke,"connectClient");a(hke,"probe");a(YC,"callTool")});import{Buffer as Nwt}from"node:buffer";function Lwt(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Mwt.has(e.code)}function gke(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Dwt.has(e.code)}function yke(e,t,n){let r=Nwt.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 jwt(e){return yke(e,"reject","INVALID_IMAGE_BASE64")}function Fwt(e){return{data:jwt(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function w6(e,t){return e.saveImages(t.map(Fwt))}async function qwt(e,t){return e.saveFile({data:yke(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function vke(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 mke,Pwt,Dwt,Mwt,ur,rZ,sm=ce(()=>{Yn();mke=["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"],Pwt=[...mke,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],Dwt=new Set(mke),Mwt=new Set(Pwt),ur=class extends Error{static{a(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};a(Lwt,"isAttachmentError");a(gke,"isImageAdmissionError");a(yke,"decodeCanonicalBase64");a(jwt,"decodeBase64");a(Fwt,"saveInput");a(w6,"admitEncodedImages");a(qwt,"admitEncodedFile");a(vke,"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 w6(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 qwt(this,e)}isAttachmentError(e){return Lwt(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 XC={};hn(XC,{buildAuthorizationUrl:()=>Zwt,discoverEndpoints:()=>Gwt,exchangeCode:()=>Ywt,isTokenExpired:()=>Xwt,refreshToken:()=>Jwt,registerClient:()=>Kwt});function Ske(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 Vwt(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 Gwt(e){let t=AbortSignal.timeout(JC),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 Kwt(e,t,n){let r=AbortSignal.timeout(JC);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 Zwt(e,t,n,r,i){let s=Ske(32),o=Ske(64),c=await Vwt(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 Ywt(e,t,n,r,i,s){let o=AbortSignal.timeout(JC),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 kke(await l.json())}async function Jwt(e,t,n,r){let i=AbortSignal.timeout(JC),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 kke(await o.json())}function kke(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 Xwt(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var JC,QC=ce(()=>{"use strict";v6();JC=1e4;a(Ske,"randomString");a(Vwt,"sha256Base64Url");a(Gwt,"discoverEndpoints");a(Kwt,"registerClient");a(Zwt,"buildAuthorizationUrl");a(Ywt,"exchangeCode");a(Jwt,"refreshToken");a(kke,"parseTokenResponse");a(Xwt,"isTokenExpired")});var Un,Oke,tx=ce(()=>{Yn();gr();Un=class extends zr{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},Oke=class extends Et{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new Un("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function SZ(e){return u9.test(e)}function d9(e){return e.invocation.modelInvocable}function rx(e){return e.invocation.userInvocable}function kZ(e){let t=Mxt(e);return[`<skill_content name="${Lxt(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 wwt,Swt,kwt,ZC=ce(()=>{"use strict";ao();KC();wwt=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a(bwt,"globToRegExp");a(ske,"evaluateMcpToolPolicy");a(Rf,"scrubMcpErrorMessage");a(oke,"publicToolName");a(xwt,"hashSuffix");a(ake,"supportedOutputSchema");Swt=new Set(["image/png","image/jpeg"]),kwt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(Ewt,"isImageMediaType");a(cke,"decodeImageBlock");a(lke,"containsImage");a(g6,"mapMcpResultToContentBlocks")});var tZ,uke=ce(()=>{tZ={name:"dsh-edge",version:"0.22.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-command-compact":"0.2.0-rc.2","@deepseek-ai/dsh-command-goal":"0.2.0-rc.2","@deepseek-ai/dsh-commands":"0.2.0-rc.2","@deepseek-ai/dsh-compaction":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-basic":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-tool-result-pruner":"0.2.0-rc.2","@deepseek-ai/dsh-credentials":"0.2.0-rc.2","@deepseek-ai/dsh-file-reference":"0.2.0-rc.2","@deepseek-ai/dsh-fs":"0.2.0-rc.2","@deepseek-ai/dsh-fs-observation-policy":"0.2.0-rc.2","@deepseek-ai/dsh-goal":"0.2.0-rc.2","@deepseek-ai/dsh-goal-round-driver":"0.2.0-rc.2","@deepseek-ai/dsh-home-paths":"0.2.0-rc.2","@deepseek-ai/dsh-host-directory-picker":"0.2.0-rc.2","@deepseek-ai/dsh-host-plugin-inventory":"0.2.0-rc.2","@deepseek-ai/dsh-invariants":"0.2.0-rc.2","@deepseek-ai/dsh-jobs":"0.2.0-rc.2","@deepseek-ai/dsh-jobs-local":"0.2.0-rc.2","@deepseek-ai/dsh-launch-environment":"0.2.0-rc.2","@deepseek-ai/dsh-llm":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek-api-key":"0.2.0-rc.2","@deepseek-ai/dsh-llm-retry":"0.2.0-rc.2","@deepseek-ai/dsh-message-feedback":"0.2.0-rc.2","@deepseek-ai/dsh-output-retention":"0.2.0-rc.2","@deepseek-ai/dsh-plan-mode":"0.2.0-rc.2","@deepseek-ai/dsh-ptc-runtime":"0.2.0-rc.2","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.0-rc.2","@deepseek-ai/dsh-sandbox":"0.2.0-rc.2","@deepseek-ai/dsh-schedule":"0.2.0-rc.2","@deepseek-ai/dsh-scope":"0.2.0-rc.2","@deepseek-ai/dsh-session":"0.2.0-rc.2","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.0-rc.2","@deepseek-ai/dsh-session-format":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-catalog":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.0-rc.2","@deepseek-ai/dsh-session-persistence":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection-cache":"0.2.0-rc.2","@deepseek-ai/dsh-session-stats":"0.2.0-rc.2","@deepseek-ai/dsh-session-query":"0.2.0-rc.2","@deepseek-ai/dsh-session-reference":"0.2.0-rc.2","@deepseek-ai/dsh-session-title":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-llm":"0.2.0-rc.2","@deepseek-ai/dsh-settings":"0.2.0-rc.2","@deepseek-ai/dsh-skill":"0.2.0-rc.2","@deepseek-ai/dsh-spill":"0.2.0-rc.2","@deepseek-ai/dsh-spill-policy":"0.2.0-rc.2","@deepseek-ai/dsh-storage":"0.2.0-rc.2","@deepseek-ai/dsh-storage-domain":"0.2.0-rc.2","@deepseek-ai/dsh-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-in-process-driver":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-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-present":"0.2.0-rc.2","@deepseek-ai/dsh-tool-todo":"0.2.0-rc.2","@deepseek-ai/dsh-tool-web":"0.2.0-rc.2","@deepseek-ai/dsh-tool-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-tools":"0.2.0-rc.2","@deepseek-ai/dsh-typert-protocol":"0.2.0-rc.2","@deepseek-ai/dsh-typert-registry":"0.2.0-rc.2","@deepseek-ai/dsh-user-approval":"0.2.0-rc.2","@deepseek-ai/dsh-user-questions":"0.2.0-rc.2","@deepseek-ai/dsh-util-values":"0.2.0-rc.2","@deepseek-ai/dsh-web":"0.2.0-rc.2","@deepseek-ai/dsh-web-fetch-http":"0.2.0-rc.2","@deepseek-ai/dsh-web-search-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-workspace":"0.2.0-rc.2","@deepseek-ai/schemastery":"3.18.4","@mixmark-io/domino":"2.2.0","@modelcontextprotocol/sdk":"1.30.0",acorn:"8.18.0","fast-png":"8.0.0","jpeg-js":"0.4.4","just-bash":"3.4.2",minimatch:"10.2.6",playwright:"^1.49.0",re2js:"1.3.3",sucrase:"3.35.1",typescript:"^6.0.3",vitest:"^4.1.8",ws:"^8.21.0"}}});var _y,dke,pke,y6=ce(()=>{"use strict";uke();_y=tZ.version,dke=tZ.dshEdge.upstreamVersion,pke=`npx dsh-edge@${_y.includes("-")?"next":"latest"} upgrade`});function Cwt(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 Rwt(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 Twt)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(Rwt(i)){let s=Cwt(i),o=s??i;for(let c of Awt)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 Iwt)if(c.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function Owt(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function fke(e,t,n){im(e);let r=new zC(new URL(e),{requestInit:{headers:Owt(t),signal:n},fetch:Ty}),i=new UC({name:"dsh-edge",version:_y},{capabilities:{},jsonSchemaValidator:$wt});return await i.connect(r),{client:i,close:a(async()=>{await i.close().catch(()=>{})},"close")}}async function hke(e,t,n){let r=AbortSignal.timeout(Do.probeTimeoutMs),i;try{i=await fke(t,n,r)}catch(c){throw new Error(Rf(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<Do.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>=Do.maxToolsPerServer)break;let v=oke(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=ake(y.outputSchema);c.push({name:y.name,publicName:v,description:y.description??"",inputSchema:y.inputSchema??{type:"object"},...b!==void 0?{outputSchema:b}:{},...w!==void 0?{annotations:{readOnlyHint:w}}:{}})}if(c.length>=Do.maxToolsPerServer||(d=g.nextCursor??void 0,d===void 0))break;if(u.has(d))throw new Error("Server repeated a tools/list continuation cursor");u.add(d)}let p=s.getServerVersion?.(),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,Do.maxInstructionsLength):void 0}}finally{await o()}}async function YC(e,t,n,r,i,s){let o=s??Do.callTimeoutMs,c=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),l;try{l=await fke(e,r,c)}catch(u){throw new Error(Rf(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(Rf(u instanceof Error?u.message:String(u)))}finally{await l.close()}}var Twt,Awt,Iwt,$wt,Ty,v6=ce(()=>{"use strict";ySe();YSe();ike();ZC();KC();y6();Twt=[".internal",".local",".localhost"],Awt=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],Iwt=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(Cwt,"extractMappedIPv4");a(Rwt,"isIpAddress");a(im,"assertSafeUrl");a(Owt,"buildHeaders");$wt=new GC,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(fke,"connectClient");a(hke,"probe");a(YC,"callTool")});import{Buffer as Nwt}from"node:buffer";function Lwt(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Mwt.has(e.code)}function gke(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Dwt.has(e.code)}function yke(e,t,n){let r=Nwt.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 jwt(e){return yke(e,"reject","INVALID_IMAGE_BASE64")}function Fwt(e){return{data:jwt(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function w6(e,t){return e.saveImages(t.map(Fwt))}async function qwt(e,t){return e.saveFile({data:yke(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function vke(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 mke,Pwt,Dwt,Mwt,ur,rZ,sm=ce(()=>{Yn();mke=["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"],Pwt=[...mke,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],Dwt=new Set(mke),Mwt=new Set(Pwt),ur=class extends Error{static{a(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};a(Lwt,"isAttachmentError");a(gke,"isImageAdmissionError");a(yke,"decodeCanonicalBase64");a(jwt,"decodeBase64");a(Fwt,"saveInput");a(w6,"admitEncodedImages");a(qwt,"admitEncodedFile");a(vke,"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 w6(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 qwt(this,e)}isAttachmentError(e){return Lwt(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 XC={};hn(XC,{buildAuthorizationUrl:()=>Zwt,discoverEndpoints:()=>Gwt,exchangeCode:()=>Ywt,isTokenExpired:()=>Xwt,refreshToken:()=>Jwt,registerClient:()=>Kwt});function Ske(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 Vwt(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 Gwt(e){let t=AbortSignal.timeout(JC),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 Kwt(e,t,n){let r=AbortSignal.timeout(JC);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 Zwt(e,t,n,r,i){let s=Ske(32),o=Ske(64),c=await Vwt(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 Ywt(e,t,n,r,i,s){let o=AbortSignal.timeout(JC),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 kke(await l.json())}async function Jwt(e,t,n,r){let i=AbortSignal.timeout(JC),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 kke(await o.json())}function kke(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 Xwt(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var JC,QC=ce(()=>{"use strict";v6();JC=1e4;a(Ske,"randomString");a(Vwt,"sha256Base64Url");a(Gwt,"discoverEndpoints");a(Kwt,"registerClient");a(Zwt,"buildAuthorizationUrl");a(Ywt,"exchangeCode");a(Jwt,"refreshToken");a(kke,"parseTokenResponse");a(Xwt,"isTokenExpired")});var Un,Oke,tx=ce(()=>{Yn();gr();Un=class extends zr{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},Oke=class extends Et{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new Un("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function SZ(e){return u9.test(e)}function d9(e){return e.invocation.modelInvocable}function rx(e){return e.invocation.userInvocable}function kZ(e){let t=Mxt(e);return[`<skill_content name="${Lxt(e.name)}">`,"<skill_resources>",...t,"</skill_resources>","","<skill_instructions>",e.content,"</skill_instructions>","</skill_content>"].join(`
|
|
156
156
|
`)}function Mxt(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 Lxt(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<")}function nx(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function Fxt(e,t){if(Array.isArray(e))return{candidates:e,complete:!0};if(e===null||typeof e!="object")throw Xke(t);let n=e;if(!Array.isArray(n.candidates)||typeof n.complete!="boolean")throw Xke(t);return n}function Xke(e){return new TypeError(`skill provider "${e}" list() must return an array or { candidates, complete } observation`)}function Uxt(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:Dxt,locator:e,...e.path!==void 0?{path:e.path}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}function Bxt(e,t){if(typeof e.name!="string")throw new TypeError(`skill provider "${t}" returned a non-string skill name`);if(!u9.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 zxt(e){if(!u9.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 Hxt(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(!u9.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 Wxt(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 Vxt(e,t){return nEe(e.name,t.name)}function nEe(e,t){return e<t?-1:e>t?1:0}function Gxt(e,t){return e.candidate.rank-t.candidate.rank||e.providerOrder-t.providerOrder||e.localOrder-t.localOrder}function Kxt(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 Qke(e,t){return t===void 0?e:(k6(t),new Promise((n,r)=>{let i=a(()=>{t.removeEventListener("abort",s)},"cleanup"),s=a(()=>{i(),r(l9(t.reason))},"onAbort");t.addEventListener("abort",s,{once:!0}),e.then(o=>{i(),n(o)},o=>{i(),r(l9(o))})}))}function k6(e){if(e?.aborted===!0)throw l9(e.reason)}function l9(e){try{if(e instanceof Error)return e}catch{}return new Error(c9(e))}function c9(e){try{return String(e)}catch{return"[unrenderable thrown value]"}}var u9,Jke,Pxt,a9,Dxt,eEe,jxt,tEe,qxt,ix=ce(()=>{Yn();rs();Kc();pn();u9=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Jke=128,Pxt=2,a9="runtime",Dxt=250,eEe=600;a(SZ,"isSkillName");a(d9,"isModelInvocable");a(rx,"isUserInvocable");a(kZ,"renderSkillContent");a(Mxt,"renderResourceHint");a(Lxt,"escapeAttr");a(nx,"escapeText");jxt=class{static{a(this,"SkillLayer")}providers;runtime=new Map;constructor(e){this.providers=new pf(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}},tEe=class extends Et{static{a(this,"SkillRegistry")}static Config=q.object({collectCacheMaxEntries:q.number().default(Jke)});collectCacheMaxEntries;layers=new ff(e=>new jxt(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??Jke,Kxt("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===a9)throw new Error(`"${a9}" 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){zxt(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??a9};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=>Wxt(n.candidate)).sort(Vxt),complete:t.cacheable}}async get(e,t={}){if(!SZ(e))return;let n=await this.collect(t);k6(t.signal);let r=n.entries.get(e);if(r===void 0)return;let i=await Qke(r.provider.get(r.candidate,t),t.signal);if(i!==void 0){if(Hxt(i),i.name!==r.candidate.name){this.invalidateEntry(r);return}return i}}async collect(e){k6(e.signal);let t=1;for(;;){let n=this.revision,r=this.collectCacheKey(e.cwd,Gk(e.scope),n),i=this.collectCache.get(r);if(i!==void 0)return{entries:i,cacheable:!0};let s=await this.collectFresh(e);if(k6(e.signal),n!==this.revision){if(t<Pxt){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(Gxt);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){k6(t.signal);let n=[],r=!0,i=0;for(let s of[...e.runtime.values()].sort((o,c)=>nEe(o.name,c.name)))n.push({candidate:Uxt(s),provider:qxt,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 Qke(s.list(t),t.signal)}catch(d){if(t.signal?.aborted===!0)throw l9(t.signal.reason);r=!1,this.ctx.logger.warn(`skill provider "${s.name}" skipped: ${c9(d)}`)}if(l===void 0)continue;let u=Fxt(l,s.name);u.complete||(r=!1);for(let d of u.candidates)Bxt(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: ${c9(n)}`)})}catch(t){this.ctx.logger.warn(`skills/change listener threw: ${c9(t)}`)}}};a(Fxt,"normalizeProviderObservation");a(Xke,"invalidProviderObservation");qxt={name:a9,list(){return Promise.resolve([])},get(e){return Promise.resolve(e.locator)}};a(Uxt,"runtimeCandidate");a(Bxt,"validateCandidate");a(zxt,"validateRuntimeSkill");a(Hxt,"validateDefinition");a(Wxt,"toSummary");a(EZ,"validateInvocation");a(Vxt,"compareSkillSummary");a(nEe,"compareCodePoints");a(Gxt,"compareIndexedCandidates");a(Kxt,"assertPositiveInteger");a(Qke,"waitWithAbort");a(k6,"throwIfAborted");a(l9,"toError");a(c9,"errorMessage")});var pd,ax=ce(()=>{pd=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,k_e,uY=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"}},k_e=class extends Et{static{a(this,"DirectoryPicker")}constructor(e){super(e,"directoryPicker")}}});var mTe=be((MUn,vR)=>{var hTe=hTe||function(e){return Buffer.from(e).toString("base64")};function zTt(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 wn=Ee+yt,Vt=Ee-yt,Ut=ut+Ke,ae=ut-Ke,Pe=ze+st,Ge=ze-st,ct=je+wt,Ot=je-wt,Xe=wn+ct,cn=wn-ct,rn=Ut+Pe,bn=Ut-Pe;oe[Oe]=Xe+rn,oe[Oe+4]=Xe-rn;var jt=(bn+cn)*.707106781;oe[Oe+2]=cn+jt,oe[Oe+6]=cn-jt,Xe=Ot+Ge,rn=Ge+ae,bn=ae+Vt;var Lr=(Xe-bn)*.382683433,Ur=.5411961*Xe+Lr,ms=1.306562965*bn+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,po=Ee-yt,Io=ut+Ke,Bt=ut-Ke,jn=ze+st,Co=ze-st,Aa=je+wt,Vo=je-wt,Go=Bs+Aa,na=Bs-Aa,Ia=Io+jn,nc=Io-jn;oe[Oe]=Go+Ia,oe[Oe+32]=Go-Ia;var eu=(nc+na)*.707106781;oe[Oe+16]=na+eu,oe[Oe+48]=na-eu,Go=Vo+Co,Ia=Co+Bt,nc=Bt+po;var cl=(Go-nc)*.382683433,qd=.5411961*Go+cl,Ud=1.306562965*nc+cl,Bd=Ia*.707106781,zd=po+Bd,vh=po-Bd;oe[Oe+40]=vh+qd,oe[Oe+24]=vh-qd,oe[Oe+8]=zd+Ud,oe[Oe+56]=zd-Ud,Oe++}var Gp;for(_t=0;_t<ht;++_t)Gp=oe[_t]*Le[_t],g[_t]=Gp>0?Gp+.5|0:Gp-.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 wn=63;wn>0&&y[wn]==0;wn--);if(wn==0)return Q(je),Ee;for(var Vt=1,Ut;Vt<=wn;){for(var ae=Vt;y[Vt]==0&&Vt<=wn;++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 wn!=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,wn,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++],wn=wt[ae++],Vt=wt[ae++],S[ct]=(T[ht]+T[wn+256>>0]+T[Vt+512>>0]>>16)-128,k[ct]=(T[ht+768>>0]+T[wn+1024>>0]+T[Vt+1280>>0]>>16)-128,E[ct]=(T[ht+1280>>0]+T[wn+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 vR>"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(zTt,"JPEGEncoder");typeof vR<"u"?vR.exports=fTe:typeof window<"u"&&(window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=fTe);function fTe(e,t){typeof t>"u"&&(t=50);var n=new zTt(t),r=n.encode(e,t);return{data:r,width:e.width,height:e.height}}a(fTe,"encode")});var yTe=be((jUn,SJ)=>{var xJ=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 wn=1;wn<64;){var Vt=Q(Oe.huffmanTableAC),Ut=Vt&15,ae=Vt>>4;if(Ut===0){if(ae<15)break;wn+=16;continue}wn+=ae;var Pe=t[wn];_t[Pe]=ne(Ut),wn++}}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 wn=Q(Oe.huffmanTableAC),Vt=wn&15,Ut=wn>>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,wn=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,wn=ae>>4;if(Pe===0)wn<15?(Se=z(wn)+(1<<wn),ue=4):(wn=16,ue=1);else{if(Pe!==1)throw new Error("invalid ACn encoding");de=ne(Pe),ue=wn?2:3}continue;case 1:case 2:_t[Vt]?_t[Vt]+=(X()<<j)*Ut:(wn--,wn===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,wn){var Vt=Gt/U|0,Ut=Gt%U,ae=Vt*Oe.v+ht,Pe=Ut*Oe.h+wn;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,wn=Gt%Oe.blocksPerLine;Oe.blocks[ht]===void 0&&$.tolerantDecoding||_t(Oe,Oe.blocks[ht][wn])}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),bn=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=bn,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++],wn=S[E++],Vt=h(S,E,J,yt,I,Gt,ht,wn>>4,wn&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 SJ<"u"?SJ.exports=gTe:typeof window<"u"&&(window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=gTe);function gTe(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 xJ;s.opts=r,xJ.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),s.parse(i);var o=r.formatAsRGBA?4:3,c=s.width*s.height*o;try{xJ.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(gTe,"decode")});var wTe=be((qUn,vTe)=>{var HTt=mTe(),WTt=yTe();vTe.exports={encode:HTt,decode:WTt}});function e3e(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 vn({...e,content:s})}var t3e=ce(()=>{rs();a(e3e,"offloadMessageImages")});function n3e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function r3e(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0&&!Object.is(e,-0)}var jR,bX=ce(()=>{t3e();a(n3e,"isRecord");a(r3e,"isIndex");jR={type:"image/offload",project(e,t){let n=e.data;if(!n3e(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(!n3e(s)||Object.keys(s).length!==2||!r3e(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(!r3e(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,e3e(u,s.imageIndexes))}return r}}});var QR,SAe=ce(()=>{bX();QR=[jR]});async function CAe(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,...h7(o)]}}function nQ(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 e5(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 rQ(e){return{header:e.header,events:e.snapshotEvents()}}function t5(e,t){return e.map(n=>t.get(n))}async function iQ(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: ${aQ(n)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:n})}}async function kAe(e,t,n){try{return await CAe(e,t,n)}catch(r){throw n?.aborted&&n.throwIfAborted(),r instanceof Error&&r.name==="SessionPersistenceCorruptionError"?new Pr(`stored session "${t}" is corrupt: ${aQ(r)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:r}):new Pr(`failed to read stored session "${t}": ${aQ(r)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:r})}}function EAe(e){return{header:structuredClone(e.header),inheritedEventCount:e.inheritedEventCount,events:e.snapshotEvents().map(t=>structuredClone(t))}}function XIt(e,t){return t.header.createdAt-e.header.createdAt||e.header.id.localeCompare(t.header.id)}function n5(e){return new Pr(`session "${e}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND")}function aQ(e){return e instanceof Error?e.message:"unknown error"}function yT(e){if(e?.aborted===!0)throw new Pr("session observation was aborted","SESSION_QUERY_ABORTED",{cause:e.reason})}function _Ae(e,t){return TAe(t,"SessionPersistenceNotFoundError")?cQ(e,t):TAe(t,"SessionPersistenceCorruptionError")?new Pr(`stored session "${e}" is corrupt: ${t.message}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:t}):new Pr(`failed to observe session "${e}": ${r5(t)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:t})}function cQ(e,t){return new Pr(`session "${e}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND",t===void 0?void 0:{cause:t})}function r5(e){return e instanceof Error?e.message:"unknown error"}function TAe(e,t){return e instanceof Error&&e.name===t}function e8t(e){switch(e.type){case"user/message":return sQ(e.data.content);case"assistant/message":return sQ(e.data.message.content);case"tool/call":return vT([e.data.name,e.data.arguments]);case"tool/result":return vT([sQ(e.data.message.content),e.data.error?.name??"",e.data.error?.code??""]);case"todo/write":return vT(e.data.todos.flatMap(t=>[t.status,t.content]));case"turn/end":return t8t(e.data.reason);case"turn/start":case"step/start":case"step/end":case"assistant/attempt":case"request/header":return"";default:return""}}function t8t(e){switch(e.kind){case"error":return vT(["error",e.error.message]);case"aborted":return"aborted";case"max-tokens":case"interrupted":return e.kind;case"completed":return"";default:return""}}function sQ(e){return vT(e.flatMap(n8t))}function n8t(e){switch(e.type){case"text":return[e.text];case"reasoning":return[];case"tool-call":return[e.name,e.arguments];default:return[]}}function vT(e){return e.map(t=>t.trim()).filter(Boolean).join(`
|
|
157
157
|
`)}function uQ(e,t){let n=r8t(t),r=[];for(let i of t){let s=e8t(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 r8t(e){let t;try{t=nj(e,QR)}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 dQ(e,t=[]){let n=t.map(s8t);return e.filter(r=>n.every(i=>i(r)))}function a5(e,t=[]){let n=t.map(o8t);return e.filter(r=>n.every(i=>i(r)))}function pQ(e){return RAe(e),e.map(t=>{switch(t.kind){case"id":return{kind:t.kind,values:s5(t.kind,t.values)};case"cwd":return{kind:t.kind,values:AAe(t.kind,t.values)};case"created-at":return OAe(t.kind,t);case"parent":return{kind:t.kind,values:AAe(t.kind,t.values)};case"availability":{let n=s5(t.kind,t.values);return u5(t.kind,n,["live","persisted"]),{kind:t.kind,values:n}}default:return l5(t)}})}function c5(e){return RAe(e),e.map(t=>{switch(t.kind){case"seq":case"time":return OAe(t.kind,t);case"type":return{kind:t.kind,values:s5(t.kind,t.values)};case"surface":{let n=s5(t.kind,t.values);return u5(t.kind,n,["current","shadowed","log-only"]),{kind:t.kind,values:n}}case"text":if(typeof t.text!="string")throw Fx("text filter text must be a string");return{kind:t.kind,text:t.text};default:return l5(t)}})}function i8t(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 s8t(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=o5(e.kind,e);return n=>lQ(n.header.createdAt,t)}case"parent":return t=>e.values.includes(t.header.parentSession??null);case"availability":return u5(e.kind,e.values,["live","persisted"]),t=>e.values.some(n=>n==="live"?t.live:t.persisted);default:return l5(e)}}function o8t(e){switch(e.kind){case"seq":{let t=o5(e.kind,e);return n=>lQ(n.seq,t)}case"time":{let t=o5(e.kind,e);return n=>lQ(n.time,t)}case"type":return t=>e.values.includes(t.type);case"surface":return u5(e.kind,e.values,["current","shadowed","log-only"]),t=>e.values.includes(t.surface);case"text":{let t=i8t(e.text);return n=>t.test(n.text)}default:return l5(e)}}function s5(e,t){if(!$Ae(t)||t.some(n=>typeof n!="string"))throw Fx(`${e} filter values must be an array of strings`);return[...t]}function RAe(e){if(!Array.isArray(e))throw Fx("filters must be an array")}function AAe(e,t){if(!$Ae(t)||t.some(n=>n!==null&&typeof n!="string"))throw Fx(`${e} filter values must be an array of strings or null`);return[...t]}function OAe(e,t){let n={kind:e,...t.from===void 0?{}:{from:t.from},...t.to===void 0?{}:{to:t.to}};return o5(e,n),n}function l5(e){let t=e.kind;throw Fx(`unknown filter kind ${typeof t=="string"?`"${t}"`:"(missing)"}`)}function u5(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 o5(e,t){if(t.from!==void 0&&!Number.isFinite(t.from))throw oQ(e,"from must be finite");if(t.to!==void 0&&!Number.isFinite(t.to))throw oQ(e,"to must be finite");if(t.from!==void 0&&t.to!==void 0&&t.from>t.to)throw oQ(e,"from must be less than or equal to to");return t}function lQ(e,t){return(t.from===void 0||e>=t.from)&&(t.to===void 0||e<=t.to)}function oQ(e,t){return Fx(`${e} filter ${t}`)}function Fx(e){return new Pr(`session ${e}`,"SESSION_QUERY_INVALID_FILTER")}function $Ae(e){return Array.isArray(e)}function a8t(e,t){return fQ(e,t).records}function c8t(e,t){return fQ(e,t).currentSeqs.map(n=>{let r=t[n];if(r===void 0||r.seq!==n||!bg(r))throw new Pr(`invalid session surface: current node ${n} is not a surface event`,"SESSION_QUERY_INVALID_SURFACE");return Yk(r)})}function l8t(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=fQ(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||IAe(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:[...IAe(r)],derivedEventSeqs:c}}function u8t(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=d8t(l,t),d={target:i5(r),ancestors:i.map(i5),descendants:u};return o!==void 0?{...d,complete:!1,unresolvedParentId:o}:{...d,complete:!0,root:i5(i.at(-1)??r)}}function fQ(e,t){let n;try{n=nj(t,QR)}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 IAe(e){return e.sourceEventSeqs??[]}function d8t(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:i5(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 i5(e){return{...e,header:structuredClone(e.header)}}var Pr,JIt,QIt,NAe,hQ=ce(()=>{SAe();Yn();Hs();qg();gr();Pr=class extends zr{static{a(this,"SessionQueryError")}constructor(e,t,n){super(e,t,n)}};a(CAe,"readColdSessionLog");a(nQ,"assertSessionHeadersCompatible");JIt=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 iQ(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&&nQ(i.header,s.header),r.set(i.id,{header:structuredClone(i.header),live:!0,persisted:s!==void 0})}return[...r.values()].sort(XIt)}async load(e,t){t?.throwIfAborted();let n=this._ctx.sessions.get(e);if(n!==void 0){let l=EAe(n);return t?.throwIfAborted(),l}let r=this._persistence;if(r===void 0)throw n5(e);let i=(await iQ(r,t)).find(l=>l.id===e);if(t?.throwIfAborted(),i===void 0)throw n5(e);let s=await kAe(r,e,t);t?.throwIfAborted();let o=this._ctx.sessions.get(e);if(o!==void 0){let l=EAe(o);return t?.throwIfAborted(),l}nQ(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,e5(g,rQ(y),t,n))}if(s.length===0)return t5(r,i);let o=this._persistence;if(o===void 0){for(let g of s)i.set(g,{sessionId:g,status:"rejected",reason:n5(g)});return t5(r,i)}let c;try{c=await iQ(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 t5(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:n5(g)}:e5(g,rQ(v),t,n));return}try{n?.throwIfAborted();let v=await kAe(o,g,n);n?.throwIfAborted();let w=this._ctx.sessions.get(g);if(w!==void 0){i.set(g,e5(g,rQ(w),t,n));return}nQ(v.header,y),i.set(g,e5(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(),t5(r,i)}};a(e5,"projectSource");a(rQ,"sourceLive");a(t5,"orderedResults");a(iQ,"listPersisted");a(kAe,"inspectPersisted");a(EAe,"snapshotLive");a(XIt,"compareSessions");a(n5,"notFound$1");a(aQ,"errorMessage$1");QIt=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(;;){yT(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 cQ(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);yT(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: ${r5(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}": ${r5(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 yT(n),_Ae(t,i)}if(yT(n),r===void 0)throw cQ(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 CAe(e,t,n)}catch(r){throw yT(n),_Ae(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}": ${r5(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(yT,"throwIfObservationAborted");a(_Ae,"mapPersistenceFailure");a(cQ,"notFound");a(r5,"errorMessage");a(TAe,"hasErrorName");a(e8t,"extractSessionEventText");a(t8t,"turnEndText");a(sQ,"contentText");a(n8t,"blockText");a(vT,"joinText");a(uQ,"buildSessionEventSearchDocuments");a(r8t,"classifySurface");a(dQ,"filterSessionResults");a(a5,"filterSessionEventDocuments");a(pQ,"materializeSessionResultFilters");a(c5,"materializeSessionEventResultFilters");a(i8t,"compileSessionTextFilter");a(s8t,"sessionPredicate");a(o8t,"eventPredicate");a(s5,"copyStrings");a(RAe,"assertArray");a(AAe,"copyNullableStrings");a(OAe,"copyRange");a(l5,"unknownFilter");a(u5,"assertAllowedValues");a(o5,"validateRange");a(lQ,"matchesRange");a(oQ,"invalidRange");a(Fx,"invalidFilter");a($Ae,"isRuntimeArray");a(a8t,"eventRecords");a(c8t,"currentSurfaceEvents");a(l8t,"traceEvent");a(u8t,"traceSession");a(fQ,"analyzeEventLog");a(IAe,"eventSources");a(d8t,"buildDescendants");a(i5,"cloneRecord");NAe=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 JIt(e,n),this._observations=new QIt(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,QR),{session:structuredClone(t.header),inheritedEventCount:t.inheritedEventCount,events:t.events.map(Yk)}}async filterSessions(e,t){let n=pQ(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=Fg(n.events);return{session:structuredClone(n.header),...r===void 0?{}:{title:r}}},t)}async listEvents(e){return a8t(e,(await this._corpus.load(e)).events)}async filterEvents(e,t){let n=c5(t);return this._filterEvents(e,n)}async _filterSessions(e,t){return dQ(await this._corpus.listSessions(t),e)}async _filterEvents(e,t){return a5(uQ(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:c8t(e,t.events)}}async traceSession(e,t){let n=await this._corpus.listSessions(t);return t?.throwIfAborted(),u8t(n,e)}async traceEvent(e,t){let n=await this._corpus.load(e.sessionId,t);return t?.throwIfAborted(),{session:n.header,...l8t(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=Yk(o),d=s.events.slice(c,l+1).map(p=>p===o?u:Yk(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 qx=be((qWn,WAe)=>{"use strict";WAe.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 xQ=be((BWn,GAe)=>{"use strict";var VAe=qx();GAe.exports=bQ;function bQ(){VAe.call(this),this.view=null,this.detail=0}a(bQ,"UIEvent");bQ.prototype=Object.create(VAe.prototype,{constructor:{value:bQ},initUIEvent:{value:a(function(e,t,n,r,i){this.initEvent(e,t,n),this.view=r,this.detail=i},"value")}})});var kQ=be((HWn,ZAe)=>{"use strict";var KAe=xQ();ZAe.exports=SQ;function SQ(){KAe.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(SQ,"MouseEvent");SQ.prototype=Object.create(KAe.prototype,{constructor:{value:SQ},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 g5=be((VWn,JAe)=>{"use strict";JAe.exports=m5;var I8t=1,C8t=3,R8t=4,O8t=5,$8t=7,N8t=8,P8t=9,D8t=11,M8t=12,L8t=13,j8t=14,F8t=15,q8t=17,U8t=18,B8t=19,z8t=20,H8t=21,W8t=22,V8t=23,G8t=24,K8t=25,Z8t=[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"],Y8t=[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."],YAe={INDEX_SIZE_ERR:I8t,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:C8t,WRONG_DOCUMENT_ERR:R8t,INVALID_CHARACTER_ERR:O8t,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:$8t,NOT_FOUND_ERR:N8t,NOT_SUPPORTED_ERR:P8t,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:D8t,SYNTAX_ERR:M8t,INVALID_MODIFICATION_ERR:L8t,NAMESPACE_ERR:j8t,INVALID_ACCESS_ERR:F8t,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:q8t,SECURITY_ERR:U8t,NETWORK_ERR:B8t,ABORT_ERR:z8t,URL_MISMATCH_ERR:H8t,QUOTA_EXCEEDED_ERR:W8t,TIMEOUT_ERR:V8t,INVALID_NODE_TYPE_ERR:G8t,DATA_CLONE_ERR:K8t};function m5(e){Error.call(this),Error.captureStackTrace(this,this.constructor),this.code=e,this.message=Y8t[e],this.name=Z8t[e]}a(m5,"DOMException");m5.prototype.__proto__=Error.prototype;for(h5 in YAe)EQ={value:YAe[h5]},Object.defineProperty(m5,h5,EQ),Object.defineProperty(m5.prototype,h5,EQ);var EQ,h5});var y5=be(XAe=>{XAe.isApiWritable=!globalThis.__domino_frozen__});var bo=be(ji=>{"use strict";var wo=g5(),Mo=wo,J8t=y5().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 wo(Mo.INDEX_SIZE_ERR)};ji.HierarchyRequestError=function(){throw new wo(Mo.HIERARCHY_REQUEST_ERR)};ji.WrongDocumentError=function(){throw new wo(Mo.WRONG_DOCUMENT_ERR)};ji.InvalidCharacterError=function(){throw new wo(Mo.INVALID_CHARACTER_ERR)};ji.NoModificationAllowedError=function(){throw new wo(Mo.NO_MODIFICATION_ALLOWED_ERR)};ji.NotFoundError=function(){throw new wo(Mo.NOT_FOUND_ERR)};ji.NotSupportedError=function(){throw new wo(Mo.NOT_SUPPORTED_ERR)};ji.InvalidStateError=function(){throw new wo(Mo.INVALID_STATE_ERR)};ji.SyntaxError=function(){throw new wo(Mo.SYNTAX_ERR)};ji.InvalidModificationError=function(){throw new wo(Mo.INVALID_MODIFICATION_ERR)};ji.NamespaceError=function(){throw new wo(Mo.NAMESPACE_ERR)};ji.InvalidAccessError=function(){throw new wo(Mo.INVALID_ACCESS_ERR)};ji.TypeMismatchError=function(){throw new wo(Mo.TYPE_MISMATCH_ERR)};ji.SecurityError=function(){throw new wo(Mo.SECURITY_ERR)};ji.NetworkError=function(){throw new wo(Mo.NETWORK_ERR)};ji.AbortError=function(){throw new wo(Mo.ABORT_ERR)};ji.UrlMismatchError=function(){throw new wo(Mo.URL_MISMATCH_ERR)};ji.QuotaExceededError=function(){throw new wo(Mo.QUOTA_EXCEEDED_ERR)};ji.TimeoutError=function(){throw new wo(Mo.TIMEOUT_ERR)};ji.InvalidNodeTypeError=function(){throw new wo(Mo.INVALID_NODE_TYPE_ERR)};ji.DataCloneError=function(){throw new wo(Mo.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:J8t})};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 _Q=be((YWn,e7e)=>{"use strict";var Gy=qx(),X8t=kQ(),Q8t=bo();e7e.exports=QAe;function QAe(){}a(QAe,"EventTarget");QAe.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)&&Q8t.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 X8t)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 TQ=be((XWn,t7e)=>{"use strict";var mm=bo(),gd=t7e.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(gd.valid(e)&&gd.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(gd.valid(e)&&gd.valid(t))},"insertBefore"),replace:a(function(e,t){mm.assert(gd.valid(e)&&(t===null||gd.valid(t))),t!==null&&gd.insertBefore(t,e),gd.remove(e),mm.assert(gd.valid(e)&&(t===null||gd.valid(t)))},"replace"),remove:a(function(e){mm.assert(gd.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(gd.valid(e))}},"remove")}});var AQ=be((eVn,l7e)=>{"use strict";l7e.exports={serializeOne:oCt,\u0275escapeMatchingClosingTag:o7e,\u0275escapeClosingCommentTag:a7e,\u0275escapeProcessingInstructionContent:c7e};var s7e=bo(),Ky=s7e.NAMESPACE,n7e={STYLE:!0,SCRIPT:!0,XMP:!0,IFRAME:!0,NOEMBED:!0,NOFRAMES:!0,PLAINTEXT:!0},eCt={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},tCt={},r7e=/[&<>\u00A0]/g,i7e=/[&"<>\u00A0]/g;function nCt(e){return r7e.test(e)?e.replace(r7e,t=>{switch(t){case"&":return"&";case"<":return"<";case">":return">";case"\xA0":return" "}}):e}a(nCt,"escape");function rCt(e){return i7e.test(e)?e.replace(i7e,t=>{switch(t){case"<":return"<";case">":return">";case"&":return"&";case'"':return""";case"\xA0":return" "}}):e}a(rCt,"escapeAttr");function iCt(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(iCt,"attrname");function o7e(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]="<";return r.join("")}a(o7e,"escapeMatchingClosingTag");var sCt=/--!?>/;function a7e(e){return sCt.test(e)?e.replace(/(--\!?)>/g,"$1>"):e}a(a7e,"escapeClosingCommentTag");function c7e(e){return e.includes(">")?e.replaceAll(">",">"):e}a(c7e,"escapeProcessingInstructionContent");function oCt(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+=" "+iCt(l),l.value!==void 0&&(n+='="'+rCt(l.value)+'"')}if(n+=">",!(i&&eCt[s])){var u=e.serialize();n7e[s.toUpperCase()]&&(u=o7e(u,s)),i&&tCt[s]&&u.charAt(0)===`
|
|
@@ -5844,7 +5844,7 @@ The web search request used endpoint ${JSON.stringify(e)}. Search endpoint confi
|
|
|
5844
5844
|
.error { padding: .75rem; border-radius: .5rem; background: #461d2b; color: #ffd6df; }
|
|
5845
5845
|
.hint { margin: 1.5rem 0 0; font-size: .875rem; }
|
|
5846
5846
|
code { padding: .1rem .3rem; border-radius: .3rem; background: #0c1222; color: #edf2ff; }
|
|
5847
|
-
`}a(ZDe,"pageStyles");y6();var Hie="enabled",Wie=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")}),O4=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")}),Vie=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===Hie?"available":"needs-binding","probe")}),NXt=Object.freeze([Vie,O4,Wie]);function Gie(e,t=NXt){return t.filter(n=>n.probe(e)==="available")}a(Gie,"availableEdgeRuntimeProviders");function Kie(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(Kie,"resolveEdgeRuntimeSelection");function G$(e){let t=Gie(e),{bash:n,container:r}=Kie(t);return t.find(i=>i.id===(r??n)).shell}a(G$,"resolveEdgeRuntimeShell");function PXt(){return"dsh-edge@0.22.0-alpha.1/direct"}a(PXt,"resolveEdgeDeploymentId");function E2(e){return{baseURL:PY(e.DEEPSEEK_BASE_URL),maxTokens:LY(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Oy(e.DEEPSEEK_MODEL),reasoningEffort:DY(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:UT(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:MY(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:B1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(E2,"resolveEdgeDeploymentConfig");function DXt(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(DXt,"edgeDeploymentApiKeyConfigured");function MXt(e){let t=PY(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(MXt,"projectedEdgeBaseURL");function Zie(e,t){return{shell:G$(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:PXt(),apiKeyConfigured:DXt(e),baseURL:MXt(e.DEEPSEEK_BASE_URL),maxTokens:LY(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Oy(e.DEEPSEEK_MODEL),reasoningEffort:DY(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:UT(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:MY(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:B1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(Zie,"resolveEdgeDeploymentProfile");function K$(e){E2(e);let t=Zie(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:dke,status:"ready"}}a(K$,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as Vmn}from"node:async_hooks";import{RpcTarget as LXt}from"cloudflare:workers";function jXt(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(jXt,"startHeartbeat");async function FXt(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(FXt,"probeComputerdHealth");var qXt="computer.internal",UXt="/health",Yie="/api",BXt=8080,zXt=3e4,HXt=2e4,WXt=1,VXt=2e3,GXt=250,KXt=2e3;function ZXt(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(ZXt,"bearerMatches");var Y$=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??qXt,containerPort:e.containerPort??BXt,connectTimeoutMs:e.connectTimeoutMs??zXt,heartbeatIntervalMs:e.heartbeatIntervalMs??HXt,restartAttempts:e.restartAttempts??WXt,healthProbeTimeoutMs:e.healthProbeTimeoutMs??VXt,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??GXt,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??KXt}}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=kD(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=jXt({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(SS),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(z3),i.delete(SS);let c=new Request(e,{headers:i});return this.#t.gateway.fetch(new Request(o,c))}if(new URL(e.url).pathname!==Yie)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${Yie} requires a websocket upgrade`,{status:400});if(!ZXt(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 FXt(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 YXt(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=${YDe(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:UXt,api:Yie,healthTimeoutMs:r})})}catch(s){throw this.#a?.(s),this.#o(),new Cc(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${YDe(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 YXt(e){return new Promise(t=>setTimeout(t,e))}a(YXt,"sleep");function YDe(e){return e instanceof Error?e.message:String(e)}a(YDe,"describeError");var JDe="computer:container-client-secret",JXt=16;function XXt(){let e=crypto.getRandomValues(new Uint8Array(JXt));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(XXt,"generate");var QXt=class{static{a(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(JDe);if(typeof e=="string"&&e.length>0)return e;let t=XXt();return await this.storage.put(JDe,t),t}},XDe="computer:container-launch-record";async function QDe(e){return{enableInternet:e.enableInternet,envDigest:await tQt(e.env)}}a(QDe,"launchRecordFor");function eQt(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}a(eQt,"sameLaunch");async function tQt(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(tQt,"digestEnv");var nQt=class{static{a(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(XDe)??null}async set(e){await this.storage.put(XDe,e)}},eMe=new WeakMap;function Qie(e){let t=eMe.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},eMe.set(e,t)),t}a(Qie,"getContainerLifecycle");function Z$(e){return Qie(e).exit}a(Z$,"containerExitInfo");function tMe(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}a(tMe,"formatExitReason");function nMe(e,t,n){let r=Qie(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>rMe(r,i,void 0,n),s=>rMe(r,i,s,n))}a(nMe,"installContainerMonitor");async function Jie(e,t){let n=Qie(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}a(Jie,"destroyContainerExpectingExit");async function rMe(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=tMe(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:tMe(c),exitedAt:Date.now()})}}a(rMe,"recordExit");var Xie="computer:container-runtime-identity",rQt=class{static{a(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(Xie)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(Xie,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(Xie)}},iQt=class extends LXt{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 rQt(e.storage),this.#n=new QXt(e.storage),this.#i=new nQt(e.storage)}async start(e){let t=Z$(this.#t),n=await this.#n.ensure(),r=await QDe(e);if(t!==null){try{await Jie(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||!eQt(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 Jie(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return nMe(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await Jie(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await QDe(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),nMe(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 iMe(e){class t extends e{static{a(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new iQt(this.ctx)}}return t}a(iMe,"withWorkspaceContainer");var sQt={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function oMe(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=sQt[s]??s,l=e[c];if(l===void 0)return;let u=l[o];return typeof u=="function"?u:void 0}a(oMe,"resolve");function oQt(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}a(oQt,"errorResponse");async function ese(e,t,n,r,i){let s=oMe(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}a(ese,"callEdgeApi");async function aMe(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(oMe(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 ese(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 oQt(o,{code:"internal",message:String(l),details:{}})}}a(aMe,"dispatchEdgeApi");gr();Hs();qg();import{DurableObject as Gmn}from"cloudflare:workers";var J$=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 aQt(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 aQt(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(aQt,"untilAborted");import{WorkerEntrypoint as Zsr}from"cloudflare:workers";var Gv=dl(cMe());import{gunzipSync as ptn}from"node:zlib";var $4=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 tse=class extends $4{static{a(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=lQt}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
|
|
5847
|
+
`}a(ZDe,"pageStyles");y6();var Hie="enabled",Wie=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")}),O4=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")}),Vie=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===Hie?"available":"needs-binding","probe")}),NXt=Object.freeze([Vie,O4,Wie]);function Gie(e,t=NXt){return t.filter(n=>n.probe(e)==="available")}a(Gie,"availableEdgeRuntimeProviders");function Kie(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(Kie,"resolveEdgeRuntimeSelection");function G$(e){let t=Gie(e),{bash:n,container:r}=Kie(t);return t.find(i=>i.id===(r??n)).shell}a(G$,"resolveEdgeRuntimeShell");function PXt(){return"dsh-edge@0.22.0/direct"}a(PXt,"resolveEdgeDeploymentId");function E2(e){return{baseURL:PY(e.DEEPSEEK_BASE_URL),maxTokens:LY(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Oy(e.DEEPSEEK_MODEL),reasoningEffort:DY(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:UT(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:MY(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:B1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(E2,"resolveEdgeDeploymentConfig");function DXt(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(DXt,"edgeDeploymentApiKeyConfigured");function MXt(e){let t=PY(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(MXt,"projectedEdgeBaseURL");function Zie(e,t){return{shell:G$(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:PXt(),apiKeyConfigured:DXt(e),baseURL:MXt(e.DEEPSEEK_BASE_URL),maxTokens:LY(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Oy(e.DEEPSEEK_MODEL),reasoningEffort:DY(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:UT(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:MY(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:B1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(Zie,"resolveEdgeDeploymentProfile");function K$(e){E2(e);let t=Zie(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:dke,status:"ready"}}a(K$,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as Vmn}from"node:async_hooks";import{RpcTarget as LXt}from"cloudflare:workers";function jXt(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(jXt,"startHeartbeat");async function FXt(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(FXt,"probeComputerdHealth");var qXt="computer.internal",UXt="/health",Yie="/api",BXt=8080,zXt=3e4,HXt=2e4,WXt=1,VXt=2e3,GXt=250,KXt=2e3;function ZXt(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(ZXt,"bearerMatches");var Y$=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??qXt,containerPort:e.containerPort??BXt,connectTimeoutMs:e.connectTimeoutMs??zXt,heartbeatIntervalMs:e.heartbeatIntervalMs??HXt,restartAttempts:e.restartAttempts??WXt,healthProbeTimeoutMs:e.healthProbeTimeoutMs??VXt,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??GXt,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??KXt}}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=kD(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=jXt({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(SS),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(z3),i.delete(SS);let c=new Request(e,{headers:i});return this.#t.gateway.fetch(new Request(o,c))}if(new URL(e.url).pathname!==Yie)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${Yie} requires a websocket upgrade`,{status:400});if(!ZXt(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 FXt(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 YXt(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=${YDe(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:UXt,api:Yie,healthTimeoutMs:r})})}catch(s){throw this.#a?.(s),this.#o(),new Cc(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${YDe(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 YXt(e){return new Promise(t=>setTimeout(t,e))}a(YXt,"sleep");function YDe(e){return e instanceof Error?e.message:String(e)}a(YDe,"describeError");var JDe="computer:container-client-secret",JXt=16;function XXt(){let e=crypto.getRandomValues(new Uint8Array(JXt));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(XXt,"generate");var QXt=class{static{a(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(JDe);if(typeof e=="string"&&e.length>0)return e;let t=XXt();return await this.storage.put(JDe,t),t}},XDe="computer:container-launch-record";async function QDe(e){return{enableInternet:e.enableInternet,envDigest:await tQt(e.env)}}a(QDe,"launchRecordFor");function eQt(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}a(eQt,"sameLaunch");async function tQt(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(tQt,"digestEnv");var nQt=class{static{a(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(XDe)??null}async set(e){await this.storage.put(XDe,e)}},eMe=new WeakMap;function Qie(e){let t=eMe.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},eMe.set(e,t)),t}a(Qie,"getContainerLifecycle");function Z$(e){return Qie(e).exit}a(Z$,"containerExitInfo");function tMe(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}a(tMe,"formatExitReason");function nMe(e,t,n){let r=Qie(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>rMe(r,i,void 0,n),s=>rMe(r,i,s,n))}a(nMe,"installContainerMonitor");async function Jie(e,t){let n=Qie(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}a(Jie,"destroyContainerExpectingExit");async function rMe(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=tMe(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:tMe(c),exitedAt:Date.now()})}}a(rMe,"recordExit");var Xie="computer:container-runtime-identity",rQt=class{static{a(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(Xie)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(Xie,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(Xie)}},iQt=class extends LXt{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 rQt(e.storage),this.#n=new QXt(e.storage),this.#i=new nQt(e.storage)}async start(e){let t=Z$(this.#t),n=await this.#n.ensure(),r=await QDe(e);if(t!==null){try{await Jie(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||!eQt(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 Jie(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return nMe(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await Jie(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await QDe(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),nMe(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 iMe(e){class t extends e{static{a(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new iQt(this.ctx)}}return t}a(iMe,"withWorkspaceContainer");var sQt={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function oMe(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=sQt[s]??s,l=e[c];if(l===void 0)return;let u=l[o];return typeof u=="function"?u:void 0}a(oMe,"resolve");function oQt(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}a(oQt,"errorResponse");async function ese(e,t,n,r,i){let s=oMe(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}a(ese,"callEdgeApi");async function aMe(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(oMe(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 ese(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 oQt(o,{code:"internal",message:String(l),details:{}})}}a(aMe,"dispatchEdgeApi");gr();Hs();qg();import{DurableObject as Gmn}from"cloudflare:workers";var J$=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 aQt(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 aQt(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(aQt,"untilAborted");import{WorkerEntrypoint as Zsr}from"cloudflare:workers";var Gv=dl(cMe(),1);import{gunzipSync as ptn}from"node:zlib";var $4=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 tse=class extends $4{static{a(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=lQt}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
|
|
5848
5848
|
`))&&(t=t.trim()),(!r.newlineIsToken||!n.includes(`
|
|
5849
5849
|
`))&&(n=n.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
|
|
5850
5850
|
`)&&(t=t.slice(0,-1)),n.endsWith(`
|
package/worker/isolated/index.js
CHANGED
|
@@ -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"?g3(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=>g3(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&<.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&<.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&<.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)&&g3(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:X2e(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();y8();$H();g8();PH();o(Es,"validate")});var v8,Q2e=oe(()=>{y8();DH();v8=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 e3e=oe(()=>{OH();y8();$H();g8();Y2e();PH();DH();Q2e()});var w8,t3e=oe(()=>{e3e();w8=class{static{o(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let n=new v8(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 ca,b8=oe(()=>{"use strict";ca={probeTimeoutMs:3e4,callTimeoutMs:6e4,maxToolsPerServer:128,maxCatalogPages:10,maxCatalogBytes:131072,maxDescriptionLength:512,maxErrorMessageChars:300,maxPublicNameLength:64,maxInstructionsLength:1024,metaToolThreshold:20}});import{createHash as Hdt}from"node:crypto";function Gdt(e){let t=e.replace(/[.*+?^${}()|[\]\\]/gu,n=>n==="*"?"\0":`\\${n}`);return new RegExp(`^${t.replaceAll("\0",".*")}$`)}function n3e(e,t,n){let r=t??"read_only";return r==="allow_all"?"allow":r==="approve_all"?"ask":n===!0?"allow":n===!1?"ask":Vdt.some(i=>Gdt(i).test(e))?"allow":"ask"}function Ap(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,ca.maxErrorMessageChars)}function r3e(e,t){let n=`mcp__${e}__${t}`,r=n.replace(/[^A-Za-z0-9_-]/gu,"_");if(r===n&&r.length<=ca.maxPublicNameLength)return r;let i=Zdt(e,t),s=ca.maxPublicNameLength-i.length-1;return`${r.slice(0,s)}_${i}`}function Zdt(e,t){return Hdt("sha256").update(`${e}\0${t}`).digest("hex").slice(0,12)}function i3e(e){if(!(e==null||typeof e!="object"))try{let t=JSON.parse(JSON.stringify(e));return mg(t),t}catch{return}}function Ydt(e){return Kdt.has(e)}function s3e(e){return e.type!=="image"||e.data===void 0||e.mimeType===void 0||!Ydt(e.mimeType)||!Jdt.test(e.data)?void 0:{data:Uint8Array.from(atob(e.data),n=>n.charCodeAt(0)),mediaType:e.mimeType}}function a3e(e){return e.some(t=>t.type==="image"&&t.data!==void 0)}function oS(e){if(e.isError)return[{type:"text",text:e.content.filter(i=>i.type==="text"&&typeof i.text=="string").map(i=>i.text).join(`
|
|
153
153
|
`)||"MCP tool returned an error."}];let t=[],n=[];for(let r of e.content)if(r.type==="text"&&typeof r.text=="string")n.push(r.text);else if(r.type==="resource_link"&&r.uri!==void 0)n.push(`Resource: ${r.name??"unnamed"} (${r.uri})`);else if(r.type==="image"&&r.data!==void 0)n.push(``);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 Vdt,Kdt,Jdt,x8=oe(()=>{"use strict";js();b8();Vdt=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];o(Gdt,"globToRegExp");o(n3e,"evaluateMcpToolPolicy");o(Ap,"scrubMcpErrorMessage");o(r3e,"publicToolName");o(Zdt,"hashSuffix");o(i3e,"supportedOutputSchema");Kdt=new Set(["image/png","image/jpeg"]),Jdt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;o(Ydt,"isImageMediaType");o(s3e,"decodeImageBlock");o(a3e,"containsImage");o(oS,"mapMcpResultToContentBlocks")});var MH,o3e=oe(()=>{MH={name:"dsh-edge",version:"0.22.0-alpha.1",description:"Your DeepSeek Harness, anywhere \u2014 deploy a persistent personal coding agent to Cloudflare Workers in one command",author:"pawaca",license:"MIT",type:"module",bin:{"dsh-edge":"scripts/cli.mjs"},files:["dist","worker","scripts/*.d.mts","scripts/*.mjs","wrangler.jsonc","README.md","README.zh.md","LICENSE","THIRD_PARTY_NOTICES.md"],repository:{type:"git",url:"git+https://github.com/pawaca/dsh-edge.git",directory:"apps/dsh-edge"},homepage:"https://github.com/pawaca/dsh-edge#readme",bugs:{url:"https://github.com/pawaca/dsh-edge/issues"},keywords:["deepseek","deepseek-harness","ai-agents","byok","cloudflare-workers","durable-objects","self-hosted"],engines:{node:">=22.14.0"},publishConfig:{access:"public"},dshEdge:{upstreamVersion:"0.2.0-rc.2"},scripts:{"bundle:direct":"pnpm run web:build && pnpm --dir standalone run build:worker:direct && node standalone/scripts/promote.mjs direct","bundle:isolated":"pnpm run web:build && pnpm --dir standalone run build:worker:isolated && node standalone/scripts/promote.mjs isolated","bundle:workers":"pnpm --dir standalone run build && pnpm --dir standalone run verify && node standalone/scripts/promote.mjs all",dev:"pnpm run bundle:direct && node scripts/dev.mjs direct","dev:isolated":"pnpm run bundle:isolated && node scripts/dev.mjs isolated","dev:container":"pnpm run bundle:isolated && node scripts/dev.mjs container","dsh-edge":"node scripts/cli.mjs","example:install":"node examples/install-keyless.mjs","install:cloudflare":"pnpm run bundle:workers && node scripts/cli.mjs install","legal:write":"node scripts/legal-files.mjs write","pack:verify":"node scripts/verify-packed.mjs",prepack:"node scripts/legal-files.mjs verify && pnpm run bundle:workers","web:build":"pnpm --dir standalone run build:web && node standalone/scripts/promote.mjs web",test:"vitest run --root ../.. --project edge-runtime","test:integration":"pnpm run bundle:workers && node tests/run-session-integration.mjs","test:container":"pnpm run bundle:isolated && node tests/container.integration.mjs","test:snapshot":"vitest run --root ../.. --config apps/dsh-edge/vitest.snapshot.config.ts",typecheck:"tsc --noEmit"},dependencies:{"@clack/prompts":"1.7.0","compare-versions":"6.1.1",execa:"^10.0.1","jsonc-parser":"^3.3.1",wrangler:"4.129.0"},devDependencies:{"@cfworker/json-schema":"^4.1.1","@cloudflare/computer":"0.3.1","@cloudflare/workers-types":"5.20260904.1","@deepseek-ai/cordis":"4.0.4","@deepseek-ai/cosmokit":"1.8.5","@deepseek-ai/dsh-agent":"0.2.0-rc.2","@deepseek-ai/dsh-agent-instructions":"0.2.0-rc.2","@deepseek-ai/dsh-agent-loop":"0.2.0-rc.2","@deepseek-ai/dsh-anonymous-user-id":"0.2.0-rc.2","@deepseek-ai/dsh-api-gateway":"0.2.0-rc.2","@deepseek-ai/dsh-api-job-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-remotes":"0.2.0-rc.2","@deepseek-ai/dsh-api-session-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-settings-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-workspace-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-workspace-files":"0.2.0-rc.2","@deepseek-ai/dsh-attachment":"0.2.0-rc.2","@deepseek-ai/dsh-brand":"0.2.0-rc.2","@deepseek-ai/dsh-client-locale":"0.2.0-rc.2","@deepseek-ai/dsh-client-store":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-chat":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-conversation":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-settings":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-settings-general":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-theme":"0.2.0-rc.2","@deepseek-ai/dsh-command-compact":"0.2.0-rc.2","@deepseek-ai/dsh-command-goal":"0.2.0-rc.2","@deepseek-ai/dsh-commands":"0.2.0-rc.2","@deepseek-ai/dsh-compaction":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-basic":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-tool-result-pruner":"0.2.0-rc.2","@deepseek-ai/dsh-credentials":"0.2.0-rc.2","@deepseek-ai/dsh-file-reference":"0.2.0-rc.2","@deepseek-ai/dsh-fs":"0.2.0-rc.2","@deepseek-ai/dsh-fs-observation-policy":"0.2.0-rc.2","@deepseek-ai/dsh-goal":"0.2.0-rc.2","@deepseek-ai/dsh-goal-round-driver":"0.2.0-rc.2","@deepseek-ai/dsh-home-paths":"0.2.0-rc.2","@deepseek-ai/dsh-host-directory-picker":"0.2.0-rc.2","@deepseek-ai/dsh-host-plugin-inventory":"0.2.0-rc.2","@deepseek-ai/dsh-invariants":"0.2.0-rc.2","@deepseek-ai/dsh-jobs":"0.2.0-rc.2","@deepseek-ai/dsh-jobs-local":"0.2.0-rc.2","@deepseek-ai/dsh-launch-environment":"0.2.0-rc.2","@deepseek-ai/dsh-llm":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek-api-key":"0.2.0-rc.2","@deepseek-ai/dsh-llm-retry":"0.2.0-rc.2","@deepseek-ai/dsh-message-feedback":"0.2.0-rc.2","@deepseek-ai/dsh-output-retention":"0.2.0-rc.2","@deepseek-ai/dsh-plan-mode":"0.2.0-rc.2","@deepseek-ai/dsh-ptc-runtime":"0.2.0-rc.2","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.0-rc.2","@deepseek-ai/dsh-sandbox":"0.2.0-rc.2","@deepseek-ai/dsh-schedule":"0.2.0-rc.2","@deepseek-ai/dsh-scope":"0.2.0-rc.2","@deepseek-ai/dsh-session":"0.2.0-rc.2","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.0-rc.2","@deepseek-ai/dsh-session-format":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-catalog":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.0-rc.2","@deepseek-ai/dsh-session-persistence":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection-cache":"0.2.0-rc.2","@deepseek-ai/dsh-session-stats":"0.2.0-rc.2","@deepseek-ai/dsh-session-query":"0.2.0-rc.2","@deepseek-ai/dsh-session-reference":"0.2.0-rc.2","@deepseek-ai/dsh-session-title":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-llm":"0.2.0-rc.2","@deepseek-ai/dsh-settings":"0.2.0-rc.2","@deepseek-ai/dsh-skill":"0.2.0-rc.2","@deepseek-ai/dsh-spill":"0.2.0-rc.2","@deepseek-ai/dsh-spill-policy":"0.2.0-rc.2","@deepseek-ai/dsh-storage":"0.2.0-rc.2","@deepseek-ai/dsh-storage-domain":"0.2.0-rc.2","@deepseek-ai/dsh-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-in-process-driver":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-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-present":"0.2.0-rc.2","@deepseek-ai/dsh-tool-todo":"0.2.0-rc.2","@deepseek-ai/dsh-tool-web":"0.2.0-rc.2","@deepseek-ai/dsh-tool-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-tools":"0.2.0-rc.2","@deepseek-ai/dsh-typert-protocol":"0.2.0-rc.2","@deepseek-ai/dsh-typert-registry":"0.2.0-rc.2","@deepseek-ai/dsh-user-approval":"0.2.0-rc.2","@deepseek-ai/dsh-user-questions":"0.2.0-rc.2","@deepseek-ai/dsh-util-values":"0.2.0-rc.2","@deepseek-ai/dsh-web":"0.2.0-rc.2","@deepseek-ai/dsh-web-fetch-http":"0.2.0-rc.2","@deepseek-ai/dsh-web-search-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-workspace":"0.2.0-rc.2","@deepseek-ai/schemastery":"3.18.4","@mixmark-io/domino":"2.2.0","@modelcontextprotocol/sdk":"1.30.0",acorn:"8.18.0","fast-png":"8.0.0","jpeg-js":"0.4.4","just-bash":"3.4.2",minimatch:"10.2.6",playwright:"^1.49.0",re2js:"1.3.3",sucrase:"3.35.1",typescript:"^6.0.3",vitest:"^4.1.8",ws:"^8.21.0"}}});var t0,l3e,c3e,lS=oe(()=>{"use strict";o3e();t0=MH.version,l3e=MH.dshEdge.upstreamVersion,c3e=`npx dsh-edge@${t0.includes("-")?"next":"latest"} upgrade`});function npt(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 rpt(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 Qdt)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(rpt(i)){let s=npt(i),a=s??i;for(let l of ept)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 tpt)if(l.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function ipt(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function u3e(e,t,n){Kf(e);let r=new m8(new URL(e),{requestInit:{headers:ipt(t),signal:n},fetch:n0}),i=new f8({name:"dsh-edge",version:t0},{capabilities:{},jsonSchemaValidator:spt});return await i.connect(r),{client:i,close:o(async()=>{await i.close().catch(()=>{})},"close")}}async function d3e(e,t,n){let r=AbortSignal.timeout(ca.probeTimeoutMs),i;try{i=await u3e(t,n,r)}catch(l){throw new Error(Ap(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<ca.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>=ca.maxToolsPerServer)break;let v=r3e(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=i3e(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>=ca.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,ca.maxInstructionsLength):void 0}}finally{await a()}}async function S8(e,t,n,r,i,s){let a=s??ca.callTimeoutMs,l=i?AbortSignal.any([i,AbortSignal.timeout(a)]):AbortSignal.timeout(a),c;try{c=await u3e(e,r,l)}catch(u){throw new Error(Ap(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(Ap(u instanceof Error?u.message:String(u)))}finally{await c.close()}}var Qdt,ept,tpt,spt,n0,cS=oe(()=>{"use strict";h2e();G2e();t3e();x8();b8();lS();Qdt=[".internal",".local",".localhost"],ept=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],tpt=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];o(npt,"extractMappedIPv4");o(rpt,"isIpAddress");o(Kf,"assertSafeUrl");o(ipt,"buildHeaders");spt=new w8,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(u3e,"connectClient");o(d3e,"probe");o(S8,"callTool")});import{Buffer as apt}from"node:buffer";function upt(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&cpt.has(e.code)}function f3e(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&lpt.has(e.code)}function h3e(e,t,n){let r=apt.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 dpt(e){return h3e(e,"reject","INVALID_IMAGE_BASE64")}function ppt(e){return{data:dpt(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function uS(e,t){return e.saveImages(t.map(ppt))}async function fpt(e,t){return e.saveFile({data:h3e(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function m3e(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 p3e,opt,lpt,cpt,ar,jH,Jf=oe(()=>{Vn();p3e=["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"],opt=[...p3e,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],lpt=new Set(p3e),cpt=new Set(opt),ar=class extends Error{static{o(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};o(upt,"isAttachmentError");o(f3e,"isImageAdmissionError");o(h3e,"decodeCanonicalBase64");o(dpt,"decodeBase64");o(ppt,"saveInput");o(uS,"admitEncodedImages");o(fpt,"admitEncodedFile");o(m3e,"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 uS(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 fpt(this,e)}isAttachmentError(e){return upt(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 E8={};dn(E8,{buildAuthorizationUrl:()=>Spt,discoverEndpoints:()=>bpt,exchangeCode:()=>kpt,isTokenExpired:()=>_pt,refreshToken:()=>Ept,registerClient:()=>xpt});function w3e(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 wpt(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 bpt(e){let t=AbortSignal.timeout(k8),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 xpt(e,t,n){let r=AbortSignal.timeout(k8);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 Spt(e,t,n,r,i){let s=w3e(32),a=w3e(64),l=await wpt(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 kpt(e,t,n,r,i,s){let a=AbortSignal.timeout(k8),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 b3e(await c.json())}async function Ept(e,t,n,r){let i=AbortSignal.timeout(k8),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 b3e(await a.json())}function b3e(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 _pt(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var k8,_8=oe(()=>{"use strict";cS();k8=1e4;o(w3e,"randomString");o(wpt,"sha256Base64Url");o(bpt,"discoverEndpoints");o(xpt,"registerClient");o(Spt,"buildAuthorizationUrl");o(kpt,"exchangeCode");o(Ept,"refreshToken");o(b3e,"parseTokenResponse");o(_pt,"isTokenExpired")});var Ln,I3e,y3=oe(()=>{Vn();dr();Ln=class extends Lr{static{o(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},I3e=class extends St{static{o(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new Ln("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function rV(e){return M8.test(e)}function L8(e){return e.invocation.modelInvocable}function w3(e){return e.invocation.userInvocable}function iV(e){let t=cht(e);return[`<skill_content name="${uht(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 Vdt,Kdt,Jdt,x8=oe(()=>{"use strict";js();b8();Vdt=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];o(Gdt,"globToRegExp");o(n3e,"evaluateMcpToolPolicy");o(Ap,"scrubMcpErrorMessage");o(r3e,"publicToolName");o(Zdt,"hashSuffix");o(i3e,"supportedOutputSchema");Kdt=new Set(["image/png","image/jpeg"]),Jdt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;o(Ydt,"isImageMediaType");o(s3e,"decodeImageBlock");o(a3e,"containsImage");o(oS,"mapMcpResultToContentBlocks")});var MH,o3e=oe(()=>{MH={name:"dsh-edge",version:"0.22.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-command-compact":"0.2.0-rc.2","@deepseek-ai/dsh-command-goal":"0.2.0-rc.2","@deepseek-ai/dsh-commands":"0.2.0-rc.2","@deepseek-ai/dsh-compaction":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-basic":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-tool-result-pruner":"0.2.0-rc.2","@deepseek-ai/dsh-credentials":"0.2.0-rc.2","@deepseek-ai/dsh-file-reference":"0.2.0-rc.2","@deepseek-ai/dsh-fs":"0.2.0-rc.2","@deepseek-ai/dsh-fs-observation-policy":"0.2.0-rc.2","@deepseek-ai/dsh-goal":"0.2.0-rc.2","@deepseek-ai/dsh-goal-round-driver":"0.2.0-rc.2","@deepseek-ai/dsh-home-paths":"0.2.0-rc.2","@deepseek-ai/dsh-host-directory-picker":"0.2.0-rc.2","@deepseek-ai/dsh-host-plugin-inventory":"0.2.0-rc.2","@deepseek-ai/dsh-invariants":"0.2.0-rc.2","@deepseek-ai/dsh-jobs":"0.2.0-rc.2","@deepseek-ai/dsh-jobs-local":"0.2.0-rc.2","@deepseek-ai/dsh-launch-environment":"0.2.0-rc.2","@deepseek-ai/dsh-llm":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek-api-key":"0.2.0-rc.2","@deepseek-ai/dsh-llm-retry":"0.2.0-rc.2","@deepseek-ai/dsh-message-feedback":"0.2.0-rc.2","@deepseek-ai/dsh-output-retention":"0.2.0-rc.2","@deepseek-ai/dsh-plan-mode":"0.2.0-rc.2","@deepseek-ai/dsh-ptc-runtime":"0.2.0-rc.2","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.0-rc.2","@deepseek-ai/dsh-sandbox":"0.2.0-rc.2","@deepseek-ai/dsh-schedule":"0.2.0-rc.2","@deepseek-ai/dsh-scope":"0.2.0-rc.2","@deepseek-ai/dsh-session":"0.2.0-rc.2","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.0-rc.2","@deepseek-ai/dsh-session-format":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-catalog":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.0-rc.2","@deepseek-ai/dsh-session-persistence":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection-cache":"0.2.0-rc.2","@deepseek-ai/dsh-session-stats":"0.2.0-rc.2","@deepseek-ai/dsh-session-query":"0.2.0-rc.2","@deepseek-ai/dsh-session-reference":"0.2.0-rc.2","@deepseek-ai/dsh-session-title":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-llm":"0.2.0-rc.2","@deepseek-ai/dsh-settings":"0.2.0-rc.2","@deepseek-ai/dsh-skill":"0.2.0-rc.2","@deepseek-ai/dsh-spill":"0.2.0-rc.2","@deepseek-ai/dsh-spill-policy":"0.2.0-rc.2","@deepseek-ai/dsh-storage":"0.2.0-rc.2","@deepseek-ai/dsh-storage-domain":"0.2.0-rc.2","@deepseek-ai/dsh-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-in-process-driver":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-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-present":"0.2.0-rc.2","@deepseek-ai/dsh-tool-todo":"0.2.0-rc.2","@deepseek-ai/dsh-tool-web":"0.2.0-rc.2","@deepseek-ai/dsh-tool-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-tools":"0.2.0-rc.2","@deepseek-ai/dsh-typert-protocol":"0.2.0-rc.2","@deepseek-ai/dsh-typert-registry":"0.2.0-rc.2","@deepseek-ai/dsh-user-approval":"0.2.0-rc.2","@deepseek-ai/dsh-user-questions":"0.2.0-rc.2","@deepseek-ai/dsh-util-values":"0.2.0-rc.2","@deepseek-ai/dsh-web":"0.2.0-rc.2","@deepseek-ai/dsh-web-fetch-http":"0.2.0-rc.2","@deepseek-ai/dsh-web-search-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-workspace":"0.2.0-rc.2","@deepseek-ai/schemastery":"3.18.4","@mixmark-io/domino":"2.2.0","@modelcontextprotocol/sdk":"1.30.0",acorn:"8.18.0","fast-png":"8.0.0","jpeg-js":"0.4.4","just-bash":"3.4.2",minimatch:"10.2.6",playwright:"^1.49.0",re2js:"1.3.3",sucrase:"3.35.1",typescript:"^6.0.3",vitest:"^4.1.8",ws:"^8.21.0"}}});var t0,l3e,c3e,lS=oe(()=>{"use strict";o3e();t0=MH.version,l3e=MH.dshEdge.upstreamVersion,c3e=`npx dsh-edge@${t0.includes("-")?"next":"latest"} upgrade`});function npt(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 rpt(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 Qdt)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(rpt(i)){let s=npt(i),a=s??i;for(let l of ept)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 tpt)if(l.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function ipt(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function u3e(e,t,n){Kf(e);let r=new m8(new URL(e),{requestInit:{headers:ipt(t),signal:n},fetch:n0}),i=new f8({name:"dsh-edge",version:t0},{capabilities:{},jsonSchemaValidator:spt});return await i.connect(r),{client:i,close:o(async()=>{await i.close().catch(()=>{})},"close")}}async function d3e(e,t,n){let r=AbortSignal.timeout(ca.probeTimeoutMs),i;try{i=await u3e(t,n,r)}catch(l){throw new Error(Ap(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<ca.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>=ca.maxToolsPerServer)break;let v=r3e(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=i3e(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>=ca.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,ca.maxInstructionsLength):void 0}}finally{await a()}}async function S8(e,t,n,r,i,s){let a=s??ca.callTimeoutMs,l=i?AbortSignal.any([i,AbortSignal.timeout(a)]):AbortSignal.timeout(a),c;try{c=await u3e(e,r,l)}catch(u){throw new Error(Ap(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(Ap(u instanceof Error?u.message:String(u)))}finally{await c.close()}}var Qdt,ept,tpt,spt,n0,cS=oe(()=>{"use strict";h2e();G2e();t3e();x8();b8();lS();Qdt=[".internal",".local",".localhost"],ept=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],tpt=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];o(npt,"extractMappedIPv4");o(rpt,"isIpAddress");o(Kf,"assertSafeUrl");o(ipt,"buildHeaders");spt=new w8,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(u3e,"connectClient");o(d3e,"probe");o(S8,"callTool")});import{Buffer as apt}from"node:buffer";function upt(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&cpt.has(e.code)}function f3e(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&lpt.has(e.code)}function h3e(e,t,n){let r=apt.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 dpt(e){return h3e(e,"reject","INVALID_IMAGE_BASE64")}function ppt(e){return{data:dpt(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function uS(e,t){return e.saveImages(t.map(ppt))}async function fpt(e,t){return e.saveFile({data:h3e(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function m3e(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 p3e,opt,lpt,cpt,ar,jH,Jf=oe(()=>{Vn();p3e=["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"],opt=[...p3e,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],lpt=new Set(p3e),cpt=new Set(opt),ar=class extends Error{static{o(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};o(upt,"isAttachmentError");o(f3e,"isImageAdmissionError");o(h3e,"decodeCanonicalBase64");o(dpt,"decodeBase64");o(ppt,"saveInput");o(uS,"admitEncodedImages");o(fpt,"admitEncodedFile");o(m3e,"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 uS(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 fpt(this,e)}isAttachmentError(e){return upt(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 E8={};dn(E8,{buildAuthorizationUrl:()=>Spt,discoverEndpoints:()=>bpt,exchangeCode:()=>kpt,isTokenExpired:()=>_pt,refreshToken:()=>Ept,registerClient:()=>xpt});function w3e(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 wpt(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 bpt(e){let t=AbortSignal.timeout(k8),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 xpt(e,t,n){let r=AbortSignal.timeout(k8);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 Spt(e,t,n,r,i){let s=w3e(32),a=w3e(64),l=await wpt(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 kpt(e,t,n,r,i,s){let a=AbortSignal.timeout(k8),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 b3e(await c.json())}async function Ept(e,t,n,r){let i=AbortSignal.timeout(k8),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 b3e(await a.json())}function b3e(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 _pt(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var k8,_8=oe(()=>{"use strict";cS();k8=1e4;o(w3e,"randomString");o(wpt,"sha256Base64Url");o(bpt,"discoverEndpoints");o(xpt,"registerClient");o(Spt,"buildAuthorizationUrl");o(kpt,"exchangeCode");o(Ept,"refreshToken");o(b3e,"parseTokenResponse");o(_pt,"isTokenExpired")});var Ln,I3e,y3=oe(()=>{Vn();dr();Ln=class extends Lr{static{o(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},I3e=class extends St{static{o(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new Ln("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function rV(e){return M8.test(e)}function L8(e){return e.invocation.modelInvocable}function w3(e){return e.invocation.userInvocable}function iV(e){let t=cht(e);return[`<skill_content name="${uht(e.name)}">`,"<skill_resources>",...t,"</skill_resources>","","<skill_instructions>",e.content,"</skill_instructions>","</skill_content>"].join(`
|
|
156
156
|
`)}function cht(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 uht(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<")}function v3(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function pht(e,t){if(Array.isArray(e))return{candidates:e,complete:!0};if(e===null||typeof e!="object")throw K3e(t);let n=e;if(!Array.isArray(n.candidates)||typeof n.complete!="boolean")throw K3e(t);return n}function K3e(e){return new TypeError(`skill provider "${e}" list() must return an array or { candidates, complete } observation`)}function hht(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:lht,locator:e,...e.path!==void 0?{path:e.path}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}function mht(e,t){if(typeof e.name!="string")throw new TypeError(`skill provider "${t}" returned a non-string skill name`);if(!M8.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 ght(e){if(!M8.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 yht(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(!M8.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 vht(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 wht(e,t){return Q3e(e.name,t.name)}function Q3e(e,t){return e<t?-1:e>t?1:0}function bht(e,t){return e.candidate.rank-t.candidate.rank||e.providerOrder-t.providerOrder||e.localOrder-t.localOrder}function xht(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 J3e(e,t){return t===void 0?e:(hS(t),new Promise((n,r)=>{let i=o(()=>{t.removeEventListener("abort",s)},"cleanup"),s=o(()=>{i(),r(D8(t.reason))},"onAbort");t.addEventListener("abort",s,{once:!0}),e.then(a=>{i(),n(a)},a=>{i(),r(D8(a))})}))}function hS(e){if(e?.aborted===!0)throw D8(e.reason)}function D8(e){try{if(e instanceof Error)return e}catch{}return new Error(P8(e))}function P8(e){try{return String(e)}catch{return"[unrenderable thrown value]"}}var M8,Z3e,oht,$8,lht,Y3e,dht,X3e,fht,b3=oe(()=>{Vn();Wi();hl();cn();M8=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Z3e=128,oht=2,$8="runtime",lht=250,Y3e=600;o(rV,"isSkillName");o(L8,"isModelInvocable");o(w3,"isUserInvocable");o(iV,"renderSkillContent");o(cht,"renderResourceHint");o(uht,"escapeAttr");o(v3,"escapeText");dht=class{static{o(this,"SkillLayer")}providers;runtime=new Map;constructor(e){this.providers=new cp(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}},X3e=class extends St{static{o(this,"SkillRegistry")}static Config=L.object({collectCacheMaxEntries:L.number().default(Z3e)});collectCacheMaxEntries;layers=new up(e=>new dht(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,xht("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===$8)throw new Error(`"${$8}" 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){ght(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??$8};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=>vht(n.candidate)).sort(wht),complete:t.cacheable}}async get(e,t={}){if(!rV(e))return;let n=await this.collect(t);hS(t.signal);let r=n.entries.get(e);if(r===void 0)return;let i=await J3e(r.provider.get(r.candidate,t),t.signal);if(i!==void 0){if(yht(i),i.name!==r.candidate.name){this.invalidateEntry(r);return}return i}}async collect(e){hS(e.signal);let t=1;for(;;){let n=this.revision,r=this.collectCacheKey(e.cwd,jb(e.scope),n),i=this.collectCache.get(r);if(i!==void 0)return{entries:i,cacheable:!0};let s=await this.collectFresh(e);if(hS(e.signal),n!==this.revision){if(t<oht){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(bht);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){hS(t.signal);let n=[],r=!0,i=0;for(let s of[...e.runtime.values()].sort((a,l)=>Q3e(a.name,l.name)))n.push({candidate:hht(s),provider:fht,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 J3e(s.list(t),t.signal)}catch(d){if(t.signal?.aborted===!0)throw D8(t.signal.reason);r=!1,this.ctx.logger.warn(`skill provider "${s.name}" skipped: ${P8(d)}`)}if(c===void 0)continue;let u=pht(c,s.name);u.complete||(r=!1);for(let d of u.candidates)mht(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: ${P8(n)}`)})}catch(t){this.ctx.logger.warn(`skills/change listener threw: ${P8(t)}`)}}};o(pht,"normalizeProviderObservation");o(K3e,"invalidProviderObservation");fht={name:$8,list(){return Promise.resolve([])},get(e){return Promise.resolve(e.locator)}};o(hht,"runtimeCandidate");o(mht,"validateCandidate");o(ght,"validateRuntimeSkill");o(yht,"validateDefinition");o(vht,"toSummary");o(sV,"validateInvocation");o(wht,"compareSkillSummary");o(Q3e,"compareCodePoints");o(bht,"compareIndexedCandidates");o(xht,"assertPositiveInteger");o(J3e,"waitWithAbort");o(hS,"throwIfAborted");o(D8,"toError");o(P8,"errorMessage")});var xu,k3=oe(()=>{xu=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,bwe,HV=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"}},bwe=class extends St{static{o(this,"DirectoryPicker")}constructor(e){super(e,"directoryPicker")}}});var fxe=we((w8n,zA)=>{var pxe=pxe||function(e){return Buffer.from(e).toString("base64")};function g3t(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 gn=ke+mt,Bt=ke-mt,jt=lt+Ge,ae=lt-Ge,$e=Be+it,Ve=Be-it,at=Le+yt,Ct=Le-yt,Ye=gn+at,rn=gn-at,Qt=jt+$e,yn=jt-$e;ie[Re]=Ye+Qt,ie[Re+4]=Ye-Qt;var Dt=(yn+rn)*.707106781;ie[Re+2]=rn+Dt,ie[Re+6]=rn-Dt,Ye=Ct+Ve,Qt=Ve+ae,yn=ae+Bt;var Rr=(Ye-yn)*.382683433,Dr=.5411961*Ye+Rr,Qi=1.306562965*yn+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,qs=ke-mt,na=lt+Ge,Ft=lt-Ge,Pn=Be+it,ra=Be-it,Za=Le+yt,ya=Le-yt,va=xs+Za,Aa=xs-Za,Ka=na+Pn,ko=na-Pn;ie[Re]=va+Ka,ie[Re+32]=va-Ka;var fc=(ko+Aa)*.707106781;ie[Re+16]=Aa+fc,ie[Re+48]=Aa-fc,va=ya+ra,Ka=ra+Ft,ko=Ft+qs;var Al=(va-ko)*.382683433,zu=.5411961*va+Al,Wu=1.306562965*ko+Al,Hu=Ka*.707106781,Vu=qs+Hu,cf=qs-Hu;ie[Re+40]=cf+zu,ie[Re+24]=cf-zu,ie[Re+8]=Vu+Wu,ie[Re+56]=Vu-Wu,Re++}var Hd;for(kt=0;kt<pt;++kt)Hd=ie[kt]*Me[kt],g[kt]=Hd>0?Hd+.5|0:Hd-.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 gn=63;gn>0&&y[gn]==0;gn--);if(gn==0)return K(Le),ke;for(var Bt=1,jt;Bt<=gn;){for(var ae=Bt;y[Bt]==0&&Bt<=gn;++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 gn!=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,gn,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++],gn=yt[ae++],Bt=yt[ae++],k[at]=(R[pt]+R[gn+256>>0]+R[Bt+512>>0]>>16)-128,x[at]=(R[pt+768>>0]+R[gn+1024>>0]+R[Bt+1280>>0]>>16)-128,E[at]=(R[pt+1280>>0]+R[gn+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 zA>"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(g3t,"JPEGEncoder");typeof zA<"u"?zA.exports=dxe:typeof window<"u"&&(window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=dxe);function dxe(e,t){typeof t>"u"&&(t=50);var n=new g3t(t),r=n.encode(e,t);return{data:r,width:e.width,height:e.height}}o(dxe,"encode")});var mxe=we((x8n,iZ)=>{var rZ=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 gn=1;gn<64;){var Bt=K(Re.huffmanTableAC),jt=Bt&15,ae=Bt>>4;if(jt===0){if(ae<15)break;gn+=16;continue}gn+=ae;var $e=t[gn];kt[$e]=ee(jt),gn++}}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 gn=K(Re.huffmanTableAC),Bt=gn&15,jt=gn>>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,gn=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,gn=ae>>4;if($e===0)gn<15?(xe=F(gn)+(1<<gn),ce=4):(gn=16,ce=1);else{if($e!==1)throw new Error("invalid ACn encoding");ue=ee($e),ce=gn?2:3}continue;case 1:case 2:kt[Bt]?kt[Bt]+=(J()<<q)*jt:(gn--,gn===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,gn){var Bt=zt/B|0,jt=zt%B,ae=Bt*Re.v+pt,$e=jt*Re.h+gn;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,gn=zt%Re.blocksPerLine;Re.blocks[pt]===void 0&&$.tolerantDecoding||kt(Re,Re.blocks[pt][gn])}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),yn=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=yn,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++],gn=k[E++],Bt=m(k,E,X,mt,I,zt,pt,gn>>4,gn&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 iZ<"u"?iZ.exports=hxe:typeof window<"u"&&(window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=hxe);function hxe(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 rZ;s.opts=r,rZ.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),s.parse(i);var a=r.formatAsRGBA?4:3,l=s.width*s.height*a;try{rZ.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(hxe,"decode")});var yxe=we((k8n,gxe)=>{var y3t=fxe(),v3t=mxe();gxe.exports={encode:y3t,decode:v3t}});function X6e(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 mn({...e,content:s})}var Q6e=oe(()=>{Wi();o(X6e,"offloadMessageImages")});function eSe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function tSe(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0&&!Object.is(e,-0)}var c9,nK=oe(()=>{Q6e();o(eSe,"isRecord");o(tSe,"isIndex");c9={type:"image/offload",project(e,t){let n=e.data;if(!eSe(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(!eSe(s)||Object.keys(s).length!==2||!tSe(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(!tSe(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,X6e(u,s.imageIndexes))}return r}}});var E9,bke=oe(()=>{nK();E9=[c9]});async function Ake(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,...U_(a)]}}function jK(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 _9(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 FK(e){return{header:e.header,events:e.snapshotEvents()}}function T9(e,t){return e.map(n=>t.get(n))}async function UK(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: ${zK(n)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:n})}}async function xke(e,t,n){try{return await Ake(e,t,n)}catch(r){throw n?.aborted&&n.throwIfAborted(),r instanceof Error&&r.name==="SessionPersistenceCorruptionError"?new Ir(`stored session "${t}" is corrupt: ${zK(r)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:r}):new Ir(`failed to read stored session "${t}": ${zK(r)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:r})}}function Ske(e){return{header:structuredClone(e.header),inheritedEventCount:e.inheritedEventCount,events:e.snapshotEvents().map(t=>structuredClone(t))}}function _6t(e,t){return t.header.createdAt-e.header.createdAt||e.header.id.localeCompare(t.header.id)}function A9(e){return new Ir(`session "${e}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND")}function zK(e){return e instanceof Error?e.message:"unknown error"}function lk(e){if(e?.aborted===!0)throw new Ir("session observation was aborted","SESSION_QUERY_ABORTED",{cause:e.reason})}function kke(e,t){return Eke(t,"SessionPersistenceNotFoundError")?WK(e,t):Eke(t,"SessionPersistenceCorruptionError")?new Ir(`stored session "${e}" is corrupt: ${t.message}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:t}):new Ir(`failed to observe session "${e}": ${I9(t)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:t})}function WK(e,t){return new Ir(`session "${e}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND",t===void 0?void 0:{cause:t})}function I9(e){return e instanceof Error?e.message:"unknown error"}function Eke(e,t){return e instanceof Error&&e.name===t}function A6t(e){switch(e.type){case"user/message":return qK(e.data.content);case"assistant/message":return qK(e.data.message.content);case"tool/call":return ck([e.data.name,e.data.arguments]);case"tool/result":return ck([qK(e.data.message.content),e.data.error?.name??"",e.data.error?.code??""]);case"todo/write":return ck(e.data.todos.flatMap(t=>[t.status,t.content]));case"turn/end":return I6t(e.data.reason);case"turn/start":case"step/start":case"step/end":case"assistant/attempt":case"request/header":return"";default:return""}}function I6t(e){switch(e.kind){case"error":return ck(["error",e.error.message]);case"aborted":return"aborted";case"max-tokens":case"interrupted":return e.kind;case"completed":return"";default:return""}}function qK(e){return ck(e.flatMap(C6t))}function C6t(e){switch(e.type){case"text":return[e.text];case"reasoning":return[];case"tool-call":return[e.name,e.arguments];default:return[]}}function ck(e){return e.map(t=>t.trim()).filter(Boolean).join(`
|
|
157
157
|
`)}function VK(e,t){let n=R6t(t),r=[];for(let i of t){let s=A6t(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 R6t(e){let t;try{t=LP(e,E9)}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 GK(e,t=[]){let n=t.map(N6t);return e.filter(r=>n.every(i=>i(r)))}function N9(e,t=[]){let n=t.map($6t);return e.filter(r=>n.every(i=>i(r)))}function ZK(e){return Ike(e),e.map(t=>{switch(t.kind){case"id":return{kind:t.kind,values:R9(t.kind,t.values)};case"cwd":return{kind:t.kind,values:_ke(t.kind,t.values)};case"created-at":return Cke(t.kind,t);case"parent":return{kind:t.kind,values:_ke(t.kind,t.values)};case"availability":{let n=R9(t.kind,t.values);return D9(t.kind,n,["live","persisted"]),{kind:t.kind,values:n}}default:return P9(t)}})}function $9(e){return Ike(e),e.map(t=>{switch(t.kind){case"seq":case"time":return Cke(t.kind,t);case"type":return{kind:t.kind,values:R9(t.kind,t.values)};case"surface":{let n=R9(t.kind,t.values);return D9(t.kind,n,["current","shadowed","log-only"]),{kind:t.kind,values:n}}case"text":if(typeof t.text!="string")throw tv("text filter text must be a string");return{kind:t.kind,text:t.text};default:return P9(t)}})}function O6t(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 N6t(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=O9(e.kind,e);return n=>HK(n.header.createdAt,t)}case"parent":return t=>e.values.includes(t.header.parentSession??null);case"availability":return D9(e.kind,e.values,["live","persisted"]),t=>e.values.some(n=>n==="live"?t.live:t.persisted);default:return P9(e)}}function $6t(e){switch(e.kind){case"seq":{let t=O9(e.kind,e);return n=>HK(n.seq,t)}case"time":{let t=O9(e.kind,e);return n=>HK(n.time,t)}case"type":return t=>e.values.includes(t.type);case"surface":return D9(e.kind,e.values,["current","shadowed","log-only"]),t=>e.values.includes(t.surface);case"text":{let t=O6t(e.text);return n=>t.test(n.text)}default:return P9(e)}}function R9(e,t){if(!Rke(t)||t.some(n=>typeof n!="string"))throw tv(`${e} filter values must be an array of strings`);return[...t]}function Ike(e){if(!Array.isArray(e))throw tv("filters must be an array")}function _ke(e,t){if(!Rke(t)||t.some(n=>n!==null&&typeof n!="string"))throw tv(`${e} filter values must be an array of strings or null`);return[...t]}function Cke(e,t){let n={kind:e,...t.from===void 0?{}:{from:t.from},...t.to===void 0?{}:{to:t.to}};return O9(e,n),n}function P9(e){let t=e.kind;throw tv(`unknown filter kind ${typeof t=="string"?`"${t}"`:"(missing)"}`)}function D9(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 O9(e,t){if(t.from!==void 0&&!Number.isFinite(t.from))throw BK(e,"from must be finite");if(t.to!==void 0&&!Number.isFinite(t.to))throw BK(e,"to must be finite");if(t.from!==void 0&&t.to!==void 0&&t.from>t.to)throw BK(e,"from must be less than or equal to to");return t}function HK(e,t){return(t.from===void 0||e>=t.from)&&(t.to===void 0||e<=t.to)}function BK(e,t){return tv(`${e} filter ${t}`)}function tv(e){return new Ir(`session ${e}`,"SESSION_QUERY_INVALID_FILTER")}function Rke(e){return Array.isArray(e)}function P6t(e,t){return KK(e,t).records}function D6t(e,t){return KK(e,t).currentSeqs.map(n=>{let r=t[n];if(r===void 0||r.seq!==n||!tm(r))throw new Ir(`invalid session surface: current node ${n} is not a surface event`,"SESSION_QUERY_INVALID_SURFACE");return qb(r)})}function M6t(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=KK(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||Tke(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:[...Tke(r)],derivedEventSeqs:l}}function L6t(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=j6t(c,t),d={target:C9(r),ancestors:i.map(C9),descendants:u};return a!==void 0?{...d,complete:!1,unresolvedParentId:a}:{...d,complete:!0,root:C9(i.at(-1)??r)}}function KK(e,t){let n;try{n=LP(t,E9)}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 Tke(e){return e.sourceEventSeqs??[]}function j6t(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:C9(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 C9(e){return{...e,header:structuredClone(e.header)}}var Ir,E6t,T6t,Oke,JK=oe(()=>{bke();Vn();ks();xm();dr();Ir=class extends Lr{static{o(this,"SessionQueryError")}constructor(e,t,n){super(e,t,n)}};o(Ake,"readColdSessionLog");o(jK,"assertSessionHeadersCompatible");E6t=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 UK(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&&jK(i.header,s.header),r.set(i.id,{header:structuredClone(i.header),live:!0,persisted:s!==void 0})}return[...r.values()].sort(_6t)}async load(e,t){t?.throwIfAborted();let n=this._ctx.sessions.get(e);if(n!==void 0){let c=Ske(n);return t?.throwIfAborted(),c}let r=this._persistence;if(r===void 0)throw A9(e);let i=(await UK(r,t)).find(c=>c.id===e);if(t?.throwIfAborted(),i===void 0)throw A9(e);let s=await xke(r,e,t);t?.throwIfAborted();let a=this._ctx.sessions.get(e);if(a!==void 0){let c=Ske(a);return t?.throwIfAborted(),c}jK(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,_9(g,FK(y),t,n))}if(s.length===0)return T9(r,i);let a=this._persistence;if(a===void 0){for(let g of s)i.set(g,{sessionId:g,status:"rejected",reason:A9(g)});return T9(r,i)}let l;try{l=await UK(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 T9(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:A9(g)}:_9(g,FK(v),t,n));return}try{n?.throwIfAborted();let v=await xke(a,g,n);n?.throwIfAborted();let b=this._ctx.sessions.get(g);if(b!==void 0){i.set(g,_9(g,FK(b),t,n));return}jK(v.header,y),i.set(g,_9(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(),T9(r,i)}};o(_9,"projectSource");o(FK,"sourceLive");o(T9,"orderedResults");o(UK,"listPersisted");o(xke,"inspectPersisted");o(Ske,"snapshotLive");o(_6t,"compareSessions");o(A9,"notFound$1");o(zK,"errorMessage$1");T6t=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(;;){lk(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 WK(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);lk(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: ${I9(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}": ${I9(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 lk(n),kke(t,i)}if(lk(n),r===void 0)throw WK(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 Ake(e,t,n)}catch(r){throw lk(n),kke(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}": ${I9(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(lk,"throwIfObservationAborted");o(kke,"mapPersistenceFailure");o(WK,"notFound");o(I9,"errorMessage");o(Eke,"hasErrorName");o(A6t,"extractSessionEventText");o(I6t,"turnEndText");o(qK,"contentText");o(C6t,"blockText");o(ck,"joinText");o(VK,"buildSessionEventSearchDocuments");o(R6t,"classifySurface");o(GK,"filterSessionResults");o(N9,"filterSessionEventDocuments");o(ZK,"materializeSessionResultFilters");o($9,"materializeSessionEventResultFilters");o(O6t,"compileSessionTextFilter");o(N6t,"sessionPredicate");o($6t,"eventPredicate");o(R9,"copyStrings");o(Ike,"assertArray");o(_ke,"copyNullableStrings");o(Cke,"copyRange");o(P9,"unknownFilter");o(D9,"assertAllowedValues");o(O9,"validateRange");o(HK,"matchesRange");o(BK,"invalidRange");o(tv,"invalidFilter");o(Rke,"isRuntimeArray");o(P6t,"eventRecords");o(D6t,"currentSurfaceEvents");o(M6t,"traceEvent");o(L6t,"traceSession");o(KK,"analyzeEventLog");o(Tke,"eventSources");o(j6t,"buildDescendants");o(C9,"cloneRecord");Oke=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 E6t(e,n),this._observations=new T6t(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,E9),{session:structuredClone(t.header),inheritedEventCount:t.inheritedEventCount,events:t.events.map(qb)}}async filterSessions(e,t){let n=ZK(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=bm(n.events);return{session:structuredClone(n.header),...r===void 0?{}:{title:r}}},t)}async listEvents(e){return P6t(e,(await this._corpus.load(e)).events)}async filterEvents(e,t){let n=$9(t);return this._filterEvents(e,n)}async _filterSessions(e,t){return GK(await this._corpus.listSessions(t),e)}async _filterEvents(e,t){return N9(VK(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:D6t(e,t.events)}}async traceSession(e,t){let n=await this._corpus.listSessions(t);return t?.throwIfAborted(),L6t(n,e)}async traceEvent(e,t){let n=await this._corpus.load(e.sessionId,t);return t?.throwIfAborted(),{session:n.header,...M6t(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=qb(a),d=s.events.slice(l,c+1).map(p=>p===a?u:qb(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 nv=we((kCn,zke)=>{"use strict";zke.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 rJ=we((_Cn,Hke)=>{"use strict";var Wke=nv();Hke.exports=nJ;function nJ(){Wke.call(this),this.view=null,this.detail=0}o(nJ,"UIEvent");nJ.prototype=Object.create(Wke.prototype,{constructor:{value:nJ},initUIEvent:{value:o(function(e,t,n,r,i){this.initEvent(e,t,n),this.view=r,this.detail=i},"value")}})});var sJ=we((ACn,Gke)=>{"use strict";var Vke=rJ();Gke.exports=iJ;function iJ(){Vke.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(iJ,"MouseEvent");iJ.prototype=Object.create(Vke.prototype,{constructor:{value:iJ},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 q9=we((CCn,Kke)=>{"use strict";Kke.exports=U9;var tSt=1,nSt=3,rSt=4,iSt=5,sSt=7,aSt=8,oSt=9,lSt=11,cSt=12,uSt=13,dSt=14,pSt=15,fSt=17,hSt=18,mSt=19,gSt=20,ySt=21,vSt=22,wSt=23,bSt=24,xSt=25,SSt=[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"],kSt=[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."],Zke={INDEX_SIZE_ERR:tSt,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:nSt,WRONG_DOCUMENT_ERR:rSt,INVALID_CHARACTER_ERR:iSt,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:sSt,NOT_FOUND_ERR:aSt,NOT_SUPPORTED_ERR:oSt,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:lSt,SYNTAX_ERR:cSt,INVALID_MODIFICATION_ERR:uSt,NAMESPACE_ERR:dSt,INVALID_ACCESS_ERR:pSt,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:fSt,SECURITY_ERR:hSt,NETWORK_ERR:mSt,ABORT_ERR:gSt,URL_MISMATCH_ERR:ySt,QUOTA_EXCEEDED_ERR:vSt,TIMEOUT_ERR:wSt,INVALID_NODE_TYPE_ERR:bSt,DATA_CLONE_ERR:xSt};function U9(e){Error.call(this),Error.captureStackTrace(this,this.constructor),this.code=e,this.message=kSt[e],this.name=SSt[e]}o(U9,"DOMException");U9.prototype.__proto__=Error.prototype;for(F9 in Zke)aJ={value:Zke[F9]},Object.defineProperty(U9,F9,aJ),Object.defineProperty(U9.prototype,F9,aJ);var aJ,F9});var B9=we(Jke=>{Jke.isApiWritable=!globalThis.__domino_frozen__});var Ks=we(Ci=>{"use strict";var Zs=q9(),ua=Zs,ESt=B9().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 Zs(ua.INDEX_SIZE_ERR)};Ci.HierarchyRequestError=function(){throw new Zs(ua.HIERARCHY_REQUEST_ERR)};Ci.WrongDocumentError=function(){throw new Zs(ua.WRONG_DOCUMENT_ERR)};Ci.InvalidCharacterError=function(){throw new Zs(ua.INVALID_CHARACTER_ERR)};Ci.NoModificationAllowedError=function(){throw new Zs(ua.NO_MODIFICATION_ALLOWED_ERR)};Ci.NotFoundError=function(){throw new Zs(ua.NOT_FOUND_ERR)};Ci.NotSupportedError=function(){throw new Zs(ua.NOT_SUPPORTED_ERR)};Ci.InvalidStateError=function(){throw new Zs(ua.INVALID_STATE_ERR)};Ci.SyntaxError=function(){throw new Zs(ua.SYNTAX_ERR)};Ci.InvalidModificationError=function(){throw new Zs(ua.INVALID_MODIFICATION_ERR)};Ci.NamespaceError=function(){throw new Zs(ua.NAMESPACE_ERR)};Ci.InvalidAccessError=function(){throw new Zs(ua.INVALID_ACCESS_ERR)};Ci.TypeMismatchError=function(){throw new Zs(ua.TYPE_MISMATCH_ERR)};Ci.SecurityError=function(){throw new Zs(ua.SECURITY_ERR)};Ci.NetworkError=function(){throw new Zs(ua.NETWORK_ERR)};Ci.AbortError=function(){throw new Zs(ua.ABORT_ERR)};Ci.UrlMismatchError=function(){throw new Zs(ua.URL_MISMATCH_ERR)};Ci.QuotaExceededError=function(){throw new Zs(ua.QUOTA_EXCEEDED_ERR)};Ci.TimeoutError=function(){throw new Zs(ua.TIMEOUT_ERR)};Ci.InvalidNodeTypeError=function(){throw new Zs(ua.INVALID_NODE_TYPE_ERR)};Ci.DataCloneError=function(){throw new Zs(ua.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:ESt})};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 oJ=we(($Cn,Xke)=>{"use strict";var S0=nv(),_St=sJ(),TSt=Ks();Xke.exports=Yke;function Yke(){}o(Yke,"EventTarget");Yke.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)&&TSt.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 _St)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 lJ=we((DCn,Qke)=>{"use strict";var ah=Ks(),_u=Qke.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(_u.valid(e)&&_u.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(_u.valid(e)&&_u.valid(t))},"insertBefore"),replace:o(function(e,t){ah.assert(_u.valid(e)&&(t===null||_u.valid(t))),t!==null&&_u.insertBefore(t,e),_u.remove(e),ah.assert(_u.valid(e)&&(t===null||_u.valid(t)))},"replace"),remove:o(function(e){ah.assert(_u.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(_u.valid(e))}},"remove")}});var cJ=we((LCn,o4e)=>{"use strict";o4e.exports={serializeOne:$St,\u0275escapeMatchingClosingTag:i4e,\u0275escapeClosingCommentTag:s4e,\u0275escapeProcessingInstructionContent:a4e};var r4e=Ks(),k0=r4e.NAMESPACE,e4e={STYLE:!0,SCRIPT:!0,XMP:!0,IFRAME:!0,NOEMBED:!0,NOFRAMES:!0,PLAINTEXT:!0},ASt={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},ISt={},t4e=/[&<>\u00A0]/g,n4e=/[&"<>\u00A0]/g;function CSt(e){return t4e.test(e)?e.replace(t4e,t=>{switch(t){case"&":return"&";case"<":return"<";case">":return">";case"\xA0":return" "}}):e}o(CSt,"escape");function RSt(e){return n4e.test(e)?e.replace(n4e,t=>{switch(t){case"<":return"<";case">":return">";case"&":return"&";case'"':return""";case"\xA0":return" "}}):e}o(RSt,"escapeAttr");function OSt(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(OSt,"attrname");function i4e(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]="<";return r.join("")}o(i4e,"escapeMatchingClosingTag");var NSt=/--!?>/;function s4e(e){return NSt.test(e)?e.replace(/(--\!?)>/g,"$1>"):e}o(s4e,"escapeClosingCommentTag");function a4e(e){return e.includes(">")?e.replaceAll(">",">"):e}o(a4e,"escapeProcessingInstructionContent");function $St(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+=" "+OSt(c),c.value!==void 0&&(n+='="'+RSt(c.value)+'"')}if(n+=">",!(i&&ASt[s])){var u=e.serialize();e4e[s.toUpperCase()]&&(u=i4e(u,s)),i&&ISt[s]&&u.charAt(0)===`
|
|
@@ -5844,7 +5844,7 @@ The web search request used endpoint ${JSON.stringify(e)}. Search endpoint confi
|
|
|
5844
5844
|
.error { padding: .75rem; border-radius: .5rem; background: #461d2b; color: #ffd6df; }
|
|
5845
5845
|
.hint { margin: 1.5rem 0 0; font-size: .875rem; }
|
|
5846
5846
|
code { padding: .1rem .3rem; border-radius: .3rem; background: #0c1222; color: #edf2ff; }
|
|
5847
|
-
`}o(GRe,"pageStyles");lS();var Tte="enabled",Ate=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")}),S4=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")}),Ite=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:o(e=>e.DSH_EDGE_CONTAINER_RUNTIME===Tte?"available":"needs-binding","probe")}),azt=Object.freeze([Ite,S4,Ate]);function Cte(e,t=azt){return t.filter(n=>n.probe(e)==="available")}o(Cte,"availableEdgeRuntimeProviders");function Rte(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(Rte,"resolveEdgeRuntimeSelection");function vR(e){let t=Cte(e),{bash:n,container:r}=Rte(t);return t.find(i=>i.id===(r??n)).shell}o(vR,"resolveEdgeRuntimeShell");function ozt(){return"dsh-edge@0.22.0-alpha.1/isolated"}o(ozt,"resolveEdgeDeploymentId");function Uv(e){return{baseURL:gG(e.DEEPSEEK_BASE_URL),maxTokens:wG(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:a0(e.DEEPSEEK_MODEL),reasoningEffort:yG(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:Nk(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:vG(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:k1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}o(Uv,"resolveEdgeDeploymentConfig");function lzt(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}o(lzt,"edgeDeploymentApiKeyConfigured");function czt(e){let t=gG(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}o(czt,"projectedEdgeBaseURL");function Ote(e,t){return{shell:vR(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:ozt(),apiKeyConfigured:lzt(e),baseURL:czt(e.DEEPSEEK_BASE_URL),maxTokens:wG(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:a0(e.DEEPSEEK_MODEL),reasoningEffort:yG(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:Nk(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:vG(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:k1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}o(Ote,"resolveEdgeDeploymentProfile");function wR(e){Uv(e);let t=Ote(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:l3e,status:"ready"}}o(wR,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as CQt}from"node:async_hooks";import{RpcTarget as uzt}from"cloudflare:workers";function dzt(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(dzt,"startHeartbeat");async function pzt(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(pzt,"probeComputerdHealth");var fzt="computer.internal",hzt="/health",Nte="/api",mzt=8080,gzt=3e4,yzt=2e4,vzt=1,wzt=2e3,bzt=250,xzt=2e3;function Szt(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(Szt,"bearerMatches");var xR=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??fzt,containerPort:e.containerPort??mzt,connectTimeoutMs:e.connectTimeoutMs??gzt,heartbeatIntervalMs:e.heartbeatIntervalMs??yzt,restartAttempts:e.restartAttempts??vzt,healthProbeTimeoutMs:e.healthProbeTimeoutMs??wzt,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??bzt,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??xzt}}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=iN(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=dzt({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(fw),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(mE),i.delete(fw);let l=new Request(e,{headers:i});return this.#t.gateway.fetch(new Request(a,l))}if(new URL(e.url).pathname!==Nte)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${Nte} requires a websocket upgrade`,{status:400});if(!Szt(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 pzt(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 kzt(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=${ZRe(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:hzt,api:Nte,healthTimeoutMs:r})})}catch(s){throw this.#o?.(s),this.#a(),new Ko(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${ZRe(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 kzt(e){return new Promise(t=>setTimeout(t,e))}o(kzt,"sleep");function ZRe(e){return e instanceof Error?e.message:String(e)}o(ZRe,"describeError");var KRe="computer:container-client-secret",Ezt=16;function _zt(){let e=crypto.getRandomValues(new Uint8Array(Ezt));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}o(_zt,"generate");var Tzt=class{static{o(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(KRe);if(typeof e=="string"&&e.length>0)return e;let t=_zt();return await this.storage.put(KRe,t),t}},JRe="computer:container-launch-record";async function YRe(e){return{enableInternet:e.enableInternet,envDigest:await Izt(e.env)}}o(YRe,"launchRecordFor");function Azt(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}o(Azt,"sameLaunch");async function Izt(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(Izt,"digestEnv");var Czt=class{static{o(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(JRe)??null}async set(e){await this.storage.put(JRe,e)}},XRe=new WeakMap;function Dte(e){let t=XRe.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},XRe.set(e,t)),t}o(Dte,"getContainerLifecycle");function bR(e){return Dte(e).exit}o(bR,"containerExitInfo");function QRe(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}o(QRe,"formatExitReason");function eOe(e,t,n){let r=Dte(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>tOe(r,i,void 0,n),s=>tOe(r,i,s,n))}o(eOe,"installContainerMonitor");async function $te(e,t){let n=Dte(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}o($te,"destroyContainerExpectingExit");async function tOe(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=QRe(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:QRe(l),exitedAt:Date.now()})}}o(tOe,"recordExit");var Pte="computer:container-runtime-identity",Rzt=class{static{o(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(Pte)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(Pte,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(Pte)}},Ozt=class extends uzt{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 Rzt(e.storage),this.#n=new Tzt(e.storage),this.#i=new Czt(e.storage)}async start(e){let t=bR(this.#t),n=await this.#n.ensure(),r=await YRe(e);if(t!==null){try{await $te(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||!Azt(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 $te(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return eOe(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await $te(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await YRe(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),eOe(this.#t,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:bR(this.#t)}}async exitInfo(){return bR(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=bR(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 nOe(e){class t extends e{static{o(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new Ozt(this.ctx)}}return t}o(nOe,"withWorkspaceContainer");var Nzt={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function iOe(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=Nzt[s]??s,c=e[l];if(c===void 0)return;let u=c[a];return typeof u=="function"?u:void 0}o(iOe,"resolve");function $zt(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}o($zt,"errorResponse");async function Mte(e,t,n,r,i){let s=iOe(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}o(Mte,"callEdgeApi");async function sOe(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(iOe(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 Mte(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 $zt(a,{code:"internal",message:String(c),details:{}})}}o(sOe,"dispatchEdgeApi");dr();ks();xm();import{DurableObject as RQt}from"cloudflare:workers";var SR=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 Pzt(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 Pzt(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(Pzt,"untilAborted");import{WorkerEntrypoint as JWn}from"cloudflare:workers";var ly=Rl(aOe(),1);import{gunzipSync as iVt}from"node:zlib";var k4=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 Lte=class extends k4{static{o(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=Mzt}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
|
|
5847
|
+
`}o(GRe,"pageStyles");lS();var Tte="enabled",Ate=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")}),S4=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")}),Ite=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:o(e=>e.DSH_EDGE_CONTAINER_RUNTIME===Tte?"available":"needs-binding","probe")}),azt=Object.freeze([Ite,S4,Ate]);function Cte(e,t=azt){return t.filter(n=>n.probe(e)==="available")}o(Cte,"availableEdgeRuntimeProviders");function Rte(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(Rte,"resolveEdgeRuntimeSelection");function vR(e){let t=Cte(e),{bash:n,container:r}=Rte(t);return t.find(i=>i.id===(r??n)).shell}o(vR,"resolveEdgeRuntimeShell");function ozt(){return"dsh-edge@0.22.0/isolated"}o(ozt,"resolveEdgeDeploymentId");function Uv(e){return{baseURL:gG(e.DEEPSEEK_BASE_URL),maxTokens:wG(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:a0(e.DEEPSEEK_MODEL),reasoningEffort:yG(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:Nk(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:vG(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:k1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}o(Uv,"resolveEdgeDeploymentConfig");function lzt(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}o(lzt,"edgeDeploymentApiKeyConfigured");function czt(e){let t=gG(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}o(czt,"projectedEdgeBaseURL");function Ote(e,t){return{shell:vR(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:ozt(),apiKeyConfigured:lzt(e),baseURL:czt(e.DEEPSEEK_BASE_URL),maxTokens:wG(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:a0(e.DEEPSEEK_MODEL),reasoningEffort:yG(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:Nk(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:vG(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:k1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}o(Ote,"resolveEdgeDeploymentProfile");function wR(e){Uv(e);let t=Ote(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:l3e,status:"ready"}}o(wR,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as CQt}from"node:async_hooks";import{RpcTarget as uzt}from"cloudflare:workers";function dzt(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(dzt,"startHeartbeat");async function pzt(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(pzt,"probeComputerdHealth");var fzt="computer.internal",hzt="/health",Nte="/api",mzt=8080,gzt=3e4,yzt=2e4,vzt=1,wzt=2e3,bzt=250,xzt=2e3;function Szt(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(Szt,"bearerMatches");var xR=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??fzt,containerPort:e.containerPort??mzt,connectTimeoutMs:e.connectTimeoutMs??gzt,heartbeatIntervalMs:e.heartbeatIntervalMs??yzt,restartAttempts:e.restartAttempts??vzt,healthProbeTimeoutMs:e.healthProbeTimeoutMs??wzt,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??bzt,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??xzt}}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=iN(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=dzt({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(fw),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(mE),i.delete(fw);let l=new Request(e,{headers:i});return this.#t.gateway.fetch(new Request(a,l))}if(new URL(e.url).pathname!==Nte)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${Nte} requires a websocket upgrade`,{status:400});if(!Szt(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 pzt(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 kzt(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=${ZRe(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:hzt,api:Nte,healthTimeoutMs:r})})}catch(s){throw this.#o?.(s),this.#a(),new Ko(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${ZRe(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 kzt(e){return new Promise(t=>setTimeout(t,e))}o(kzt,"sleep");function ZRe(e){return e instanceof Error?e.message:String(e)}o(ZRe,"describeError");var KRe="computer:container-client-secret",Ezt=16;function _zt(){let e=crypto.getRandomValues(new Uint8Array(Ezt));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}o(_zt,"generate");var Tzt=class{static{o(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(KRe);if(typeof e=="string"&&e.length>0)return e;let t=_zt();return await this.storage.put(KRe,t),t}},JRe="computer:container-launch-record";async function YRe(e){return{enableInternet:e.enableInternet,envDigest:await Izt(e.env)}}o(YRe,"launchRecordFor");function Azt(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}o(Azt,"sameLaunch");async function Izt(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(Izt,"digestEnv");var Czt=class{static{o(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(JRe)??null}async set(e){await this.storage.put(JRe,e)}},XRe=new WeakMap;function Dte(e){let t=XRe.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},XRe.set(e,t)),t}o(Dte,"getContainerLifecycle");function bR(e){return Dte(e).exit}o(bR,"containerExitInfo");function QRe(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}o(QRe,"formatExitReason");function eOe(e,t,n){let r=Dte(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>tOe(r,i,void 0,n),s=>tOe(r,i,s,n))}o(eOe,"installContainerMonitor");async function $te(e,t){let n=Dte(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}o($te,"destroyContainerExpectingExit");async function tOe(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=QRe(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:QRe(l),exitedAt:Date.now()})}}o(tOe,"recordExit");var Pte="computer:container-runtime-identity",Rzt=class{static{o(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(Pte)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(Pte,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(Pte)}},Ozt=class extends uzt{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 Rzt(e.storage),this.#n=new Tzt(e.storage),this.#i=new Czt(e.storage)}async start(e){let t=bR(this.#t),n=await this.#n.ensure(),r=await YRe(e);if(t!==null){try{await $te(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||!Azt(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 $te(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return eOe(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await $te(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await YRe(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),eOe(this.#t,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:bR(this.#t)}}async exitInfo(){return bR(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=bR(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 nOe(e){class t extends e{static{o(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new Ozt(this.ctx)}}return t}o(nOe,"withWorkspaceContainer");var Nzt={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function iOe(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=Nzt[s]??s,c=e[l];if(c===void 0)return;let u=c[a];return typeof u=="function"?u:void 0}o(iOe,"resolve");function $zt(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}o($zt,"errorResponse");async function Mte(e,t,n,r,i){let s=iOe(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}o(Mte,"callEdgeApi");async function sOe(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(iOe(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 Mte(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 $zt(a,{code:"internal",message:String(c),details:{}})}}o(sOe,"dispatchEdgeApi");dr();ks();xm();import{DurableObject as RQt}from"cloudflare:workers";var SR=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 Pzt(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 Pzt(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(Pzt,"untilAborted");import{WorkerEntrypoint as JWn}from"cloudflare:workers";var ly=Rl(aOe(),1);import{gunzipSync as iVt}from"node:zlib";var k4=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 Lte=class extends k4{static{o(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=Mzt}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
|
|
5848
5848
|
`))&&(t=t.trim()),(!r.newlineIsToken||!n.includes(`
|
|
5849
5849
|
`))&&(n=n.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
|
|
5850
5850
|
`)&&(t=t.slice(0,-1)),n.endsWith(`
|