dsh-edge 0.23.0-alpha.2 → 0.23.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=Gs(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"?yx(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=>yx(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`;Gs(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=Gs(e,Ke,n,r,i,h===!0?s:null,o,`${ze}/${st}`,yt);Ee.push(...Oe.errors),wt=wt||Oe.valid,Oe.valid&&ut.push(yt)}wt?Ee.length=je:Ee.splice(je,0,{instanceLocation:o,keyword:"anyOf",keywordLocation:ze,error:"Instance does not match any subschemas."})}if(k!==void 0){let ze=`${c}/allOf`,je=Ee.length,wt=!0;for(let st=0;st<k.length;st++){let Ke=k[st],yt=Object.create(l),Oe=Gs(e,Ke,n,r,i,h===!0?s:null,o,`${ze}/${st}`,yt);Ee.push(...Oe.errors),wt=wt&&Oe.valid,Oe.valid&&ut.push(yt)}wt?Ee.length=je:Ee.splice(je,0,{instanceLocation:o,keyword:"allOf",keywordLocation:ze,error:"Instance does not match every subschema."})}if(E!==void 0){let ze=`${c}/oneOf`,je=Ee.length,wt=E.filter((st,Ke)=>{let yt=Object.create(l),Oe=Gs(e,st,n,r,i,h===!0?s:null,o,`${ze}/${Ke}`,yt);return Ee.push(...Oe.errors),Oe.valid&&ut.push(yt),Oe.valid}).length;wt===1?Ee.length=je:Ee.splice(je,0,{instanceLocation:o,keyword:"oneOf",keywordLocation:ze,error:`Instance does not match exactly one subschema (${wt} matches).`})}if((d==="object"||d==="array")&&Object.assign(l,...ut),_!==void 0){let ze=`${c}/if`;if(Gs(e,_,n,r,i,s,o,ze,l).valid){if(T!==void 0){let wt=Gs(e,T,n,r,i,s,o,`${c}/then`,l);wt.valid||Ee.push({instanceLocation:o,keyword:"if",keywordLocation:ze,error:'Instance does not match "then" schema.'},...wt.errors)}}else if(P!==void 0){let wt=Gs(e,P,n,r,i,s,o,`${c}/else`,l);wt.valid||Ee.push({instanceLocation:o,keyword:"if",keywordLocation:ze,error:'Instance does not match "else" schema.'},...wt.errors)}}if(d==="object"){if(w!==void 0)for(let st of w)st in e||Ee.push({instanceLocation:o,keyword:"required",keywordLocation:`${c}/required`,error:`Instance does not have required property "${st}".`});let ze=Object.keys(e);if(I!==void 0&&ze.length<I&&Ee.push({instanceLocation:o,keyword:"minProperties",keywordLocation:`${c}/minProperties`,error:`Instance does not have at least ${I} properties.`}),U!==void 0&&ze.length>U&&Ee.push({instanceLocation:o,keyword:"maxProperties",keywordLocation:`${c}/maxProperties`,error:`Instance does not have at least ${U} properties.`}),C!==void 0){let st=`${c}/propertyNames`;for(let Ke in e){let yt=`${o}/${vu(Ke)}`,Oe=Gs(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=Gs(e,O[st],n,r,i,s,o,`${Ke}/${vu(st)}`,l);yt.valid||Ee.push({instanceLocation:o,keyword:"dependentSchemas",keywordLocation:Ke,error:`Instance has "${st}" but does not match dependant schema.`},...yt.errors)}}if(N!==void 0){let st=`${c}/dependencies`;for(let Ke in N)if(Ke in e){let yt=N[Ke];if(Array.isArray(yt))for(let Oe of yt)Oe in e||Ee.push({instanceLocation:o,keyword:"dependencies",keywordLocation:st,error:`Instance has "${Ke}" but does not have "${Oe}".`});else{let Oe=Gs(e,yt,n,r,i,s,o,`${st}/${vu(Ke)}`);Oe.valid||Ee.push({instanceLocation:o,keyword:"dependencies",keywordLocation:st,error:`Instance has "${Ke}" but does not match dependant schema.`},...Oe.errors)}}}let je=Object.create(null),wt=!1;if(j!==void 0){let st=`${c}/properties`;for(let Ke in j){if(!(Ke in e))continue;let yt=`${o}/${vu(Ke)}`,Oe=Gs(e[Ke],j[Ke],n,r,i,s,yt,`${st}/${vu(Ke)}`);if(Oe.valid)l[Ke]=je[Ke]=!0;else if(wt=i,Ee.push({instanceLocation:o,keyword:"properties",keywordLocation:st,error:`Property "${Ke}" does not match schema.`},...Oe.errors),wt)break}}if(!wt&&$!==void 0){let st=`${c}/patternProperties`;for(let Ke in $){let yt=new RegExp(Ke,"u"),Oe=$[Ke];for(let _t in e){if(!yt.test(_t))continue;let Gt=`${o}/${vu(_t)}`,ht=Gs(e[_t],Oe,n,r,i,s,Gt,`${st}/${vu(Ke)}`);ht.valid?l[_t]=je[_t]=!0:(wt=i,Ee.push({instanceLocation:o,keyword:"patternProperties",keywordLocation:st,error:`Property "${_t}" matches pattern "${Ke}" but does not match associated schema.`},...ht.errors))}}}if(!wt&&W!==void 0){let st=`${c}/additionalProperties`;for(let Ke in e){if(je[Ke])continue;let yt=`${o}/${vu(Ke)}`,Oe=Gs(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}/${vu(Ke)}`,Oe=Gs(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(M!==void 0){let st=`${c}/prefixItems`,Ke=Math.min(M.length,ze);for(;je<Ke;je++){let yt=Gs(e[je],M[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=Gs(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=Gs(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=Gs(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=Gs(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=Gs(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)&&yx(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:kEe(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&&nY[D]&&!nY[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 sY=ce(()=>{tY();O9();rY();R9();iY();a(Gs,"validate")});var $9,EEe=ce(()=>{O9();sY();$9=class{static{a(this,"Validator")}schema;draft;shortCircuit;lookup;constructor(t,n="2019-09",r=!0){this.schema=t,this.draft=n,this.shortCircuit=r,this.lookup=ym(t)}validate(t){return Gs(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,n){n&&(t={...t,$id:n}),ym(t,this.lookup)}}});var _Ee=ce(()=>{tY();O9();rY();R9();SEe();iY();sY();EEe()});var N9,TEe=ce(()=>{_Ee();N9=class{static{a(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let n=new $9(t,this.draft,this.shortcircuit);return r=>{let i=n.validate(r);return i.valid?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:i.errors.map(s=>`${s.instanceLocation}: ${s.error}`).join("; ")}}}}});var Mo,P9=ce(()=>{"use strict";Mo={probeTimeoutMs:3e4,callTimeoutMs:6e4,maxToolsPerServer:128,maxCatalogPages:10,maxCatalogBytes:131072,maxDescriptionLength:512,maxErrorMessageChars:300,maxPublicNameLength:64,maxInstructionsLength:1024,metaToolThreshold:20}});import{createHash as Rxt}from"node:crypto";function $xt(e){let t=e.replace(/[.*+?^${}()|[\]\\]/gu,n=>n==="*"?"\0":`\\${n}`);return new RegExp(`^${t.replaceAll("\0",".*")}$`)}function AEe(e,t,n){let r=t??"read_only";return r==="allow_all"?"allow":r==="approve_all"?"ask":n===!0?"allow":n===!1?"ask":Oxt.some(i=>$xt(i).test(e))?"allow":"ask"}function Uf(e){return e.replace(/Bearer\s+[^\s"']+/giu,"Bearer ***").replace(/(https?:\/\/[^\s"'?]+)\?[^\s"']*/giu,"$1?***").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/gu,"").slice(0,Mo.maxErrorMessageChars)}function IEe(e,t){let n=`mcp__${e}__${t}`,r=n.replace(/[^A-Za-z0-9_-]/gu,"_");if(r===n&&r.length<=Mo.maxPublicNameLength)return r;let i=Nxt(e,t),s=Mo.maxPublicNameLength-i.length-1;return`${r.slice(0,s)}_${i}`}function Nxt(e,t){return Rxt("sha256").update(`${e}\0${t}`).digest("hex").slice(0,12)}function CEe(e){if(!(e==null||typeof e!="object"))try{let t=JSON.parse(JSON.stringify(e));return ny(t),t}catch{return}}function Mxt(e){return Pxt.has(e)}function REe(e){return e.type!=="image"||e.data===void 0||e.mimeType===void 0||!Mxt(e.mimeType)||!Dxt.test(e.data)?void 0:{data:Uint8Array.from(atob(e.data),n=>n.charCodeAt(0)),mediaType:e.mimeType}}function OEe(e){return e.some(t=>t.type==="image"&&t.data!==void 0)}function j6(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 Oxt,Pxt,Dxt,D9=ce(()=>{"use strict";co();P9();Oxt=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a($xt,"globToRegExp");a(AEe,"evaluateMcpToolPolicy");a(Uf,"scrubMcpErrorMessage");a(IEe,"publicToolName");a(Nxt,"hashSuffix");a(CEe,"supportedOutputSchema");Pxt=new Set(["image/png","image/jpeg"]),Dxt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(Mxt,"isImageMediaType");a(REe,"decodeImageBlock");a(OEe,"containsImage");a(j6,"mapMcpResultToContentBlocks")});var oY,$Ee=ce(()=>{oY={name:"dsh-edge",version:"0.23.0-alpha.2",description:"Your DeepSeek Harness, anywhere \u2014 deploy a persistent personal coding agent to Cloudflare Workers in one command",author:"pawaca",license:"MIT",type:"module",bin:{"dsh-edge":"scripts/cli.mjs"},files:["dist","worker","scripts/*.d.mts","scripts/*.mjs","wrangler.jsonc","README.md","README.zh.md","LICENSE","THIRD_PARTY_NOTICES.md"],repository:{type:"git",url:"git+https://github.com/pawaca/dsh-edge.git",directory:"apps/dsh-edge"},homepage:"https://github.com/pawaca/dsh-edge#readme",bugs:{url:"https://github.com/pawaca/dsh-edge/issues"},keywords:["deepseek","deepseek-harness","ai-agents","byok","cloudflare-workers","durable-objects","self-hosted"],engines:{node:">=22.14.0"},publishConfig:{access:"public"},dshEdge:{upstreamVersion:"0.2.0-rc.2"},scripts:{"bundle:direct":"pnpm run web:build && pnpm --dir standalone run build:worker:direct && node standalone/scripts/promote.mjs direct","bundle:isolated":"pnpm run web:build && pnpm --dir standalone run build:worker:isolated && node standalone/scripts/promote.mjs isolated","bundle:workers":"pnpm --dir standalone run build && pnpm --dir standalone run verify && node standalone/scripts/promote.mjs all",dev:"pnpm run bundle:direct && node scripts/dev.mjs direct","dev:isolated":"pnpm run bundle:isolated && node scripts/dev.mjs isolated","dev:container":"pnpm run bundle:isolated && node scripts/dev.mjs container","dsh-edge":"node scripts/cli.mjs","example:install":"node examples/install-keyless.mjs","install:cloudflare":"pnpm run bundle:workers && node scripts/cli.mjs install","legal:write":"node scripts/legal-files.mjs write","pack:verify":"node scripts/verify-packed.mjs",prepack:"node scripts/legal-files.mjs verify && pnpm run bundle:workers","web:build":"pnpm --dir standalone run build:web && node standalone/scripts/promote.mjs web",test:"vitest run --root ../.. --project edge-runtime","test:integration":"pnpm run bundle:workers && node tests/run-session-integration.mjs","test:container":"pnpm run bundle:isolated && node tests/container.integration.mjs","test:snapshot":"vitest run --root ../.. --config apps/dsh-edge/vitest.snapshot.config.ts",typecheck:"tsc --noEmit"},dependencies:{"@clack/prompts":"1.7.0","compare-versions":"6.1.1",execa:"^10.0.1","jsonc-parser":"^3.3.1",wrangler:"4.129.0",yaml:"2.9.0"},devDependencies:{"@cfworker/json-schema":"^4.1.1","@cloudflare/computer":"0.3.1","@cloudflare/workers-types":"5.20260904.1","@deepseek-ai/cordis":"4.0.4","@deepseek-ai/cosmokit":"1.8.5","@deepseek-ai/dsh-agent":"0.2.0-rc.2","@deepseek-ai/dsh-agent-instructions":"0.2.0-rc.2","@deepseek-ai/dsh-agent-loop":"0.2.0-rc.2","@deepseek-ai/dsh-anonymous-user-id":"0.2.0-rc.2","@deepseek-ai/dsh-api-gateway":"0.2.0-rc.2","@deepseek-ai/dsh-api-job-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-remotes":"0.2.0-rc.2","@deepseek-ai/dsh-api-session-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-settings-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-workspace-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-workspace-files":"0.2.0-rc.2","@deepseek-ai/dsh-attachment":"0.2.0-rc.2","@deepseek-ai/dsh-brand":"0.2.0-rc.2","@deepseek-ai/dsh-client-locale":"0.2.0-rc.2","@deepseek-ai/dsh-client-store":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-chat":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-conversation":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-settings":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-settings-general":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-theme":"0.2.0-rc.2","@deepseek-ai/dsh-command-compact":"0.2.0-rc.2","@deepseek-ai/dsh-command-goal":"0.2.0-rc.2","@deepseek-ai/dsh-commands":"0.2.0-rc.2","@deepseek-ai/dsh-compaction":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-basic":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-image-offload":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-tool-result-pruner":"0.2.0-rc.2","@deepseek-ai/dsh-credentials":"0.2.0-rc.2","@deepseek-ai/dsh-file-reference":"0.2.0-rc.2","@deepseek-ai/dsh-fs":"0.2.0-rc.2","@deepseek-ai/dsh-fs-observation-policy":"0.2.0-rc.2","@deepseek-ai/dsh-goal":"0.2.0-rc.2","@deepseek-ai/dsh-goal-round-driver":"0.2.0-rc.2","@deepseek-ai/dsh-home-paths":"0.2.0-rc.2","@deepseek-ai/dsh-host-directory-picker":"0.2.0-rc.2","@deepseek-ai/dsh-host-plugin-inventory":"0.2.0-rc.2","@deepseek-ai/dsh-invariants":"0.2.0-rc.2","@deepseek-ai/dsh-jobs":"0.2.0-rc.2","@deepseek-ai/dsh-jobs-local":"0.2.0-rc.2","@deepseek-ai/dsh-launch-environment":"0.2.0-rc.2","@deepseek-ai/dsh-llm":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek-api-key":"0.2.0-rc.2","@deepseek-ai/dsh-llm-retry":"0.2.0-rc.2","@deepseek-ai/dsh-message-feedback":"0.2.0-rc.2","@deepseek-ai/dsh-output-retention":"0.2.0-rc.2","@deepseek-ai/dsh-plan-mode":"0.2.0-rc.2","@deepseek-ai/dsh-ptc-runtime":"0.2.0-rc.2","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.0-rc.2","@deepseek-ai/dsh-sandbox":"0.2.0-rc.2","@deepseek-ai/dsh-schedule":"0.2.0-rc.2","@deepseek-ai/dsh-scope":"0.2.0-rc.2","@deepseek-ai/dsh-session":"0.2.0-rc.2","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.0-rc.2","@deepseek-ai/dsh-session-format":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-catalog":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.0-rc.2","@deepseek-ai/dsh-session-persistence":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection-cache":"0.2.0-rc.2","@deepseek-ai/dsh-session-stats":"0.2.0-rc.2","@deepseek-ai/dsh-session-query":"0.2.0-rc.2","@deepseek-ai/dsh-session-reference":"0.2.0-rc.2","@deepseek-ai/dsh-session-title":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-llm":"0.2.0-rc.2","@deepseek-ai/dsh-settings":"0.2.0-rc.2","@deepseek-ai/dsh-skill":"0.2.0-rc.2","@deepseek-ai/dsh-spill":"0.2.0-rc.2","@deepseek-ai/dsh-spill-policy":"0.2.0-rc.2","@deepseek-ai/dsh-storage":"0.2.0-rc.2","@deepseek-ai/dsh-storage-domain":"0.2.0-rc.2","@deepseek-ai/dsh-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-in-process-driver":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-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 By,NEe,PEe,F6=ce(()=>{"use strict";$Ee();By=oY.version,NEe=oY.dshEdge.upstreamVersion,PEe=`npx dsh-edge@${By.includes("-")?"next":"latest"} upgrade`});function Uxt(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 Bxt(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function vm(e){let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("MCP server URL must use http: or https: protocol.");let n=t.hostname.toLowerCase(),r=n.endsWith(".")?n.slice(0,-1):n,i=r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r;if(!(i==="localhost"||i==="127.0.0.1"||i==="::1")){for(let s of jxt)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(Bxt(i)){let s=Uxt(i),o=s??i;for(let c of Fxt)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 qxt)if(c.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function zxt(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function DEe(e,t,n){vm(e);let r=new C9(new URL(e),{requestInit:{headers:zxt(t),signal:n},fetch:zy}),i=new A9({name:"dsh-edge",version:By},{capabilities:{},jsonSchemaValidator:Wxt});return await i.connect(r),{client:i,close:a(async()=>{await i.close().catch(()=>{})},"close")}}async function MEe(e,t,n){let r=AbortSignal.timeout(Mo.probeTimeoutMs),i;try{i=await DEe(t,n,r)}catch(c){throw new Error(Uf(c instanceof Error?c.message:String(c)))}let{client:s,close:o}=i;try{let c=[],l=new Set,u=new Set,d;for(let h=0;h<Mo.maxCatalogPages;h++){let g=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let y of g.tools){if(c.length>=Mo.maxToolsPerServer)break;let v=IEe(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=CEe(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>=Mo.maxToolsPerServer||(d=g.nextCursor??void 0,d===void 0))break;if(u.has(d))throw new Error("Server repeated a tools/list continuation cursor");u.add(d)}let p=s.getServerVersion?.(),f=s.getInstructions?.();return{tools:c,serverInfo:p?{name:p.name,version:p.version}:void 0,instructions:typeof f=="string"&&f.length>0?f.slice(0,Mo.maxInstructionsLength):void 0}}finally{await o()}}async function M9(e,t,n,r,i,s){let o=s??Mo.callTimeoutMs,c=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),l;try{l=await DEe(e,r,c)}catch(u){throw new Error(Uf(u instanceof Error?u.message:String(u)))}try{let u=await l.client.callTool({name:t,arguments:n},void 0,{signal:c});return{content:u.content??[],structuredContent:u.structuredContent,isError:u.isError===!0}}catch(u){throw new Error(Uf(u instanceof Error?u.message:String(u)))}finally{await l.close()}}var jxt,Fxt,qxt,Wxt,zy,q6=ce(()=>{"use strict";Fke();vEe();TEe();D9();P9();F6();jxt=[".internal",".local",".localhost"],Fxt=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],qxt=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(Uxt,"extractMappedIPv4");a(Bxt,"isIpAddress");a(vm,"assertSafeUrl");a(zxt,"buildHeaders");Wxt=new N9,zy=a(async(e,t)=>{let n=await globalThis.fetch(e,{...t,redirect:"manual"});if(n.status>=300&&n.status<400)throw new Error(`MCP server returned HTTP ${String(n.status)} redirect; redirects are blocked for security.`);return n},"noRedirectFetch");a(DEe,"connectClient");a(MEe,"probe");a(M9,"callTool")});import{Buffer as Hxt}from"node:buffer";function Zxt(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Kxt.has(e.code)}function jEe(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Gxt.has(e.code)}function FEe(e,t,n){let r=Hxt.from(e,"base64");if(e.length===0&&t==="reject"||r.toString("base64")!==e)throw new dr(n==="INVALID_IMAGE_BASE64"?"Image upload is not canonical base64.":"File upload is not canonical base64.",n);return new Uint8Array(r)}function Yxt(e){return FEe(e,"reject","INVALID_IMAGE_BASE64")}function Jxt(e){return{data:Yxt(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function U6(e,t){return e.saveImages(t.map(Jxt))}async function Xxt(e,t){return e.saveFile({data:FEe(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function qEe(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 aY(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 LEe,Vxt,Gxt,Kxt,dr,cY,wm=ce(()=>{Jn();LEe=["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"],Vxt=[...LEe,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],Gxt=new Set(LEe),Kxt=new Set(Vxt),dr=class extends Error{static{a(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};a(Zxt,"isAttachmentError");a(jEe,"isImageAdmissionError");a(FEe,"decodeCanonicalBase64");a(Yxt,"decodeBase64");a(Jxt,"saveInput");a(U6,"admitEncodedImages");a(Xxt,"admitEncodedFile");a(qEe,"requestImageDimensions");a(aY,"longEdgeDimensions");cY=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 dr("Image batch exceeds the configured image-count limit.","TOO_MANY_IMAGES");if(e.reduce((i,s)=>i+s.data.byteLength,0)>n)throw new dr("Image batch exceeds the configured aggregate image-byte limit.","IMAGES_TOO_LARGE");for(let i of e)if(!r.includes(i.mediaType))throw new dr(`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 U6(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 Xxt(this,e)}isAttachmentError(e){return Zxt(e)}imageHostPath(e){}saveFile(e){return Promise.reject(new dr("The mounted attachment provider cannot store verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}saveFileStream(e){return Promise.reject(new dr("The mounted attachment provider cannot stream verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}async*readFileStream(e,t){t?.throwIfAborted(),await Promise.reject(new dr("The mounted attachment provider cannot read verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}fileHostPath(e){}readImageRequest(e,t,n){return n?.throwIfAborted(),Promise.reject(new dr("The mounted attachment provider cannot derive model-request images.","ATTACHMENT_PROJECTION_UNSUPPORTED"))}}});var j9={};pn(j9,{buildAuthorizationUrl:()=>a2t,discoverEndpoints:()=>s2t,exchangeCode:()=>c2t,isTokenExpired:()=>u2t,refreshToken:()=>l2t,registerClient:()=>o2t});function WEe(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 i2t(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 s2t(e){let t=AbortSignal.timeout(L9),n=new URL(e),r=n.pathname==="/"?"/.well-known/oauth-protected-resource":`/.well-known/oauth-protected-resource${n.pathname}`,i=new URL(r,n.origin);vm(i.href);let s=await zy(i.href,{signal:t});if(!s.ok)throw new Error(`PRM discovery failed: HTTP ${s.status}`);let c=(await s.json()).authorization_servers?.[0];if(typeof c!="string")throw new Error("No authorization server in PRM");let l=new URL(c),u=l.pathname==="/"?"/.well-known/oauth-authorization-server":`/.well-known/oauth-authorization-server${l.pathname}`,d=new URL(u,l.origin);vm(d.href);let p=await zy(d.href,{signal:t});if(!p.ok)throw new Error(`AS metadata failed: HTTP ${p.status}`);let f=await p.json();if(typeof f.authorization_endpoint!="string"||typeof f.token_endpoint!="string")throw new Error("Missing required endpoints in AS metadata");return{authorization:f.authorization_endpoint,token:f.token_endpoint,registration:f.registration_endpoint}}async function o2t(e,t,n){let r=AbortSignal.timeout(L9);vm(e);let i=await zy(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_name:n,redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}),signal:r});if(!i.ok)throw new Error(`DCR failed: HTTP ${i.status}`);let s=await i.json();if(typeof s.client_id!="string")throw new Error("DCR response missing client_id");return{clientId:s.client_id,clientSecret:s.client_secret}}async function a2t(e,t,n,r,i){let s=WEe(32),o=WEe(64),c=await i2t(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 c2t(e,t,n,r,i,s){let o=AbortSignal.timeout(L9),c=new URLSearchParams({grant_type:"authorization_code",code:n,redirect_uri:i,client_id:t.clientId,code_verifier:r});s!==void 0&&c.set("resource",s),t.clientSecret!==void 0&&c.set("client_secret",t.clientSecret),vm(e);let l=await zy(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:c.toString(),signal:o});if(!l.ok)throw new Error(`Token exchange failed: HTTP ${l.status}`);return HEe(await l.json())}async function l2t(e,t,n,r){let i=AbortSignal.timeout(L9),s=new URLSearchParams({grant_type:"refresh_token",refresh_token:n,client_id:t.clientId});r!==void 0&&s.set("resource",r),t.clientSecret!==void 0&&s.set("client_secret",t.clientSecret),vm(e);let o=await zy(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:s.toString(),signal:i});if(!o.ok)throw new Error(`Token refresh failed: HTTP ${o.status}`);return HEe(await o.json())}function HEe(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 u2t(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var L9,F9=ce(()=>{"use strict";q6();L9=1e4;a(WEe,"randomString");a(i2t,"sha256Base64Url");a(s2t,"discoverEndpoints");a(o2t,"registerClient");a(a2t,"buildAuthorizationUrl");a(c2t,"exchangeCode");a(l2t,"refreshToken");a(HEe,"parseTokenResponse");a(u2t,"isTokenExpired")});var Bn,QEe,vx=ce(()=>{Jn();mr();Bn=class extends Wr{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},QEe=class extends Et{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new Bn("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function V6(e){return Y9.test(e)}function J9(e){return e.invocation.modelInvocable}function bx(e){return e.invocation.userInvocable}function AY(e){let t=KSt(e);return[`<skill_content name="${ZSt(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 Oxt,Pxt,Dxt,D9=ce(()=>{"use strict";co();P9();Oxt=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a($xt,"globToRegExp");a(AEe,"evaluateMcpToolPolicy");a(Uf,"scrubMcpErrorMessage");a(IEe,"publicToolName");a(Nxt,"hashSuffix");a(CEe,"supportedOutputSchema");Pxt=new Set(["image/png","image/jpeg"]),Dxt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(Mxt,"isImageMediaType");a(REe,"decodeImageBlock");a(OEe,"containsImage");a(j6,"mapMcpResultToContentBlocks")});var oY,$Ee=ce(()=>{oY={name:"dsh-edge",version:"0.23.0",description:"Your DeepSeek Harness, anywhere \u2014 deploy a persistent personal coding agent to Cloudflare Workers in one command",author:"pawaca",license:"MIT",type:"module",bin:{"dsh-edge":"scripts/cli.mjs"},files:["dist","worker","scripts/*.d.mts","scripts/*.mjs","wrangler.jsonc","README.md","README.zh.md","LICENSE","THIRD_PARTY_NOTICES.md"],repository:{type:"git",url:"git+https://github.com/pawaca/dsh-edge.git",directory:"apps/dsh-edge"},homepage:"https://github.com/pawaca/dsh-edge#readme",bugs:{url:"https://github.com/pawaca/dsh-edge/issues"},keywords:["deepseek","deepseek-harness","ai-agents","byok","cloudflare-workers","durable-objects","self-hosted"],engines:{node:">=22.14.0"},publishConfig:{access:"public"},dshEdge:{upstreamVersion:"0.2.0-rc.2"},scripts:{"bundle:direct":"pnpm run web:build && pnpm --dir standalone run build:worker:direct && node standalone/scripts/promote.mjs direct","bundle:isolated":"pnpm run web:build && pnpm --dir standalone run build:worker:isolated && node standalone/scripts/promote.mjs isolated","bundle:workers":"pnpm --dir standalone run build && pnpm --dir standalone run verify && node standalone/scripts/promote.mjs all",dev:"pnpm run bundle:direct && node scripts/dev.mjs direct","dev:isolated":"pnpm run bundle:isolated && node scripts/dev.mjs isolated","dev:container":"pnpm run bundle:isolated && node scripts/dev.mjs container","dsh-edge":"node scripts/cli.mjs","example:install":"node examples/install-keyless.mjs","install:cloudflare":"pnpm run bundle:workers && node scripts/cli.mjs install","legal:write":"node scripts/legal-files.mjs write","pack:verify":"node scripts/verify-packed.mjs",prepack:"node scripts/legal-files.mjs verify && pnpm run bundle:workers","web:build":"pnpm --dir standalone run build:web && node standalone/scripts/promote.mjs web",test:"vitest run --root ../.. --project edge-runtime","test:integration":"pnpm run bundle:workers && node tests/run-session-integration.mjs","test:container":"pnpm run bundle:isolated && node tests/container.integration.mjs","test:snapshot":"vitest run --root ../.. --config apps/dsh-edge/vitest.snapshot.config.ts",typecheck:"tsc --noEmit"},dependencies:{"@clack/prompts":"1.7.0","compare-versions":"6.1.1",execa:"^10.0.1","jsonc-parser":"^3.3.1",wrangler:"4.129.0",yaml:"2.9.0"},devDependencies:{"@cfworker/json-schema":"^4.1.1","@cloudflare/computer":"0.3.1","@cloudflare/workers-types":"5.20260904.1","@deepseek-ai/cordis":"4.0.4","@deepseek-ai/cosmokit":"1.8.5","@deepseek-ai/dsh-agent":"0.2.0-rc.2","@deepseek-ai/dsh-agent-instructions":"0.2.0-rc.2","@deepseek-ai/dsh-agent-loop":"0.2.0-rc.2","@deepseek-ai/dsh-anonymous-user-id":"0.2.0-rc.2","@deepseek-ai/dsh-api-gateway":"0.2.0-rc.2","@deepseek-ai/dsh-api-job-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-remotes":"0.2.0-rc.2","@deepseek-ai/dsh-api-session-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-settings-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-workspace-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-workspace-files":"0.2.0-rc.2","@deepseek-ai/dsh-attachment":"0.2.0-rc.2","@deepseek-ai/dsh-brand":"0.2.0-rc.2","@deepseek-ai/dsh-client-locale":"0.2.0-rc.2","@deepseek-ai/dsh-client-store":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-chat":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-conversation":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-settings":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-settings-general":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-theme":"0.2.0-rc.2","@deepseek-ai/dsh-command-compact":"0.2.0-rc.2","@deepseek-ai/dsh-command-goal":"0.2.0-rc.2","@deepseek-ai/dsh-commands":"0.2.0-rc.2","@deepseek-ai/dsh-compaction":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-basic":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-image-offload":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-tool-result-pruner":"0.2.0-rc.2","@deepseek-ai/dsh-credentials":"0.2.0-rc.2","@deepseek-ai/dsh-file-reference":"0.2.0-rc.2","@deepseek-ai/dsh-fs":"0.2.0-rc.2","@deepseek-ai/dsh-fs-observation-policy":"0.2.0-rc.2","@deepseek-ai/dsh-goal":"0.2.0-rc.2","@deepseek-ai/dsh-goal-round-driver":"0.2.0-rc.2","@deepseek-ai/dsh-home-paths":"0.2.0-rc.2","@deepseek-ai/dsh-host-directory-picker":"0.2.0-rc.2","@deepseek-ai/dsh-host-plugin-inventory":"0.2.0-rc.2","@deepseek-ai/dsh-invariants":"0.2.0-rc.2","@deepseek-ai/dsh-jobs":"0.2.0-rc.2","@deepseek-ai/dsh-jobs-local":"0.2.0-rc.2","@deepseek-ai/dsh-launch-environment":"0.2.0-rc.2","@deepseek-ai/dsh-llm":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek-api-key":"0.2.0-rc.2","@deepseek-ai/dsh-llm-retry":"0.2.0-rc.2","@deepseek-ai/dsh-message-feedback":"0.2.0-rc.2","@deepseek-ai/dsh-output-retention":"0.2.0-rc.2","@deepseek-ai/dsh-plan-mode":"0.2.0-rc.2","@deepseek-ai/dsh-ptc-runtime":"0.2.0-rc.2","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.0-rc.2","@deepseek-ai/dsh-sandbox":"0.2.0-rc.2","@deepseek-ai/dsh-schedule":"0.2.0-rc.2","@deepseek-ai/dsh-scope":"0.2.0-rc.2","@deepseek-ai/dsh-session":"0.2.0-rc.2","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.0-rc.2","@deepseek-ai/dsh-session-format":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-catalog":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.0-rc.2","@deepseek-ai/dsh-session-persistence":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection-cache":"0.2.0-rc.2","@deepseek-ai/dsh-session-stats":"0.2.0-rc.2","@deepseek-ai/dsh-session-query":"0.2.0-rc.2","@deepseek-ai/dsh-session-reference":"0.2.0-rc.2","@deepseek-ai/dsh-session-title":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-llm":"0.2.0-rc.2","@deepseek-ai/dsh-settings":"0.2.0-rc.2","@deepseek-ai/dsh-skill":"0.2.0-rc.2","@deepseek-ai/dsh-spill":"0.2.0-rc.2","@deepseek-ai/dsh-spill-policy":"0.2.0-rc.2","@deepseek-ai/dsh-storage":"0.2.0-rc.2","@deepseek-ai/dsh-storage-domain":"0.2.0-rc.2","@deepseek-ai/dsh-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-in-process-driver":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-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 By,NEe,PEe,F6=ce(()=>{"use strict";$Ee();By=oY.version,NEe=oY.dshEdge.upstreamVersion,PEe=`npx dsh-edge@${By.includes("-")?"next":"latest"} upgrade`});function Uxt(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 Bxt(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function vm(e){let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("MCP server URL must use http: or https: protocol.");let n=t.hostname.toLowerCase(),r=n.endsWith(".")?n.slice(0,-1):n,i=r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r;if(!(i==="localhost"||i==="127.0.0.1"||i==="::1")){for(let s of jxt)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(Bxt(i)){let s=Uxt(i),o=s??i;for(let c of Fxt)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 qxt)if(c.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function zxt(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function DEe(e,t,n){vm(e);let r=new C9(new URL(e),{requestInit:{headers:zxt(t),signal:n},fetch:zy}),i=new A9({name:"dsh-edge",version:By},{capabilities:{},jsonSchemaValidator:Wxt});return await i.connect(r),{client:i,close:a(async()=>{await i.close().catch(()=>{})},"close")}}async function MEe(e,t,n){let r=AbortSignal.timeout(Mo.probeTimeoutMs),i;try{i=await DEe(t,n,r)}catch(c){throw new Error(Uf(c instanceof Error?c.message:String(c)))}let{client:s,close:o}=i;try{let c=[],l=new Set,u=new Set,d;for(let h=0;h<Mo.maxCatalogPages;h++){let g=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let y of g.tools){if(c.length>=Mo.maxToolsPerServer)break;let v=IEe(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=CEe(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>=Mo.maxToolsPerServer||(d=g.nextCursor??void 0,d===void 0))break;if(u.has(d))throw new Error("Server repeated a tools/list continuation cursor");u.add(d)}let p=s.getServerVersion?.(),f=s.getInstructions?.();return{tools:c,serverInfo:p?{name:p.name,version:p.version}:void 0,instructions:typeof f=="string"&&f.length>0?f.slice(0,Mo.maxInstructionsLength):void 0}}finally{await o()}}async function M9(e,t,n,r,i,s){let o=s??Mo.callTimeoutMs,c=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),l;try{l=await DEe(e,r,c)}catch(u){throw new Error(Uf(u instanceof Error?u.message:String(u)))}try{let u=await l.client.callTool({name:t,arguments:n},void 0,{signal:c});return{content:u.content??[],structuredContent:u.structuredContent,isError:u.isError===!0}}catch(u){throw new Error(Uf(u instanceof Error?u.message:String(u)))}finally{await l.close()}}var jxt,Fxt,qxt,Wxt,zy,q6=ce(()=>{"use strict";Fke();vEe();TEe();D9();P9();F6();jxt=[".internal",".local",".localhost"],Fxt=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],qxt=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(Uxt,"extractMappedIPv4");a(Bxt,"isIpAddress");a(vm,"assertSafeUrl");a(zxt,"buildHeaders");Wxt=new N9,zy=a(async(e,t)=>{let n=await globalThis.fetch(e,{...t,redirect:"manual"});if(n.status>=300&&n.status<400)throw new Error(`MCP server returned HTTP ${String(n.status)} redirect; redirects are blocked for security.`);return n},"noRedirectFetch");a(DEe,"connectClient");a(MEe,"probe");a(M9,"callTool")});import{Buffer as Hxt}from"node:buffer";function Zxt(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Kxt.has(e.code)}function jEe(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&Gxt.has(e.code)}function FEe(e,t,n){let r=Hxt.from(e,"base64");if(e.length===0&&t==="reject"||r.toString("base64")!==e)throw new dr(n==="INVALID_IMAGE_BASE64"?"Image upload is not canonical base64.":"File upload is not canonical base64.",n);return new Uint8Array(r)}function Yxt(e){return FEe(e,"reject","INVALID_IMAGE_BASE64")}function Jxt(e){return{data:Yxt(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function U6(e,t){return e.saveImages(t.map(Jxt))}async function Xxt(e,t){return e.saveFile({data:FEe(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function qEe(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 aY(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 LEe,Vxt,Gxt,Kxt,dr,cY,wm=ce(()=>{Jn();LEe=["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"],Vxt=[...LEe,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],Gxt=new Set(LEe),Kxt=new Set(Vxt),dr=class extends Error{static{a(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};a(Zxt,"isAttachmentError");a(jEe,"isImageAdmissionError");a(FEe,"decodeCanonicalBase64");a(Yxt,"decodeBase64");a(Jxt,"saveInput");a(U6,"admitEncodedImages");a(Xxt,"admitEncodedFile");a(qEe,"requestImageDimensions");a(aY,"longEdgeDimensions");cY=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 dr("Image batch exceeds the configured image-count limit.","TOO_MANY_IMAGES");if(e.reduce((i,s)=>i+s.data.byteLength,0)>n)throw new dr("Image batch exceeds the configured aggregate image-byte limit.","IMAGES_TOO_LARGE");for(let i of e)if(!r.includes(i.mediaType))throw new dr(`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 U6(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 Xxt(this,e)}isAttachmentError(e){return Zxt(e)}imageHostPath(e){}saveFile(e){return Promise.reject(new dr("The mounted attachment provider cannot store verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}saveFileStream(e){return Promise.reject(new dr("The mounted attachment provider cannot stream verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}async*readFileStream(e,t){t?.throwIfAborted(),await Promise.reject(new dr("The mounted attachment provider cannot read verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}fileHostPath(e){}readImageRequest(e,t,n){return n?.throwIfAborted(),Promise.reject(new dr("The mounted attachment provider cannot derive model-request images.","ATTACHMENT_PROJECTION_UNSUPPORTED"))}}});var j9={};pn(j9,{buildAuthorizationUrl:()=>a2t,discoverEndpoints:()=>s2t,exchangeCode:()=>c2t,isTokenExpired:()=>u2t,refreshToken:()=>l2t,registerClient:()=>o2t});function WEe(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 i2t(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 s2t(e){let t=AbortSignal.timeout(L9),n=new URL(e),r=n.pathname==="/"?"/.well-known/oauth-protected-resource":`/.well-known/oauth-protected-resource${n.pathname}`,i=new URL(r,n.origin);vm(i.href);let s=await zy(i.href,{signal:t});if(!s.ok)throw new Error(`PRM discovery failed: HTTP ${s.status}`);let c=(await s.json()).authorization_servers?.[0];if(typeof c!="string")throw new Error("No authorization server in PRM");let l=new URL(c),u=l.pathname==="/"?"/.well-known/oauth-authorization-server":`/.well-known/oauth-authorization-server${l.pathname}`,d=new URL(u,l.origin);vm(d.href);let p=await zy(d.href,{signal:t});if(!p.ok)throw new Error(`AS metadata failed: HTTP ${p.status}`);let f=await p.json();if(typeof f.authorization_endpoint!="string"||typeof f.token_endpoint!="string")throw new Error("Missing required endpoints in AS metadata");return{authorization:f.authorization_endpoint,token:f.token_endpoint,registration:f.registration_endpoint}}async function o2t(e,t,n){let r=AbortSignal.timeout(L9);vm(e);let i=await zy(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_name:n,redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}),signal:r});if(!i.ok)throw new Error(`DCR failed: HTTP ${i.status}`);let s=await i.json();if(typeof s.client_id!="string")throw new Error("DCR response missing client_id");return{clientId:s.client_id,clientSecret:s.client_secret}}async function a2t(e,t,n,r,i){let s=WEe(32),o=WEe(64),c=await i2t(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 c2t(e,t,n,r,i,s){let o=AbortSignal.timeout(L9),c=new URLSearchParams({grant_type:"authorization_code",code:n,redirect_uri:i,client_id:t.clientId,code_verifier:r});s!==void 0&&c.set("resource",s),t.clientSecret!==void 0&&c.set("client_secret",t.clientSecret),vm(e);let l=await zy(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:c.toString(),signal:o});if(!l.ok)throw new Error(`Token exchange failed: HTTP ${l.status}`);return HEe(await l.json())}async function l2t(e,t,n,r){let i=AbortSignal.timeout(L9),s=new URLSearchParams({grant_type:"refresh_token",refresh_token:n,client_id:t.clientId});r!==void 0&&s.set("resource",r),t.clientSecret!==void 0&&s.set("client_secret",t.clientSecret),vm(e);let o=await zy(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:s.toString(),signal:i});if(!o.ok)throw new Error(`Token refresh failed: HTTP ${o.status}`);return HEe(await o.json())}function HEe(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 u2t(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var L9,F9=ce(()=>{"use strict";q6();L9=1e4;a(WEe,"randomString");a(i2t,"sha256Base64Url");a(s2t,"discoverEndpoints");a(o2t,"registerClient");a(a2t,"buildAuthorizationUrl");a(c2t,"exchangeCode");a(l2t,"refreshToken");a(HEe,"parseTokenResponse");a(u2t,"isTokenExpired")});var Bn,QEe,vx=ce(()=>{Jn();mr();Bn=class extends Wr{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},QEe=class extends Et{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new Bn("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function V6(e){return Y9.test(e)}function J9(e){return e.invocation.modelInvocable}function bx(e){return e.invocation.userInvocable}function AY(e){let t=KSt(e);return[`<skill_content name="${ZSt(e.name)}">`,"<skill_resources>",...t,"</skill_resources>","","<skill_instructions>",e.content,"</skill_instructions>","</skill_content>"].join(`
|
|
156
156
|
`)}function KSt(e){let t=e.resourceBase;if(t===void 0)return[`Resources for this skill are managed by provider "${wx(e.provider)}".`,"Load referenced resources only as needed."];switch(t.kind){case"directory":return[`Base directory for this skill: ${wx(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: ${wx(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: ${wx(t.description)}`,"Load referenced resources only as needed."];default:return mi(t,"SkillResourceBase.kind")}}function ZSt(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<")}function wx(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function JSt(e,t){if(Array.isArray(e))return{candidates:e,complete:!0};if(e===null||typeof e!="object")throw b_e(t);let n=e;if(!Array.isArray(n.candidates)||typeof n.complete!="boolean")throw b_e(t);return n}function b_e(e){return new TypeError(`skill provider "${e}" list() must return an array or { candidates, complete } observation`)}function QSt(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:GSt,locator:e,...e.path!==void 0?{path:e.path}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}function ekt(e,t){if(typeof e.name!="string")throw new TypeError(`skill provider "${t}" returned a non-string skill name`);if(!Y9.test(e.name))throw new Error(`skill provider "${t}" returned invalid skill name "${e.name}"`);if(typeof e.description!="string")throw new TypeError(`skill provider "${t}" returned skill "${e.name}" with a non-string description`);if(e.description.length===0)throw new Error(`skill provider "${t}" returned skill "${e.name}" without a description`);if(IY(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 tkt(e){if(!Y9.test(e.name))throw new Error(`invalid skill name "${e.name}"`);if(e.description.length===0)throw new Error(`skill "${e.name}" requires a description`);IY(e.invocation,`runtime skill "${e.name}"`)}function nkt(e){let t=e.name,n=e.description,r=e.whenToUse,i=e.invocation,s=e.source,o=e.provider,c=e.content,l=e.path;if(typeof t!="string")throw new TypeError("loaded skill name must be a string");if(!Y9.test(t))throw new Error(`loaded skill has invalid name "${t}"`);if(typeof n!="string")throw new TypeError(`loaded skill "${t}" description must be a string`);if(n.length===0)throw new Error(`loaded skill "${t}" requires a description`);if(IY(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 rkt(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 IY(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 ikt(e,t){return E_e(e.name,t.name)}function E_e(e,t){return e<t?-1:e>t?1:0}function skt(e,t){return e.candidate.rank-t.candidate.rank||e.providerOrder-t.providerOrder||e.localOrder-t.localOrder}function okt(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 x_e(e,t){return t===void 0?e:(H6(t),new Promise((n,r)=>{let i=a(()=>{t.removeEventListener("abort",s)},"cleanup"),s=a(()=>{i(),r(Z9(t.reason))},"onAbort");t.addEventListener("abort",s,{once:!0}),e.then(o=>{i(),n(o)},o=>{i(),r(Z9(o))})}))}function H6(e){if(e?.aborted===!0)throw Z9(e.reason)}function Z9(e){try{if(e instanceof Error)return e}catch{}return new Error(K9(e))}function K9(e){try{return String(e)}catch{return"[unrenderable thrown value]"}}var Y9,w_e,VSt,G9,GSt,S_e,YSt,k_e,XSt,Hy=ce(()=>{Jn();es();Yc();fn();Y9=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,w_e=128,VSt=2,G9="runtime",GSt=250,S_e=600;a(V6,"isSkillName");a(J9,"isModelInvocable");a(bx,"isUserInvocable");a(AY,"renderSkillContent");a(KSt,"renderResourceHint");a(ZSt,"escapeAttr");a(wx,"escapeText");YSt=class{static{a(this,"SkillLayer")}providers;runtime=new Map;constructor(e){this.providers=new kf(t=>new Error(e===void 0?`a skill provider named "${t}" is already registered`:`a skill provider named "${t}" is already registered in this scope`))}isEmpty(){return this.providers.isEmpty()&&this.runtime.size===0}},k_e=class extends Et{static{a(this,"SkillRegistry")}static Config=q.object({collectCacheMaxEntries:q.number().default(w_e)});collectCacheMaxEntries;layers=new Ef(e=>new YSt(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??w_e,okt("collectCacheMaxEntries",this.collectCacheMaxEntries)}registerProvider(e){let t=new AbortController,n,r,i={signal:t.signal,invalidate:a(()=>{let s=n;s!==void 0&&s.layer.providers.get(s.name)?.provider===r&&this.invalidateCache()},"invalidate")};try{r=e(i);let s=r.name;if(s===G9)throw new Error(`"${G9}" is reserved for runtime skill registrations`);let o=this.nextProviderOrder;return this.nextProviderOrder+=1,this.layers.effect(this.ctx,c=>{let l=c.providers.insert(s,{provider:r,order:o});return n={layer:c,name:s},()=>{n=void 0,l(),t.abort(new Error(`skill provider "${s}" disposed`))}},{label:"skills.registerProvider()"})}catch(s){throw t.abort(s),s}}register(e){tkt(e);let t=Zc(this.ctx),n=t===void 0?this.layers.global:this.layers.peek(t);if(n!==void 0&&n.runtime.has(e.name))return this.ctx.logger.warn(`runtime skill "${e.name}" ignored because it is already registered`),()=>{};let r={...e,invocation:e.invocation??{modelInvocable:!0,userInvocable:!0},provider:e.provider??G9};return this.layers.effect(this.ctx,i=>(i.runtime.set(r.name,r),()=>{i.runtime.delete(r.name)}),{label:"skills.register()"})}async list(e={}){return(await this.snapshot(e)).skills}async snapshot(e={}){let t=await this.collect(e);return{skills:[...t.entries.values()].map(n=>rkt(n.candidate)).sort(ikt),complete:t.cacheable}}async get(e,t={}){if(!V6(e))return;let n=await this.collect(t);H6(t.signal);let r=n.entries.get(e);if(r===void 0)return;let i=await x_e(r.provider.get(r.candidate,t),t.signal);if(i!==void 0){if(nkt(i),i.name!==r.candidate.name){this.invalidateEntry(r);return}return i}}async collect(e){H6(e.signal);let t=1;for(;;){let n=this.revision,r=this.collectCacheKey(e.cwd,mE(e.scope),n),i=this.collectCache.get(r);if(i!==void 0)return{entries:i,cacheable:!0};let s=await this.collectFresh(e);if(H6(e.signal),n!==this.revision){if(t<VSt){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(skt);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){H6(t.signal);let n=[],r=!0,i=0;for(let s of[...e.runtime.values()].sort((o,c)=>E_e(o.name,c.name)))n.push({candidate:QSt(s),provider:XSt,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 x_e(s.list(t),t.signal)}catch(d){if(t.signal?.aborted===!0)throw Z9(t.signal.reason);r=!1,this.ctx.logger.warn(`skill provider "${s.name}" skipped: ${K9(d)}`)}if(l===void 0)continue;let u=JSt(l,s.name);u.complete||(r=!1);for(let d of u.candidates)ekt(d,s.name),n.push({candidate:d,provider:s,providerOrder:o,localOrder:c,layer:e}),c+=1}return{entries:n,cacheable:r}}invalidateCache(){this.revision+=1,this.collectCache.clear(),this.notifyChange()}invalidateEntry(e){e.layer.providers.get(e.provider.name)?.provider===e.provider&&this.invalidateCache()}scopeId(e){let t=this.scopeIds.get(e);return t===void 0&&(t=this.nextScopeId,this.nextScopeId+=1,this.scopeIds.set(e,t)),t}collectCacheKey(e,t,n){return JSON.stringify({cwd:e,scopes:t.map(r=>this.scopeId(r)),revision:n})}notifyChange(){for(let e of this.ctx.events.dispatch("emit",["skills/change"]))try{let t=e();Promise.resolve(t).catch(n=>{this.ctx.logger.warn(`skills/change listener rejected: ${K9(n)}`)})}catch(t){this.ctx.logger.warn(`skills/change listener threw: ${K9(t)}`)}}};a(JSt,"normalizeProviderObservation");a(b_e,"invalidProviderObservation");XSt={name:G9,list(){return Promise.resolve([])},get(e){return Promise.resolve(e.locator)}};a(QSt,"runtimeCandidate");a(ekt,"validateCandidate");a(tkt,"validateRuntimeSkill");a(nkt,"validateDefinition");a(rkt,"toSummary");a(IY,"validateInvocation");a(ikt,"compareSkillSummary");a(E_e,"compareCodePoints");a(skt,"compareIndexedCandidates");a(okt,"assertPositiveInteger");a(x_e,"waitWithAbort");a(H6,"throwIfAborted");a(Z9,"toError");a(K9,"errorMessage")});var md,kx=ce(()=>{md=class{static{a(this,"Deque")}buffer=new Array(16);head=0;count=0;get size(){return this.count}pushBack(e){this.ensureCapacity();let t=this.head+this.count;this.buffer[t<this.buffer.length?t:t-this.buffer.length]=e,this.count+=1}pushFront(e){this.ensureCapacity(),this.head=this.head===0?this.buffer.length-1:this.head-1,this.buffer[this.head]=e,this.count+=1}popFront(){if(this.count===0)return;let e=this.buffer[this.head];return this.buffer[this.head]=void 0,this.head+=1,this.head===this.buffer.length&&(this.head=0),this.count-=1,this.compact(),e}clear(){this.buffer=new Array(16),this.head=0,this.count=0}ensureCapacity(){this.count<this.buffer.length||this.resize(this.buffer.length*2)}compact(){if(this.count===0){this.head=0;return}this.buffer.length>16&&this.count<=this.buffer.length/4&&this.resize(Math.max(16,this.buffer.length/2))}resize(e){let t=new Array(e),n=this.head;for(let r=0;r<this.count;r+=1)t[r]=this.buffer[n],n+=1,n===this.buffer.length&&(n=0);this.buffer=t,this.head=0}}});var xm,H6e,hJ=ce(()=>{Jn();xm=class extends Error{static{a(this,"DirectoryPickerError")}code;path;constructor(e,t,n){super(n),this.code=e,this.path=t,this.name="DirectoryPickerError"}},H6e=class extends Et{static{a(this,"DirectoryPicker")}constructor(e){super(e,"directoryPicker")}}});var x3e=be((mzn,S5)=>{var b3e=b3e||function(e){return Buffer.from(e).toString("base64")};function eAt(e){var t=this,n=Math.round,r=Math.floor,i=new Array(64),s=new Array(64),o=new Array(64),c=new Array(64),l,u,d,p,f=new Array(65535),h=new Array(65535),g=new Array(64),y=new Array(64),v=[],w=0,b=7,S=new Array(64),k=new Array(64),E=new Array(64),_=new Array(256),T=new Array(2048),P,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 M(){l=N(j,$),u=N(I,U),d=N(W,J),p=N(C,R)}a(M,"initHuffmanTbl");function G(){for(var oe=1,Le=2,Ee=1;Ee<=15;Ee++){for(var ut=oe;ut<Le;ut++)h[32767+ut]=Ee,f[32767+ut]=[],f[32767+ut][1]=Ee,f[32767+ut][0]=ut;for(var ze=-(Le-1);ze<=-oe;ze++)h[32767+ze]=Ee,f[32767+ze]=[],f[32767+ze][1]=Ee,f[32767+ze][0]=Le-1+ze;oe<<=1,Le<<=1}}a(G,"initCategoryNumber");function X(){for(var oe=0;oe<256;oe++)T[oe]=19595*oe,T[oe+256>>0]=38470*oe,T[oe+512>>0]=7471*oe+32768,T[oe+768>>0]=-11059*oe,T[oe+1024>>0]=-21709*oe,T[oe+1280>>0]=32768*oe+8421375,T[oe+1536>>0]=-27439*oe,T[oe+1792>>0]=-5329*oe}a(X,"initRGBYUVTable");function Q(oe){for(var Le=oe[0],Ee=oe[1]-1;Ee>=0;)Le&1<<Ee&&(w|=1<<b),Ee--,b--,b<0&&(w==255?(z(255),z(0)):z(w),b=7,w=0)}a(Q,"writeBits");function z(oe){v.push(oe)}a(z,"writeByte");function ne(oe){z(oe>>8&255),z(oe&255)}a(ne,"writeWord");function ge(oe,Le){var Ee,ut,ze,je,wt,st,Ke,yt,Oe=0,_t,Gt=8,ht=64;for(_t=0;_t<Gt;++_t){Ee=oe[Oe],ut=oe[Oe+1],ze=oe[Oe+2],je=oe[Oe+3],wt=oe[Oe+4],st=oe[Oe+5],Ke=oe[Oe+6],yt=oe[Oe+7];var bn=Ee+yt,Vt=Ee-yt,Ut=ut+Ke,ae=ut-Ke,Pe=ze+st,Ge=ze-st,ct=je+wt,$t=je-wt,Xe=bn+ct,cn=bn-ct,rn=Ut+Pe,xn=Ut-Pe;oe[Oe]=Xe+rn,oe[Oe+4]=Xe-rn;var jt=(xn+cn)*.707106781;oe[Oe+2]=cn+jt,oe[Oe+6]=cn-jt,Xe=$t+Ge,rn=Ge+ae,xn=ae+Vt;var jr=(Xe-xn)*.382683433,Br=.5411961*Xe+jr,gs=1.306562965*xn+jr,Ni=rn*.707106781,fr=Vt+Ni,ys=Vt-Ni;oe[Oe+5]=ys+Br,oe[Oe+3]=ys-Br,oe[Oe+1]=fr+gs,oe[Oe+7]=fr-gs,Oe+=8}for(Oe=0,_t=0;_t<Gt;++_t){Ee=oe[Oe],ut=oe[Oe+8],ze=oe[Oe+16],je=oe[Oe+24],wt=oe[Oe+32],st=oe[Oe+40],Ke=oe[Oe+48],yt=oe[Oe+56];var Hs=Ee+yt,fo=Ee-yt,Co=ut+Ke,Bt=ut-Ke,Fn=ze+st,Ro=ze-st,Ca=je+wt,Ko=je-wt,Zo=Hs+Ca,ia=Hs-Ca,Ra=Co+Fn,rc=Co-Fn;oe[Oe]=Zo+Ra,oe[Oe+32]=Zo-Ra;var ru=(rc+ia)*.707106781;oe[Oe+16]=ia+ru,oe[Oe+48]=ia-ru,Zo=Ko+Ro,Ra=Ro+Bt,rc=Bt+fo;var dl=(Zo-rc)*.382683433,zd=.5411961*Zo+dl,Wd=1.306562965*rc+dl,Hd=Ra*.707106781,Vd=fo+Hd,$h=fo-Hd;oe[Oe+40]=$h+zd,oe[Oe+24]=$h-zd,oe[Oe+8]=Vd+Wd,oe[Oe+56]=Vd-Wd,Oe++}var sf;for(_t=0;_t<ht;++_t)sf=oe[_t]*Le[_t],g[_t]=sf>0?sf+.5|0:sf-.5|0;return g}a(ge,"fDCTQuant");function we(){ne(65504),ne(16),z(74),z(70),z(73),z(70),z(0),z(1),z(1),z(0),ne(1),ne(1),z(0),z(0)}a(we,"writeAPP0");function le(oe){if(oe){ne(65505),oe[0]===69&&oe[1]===120&&oe[2]===105&&oe[3]===102?ne(oe.length+2):(ne(oe.length+5+2),z(69),z(120),z(105),z(102),z(0));for(var Le=0;Le<oe.length;Le++)z(oe[Le])}}a(le,"writeAPP1");function Se(oe,Le){ne(65472),ne(17),z(8),ne(Le),ne(oe),z(3),z(1),z(17),z(0),z(2),z(17),z(1),z(3),z(17),z(1)}a(Se,"writeSOF0");function _e(){ne(65499),ne(132),z(0);for(var oe=0;oe<64;oe++)z(i[oe]);z(1);for(var Le=0;Le<64;Le++)z(s[Le])}a(_e,"writeDQT");function ue(){ne(65476),ne(418),z(0);for(var oe=0;oe<16;oe++)z(j[oe+1]);for(var Le=0;Le<=11;Le++)z($[Le]);z(16);for(var Ee=0;Ee<16;Ee++)z(W[Ee+1]);for(var ut=0;ut<=161;ut++)z(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[h[st]]),Q(f[st]));for(var bn=63;bn>0&&y[bn]==0;bn--);if(bn==0)return Q(je),Ee;for(var Vt=1,Ut;Vt<=bn;){for(var ae=Vt;y[Vt]==0&&Vt<=bn;++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)+h[st]]),Q(f[st]),Vt++}return bn!=yt&&Q(je),Ee}a(Ve,"processDU");function it(){for(var oe=String.fromCharCode,Le=0;Le<256;Le++)_[Le]=oe(Le)}a(it,"initCharLookupTable"),this.encode=function(oe,Le){var Ee=new Date().getTime();Le&&Ce(Le),v=new Array,w=0,b=7,ne(65496),we(),de(oe.comments),le(oe.exifBuffer),_e(),Se(oe.width,oe.height),ue(),ot();var ut=0,ze=0,je=0;w=0,b=7,this.encode.displayName="_encode_";for(var wt=oe.data,st=oe.width,Ke=oe.height,yt=st*4,Oe=st*3,_t,Gt=0,ht,bn,Vt,Ut,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++],bn=wt[ae++],Vt=wt[ae++],S[ct]=(T[ht]+T[bn+256>>0]+T[Vt+512>>0]>>16)-128,k[ct]=(T[ht+768>>0]+T[bn+1024>>0]+T[Vt+1280>>0]>>16)-128,E[ct]=(T[ht+1280>>0]+T[bn+1536>>0]+T[Vt+1792>>0]>>16)-128;ut=Ve(S,o,ut,l,d),ze=Ve(k,c,ze,u,p),je=Ve(E,c,je,u,p),_t+=32}Gt+=8}if(b>=0){var $t=[];$t[1]=b+1,$t[0]=(1<<b+1)-1,Q($t)}if(ne(65497),typeof S5>"u")return new Uint8Array(v);return Buffer.from(v);var Xe,cn};function Ce(oe){if(oe<=0&&(oe=1),oe>100&&(oe=100),P!=oe){var Le=0;oe<50?Le=Math.floor(5e3/oe):Le=Math.floor(200-oe*2),O(Le),P=oe}}a(Ce,"setQuality");function ke(){var oe=new Date().getTime();e||(e=50),it(),M(),G(),X(),Ce(e);var Le=new Date().getTime()-oe}a(ke,"init"),ke()}a(eAt,"JPEGEncoder");typeof S5<"u"?S5.exports=w3e:typeof window<"u"&&(window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=w3e);function w3e(e,t){typeof t>"u"&&(t=50);var n=new eAt(t),r=n.encode(e,t);return{data:r,width:e.width,height:e.height}}a(w3e,"encode")});var k3e=be((yzn,BX)=>{var UX=a((function(){"use strict";var t=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),n=4017,r=799,i=3406,s=2276,o=1567,c=3784,l=5793,u=2896;function d(){}a(d,"constructor");function p(b,S){for(var k=0,E=[],_,T,P=16;P>0&&!b[P-1];)P--;E.push({children:[],index:0});var D=E[0],j;for(_=0;_<P;_++){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<P&&(E.push(j={children:[],index:0}),D.children[D.index]=j.children,D=j)}return E[0].children}a(p,"buildHuffmanTable");function f(b,S,k,E,_,T,P,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,M=0,G=0;function X(){if(G>0)return G--,M>>G&1;if(M=b[S++],M==255){var Oe=b[S++];if(Oe)throw new Error("unexpected marker: "+(M<<8|Oe).toString(16))}return G=7,M>>>7}a(X,"readBit");function Q(Oe){for(var _t=Oe,Gt;(Gt=X())!==null;){if(_t=_t[Gt],typeof _t=="number")return _t;if(typeof _t!="object")throw new Error("invalid huffman sequence")}return null}a(Q,"decodeHuffman");function z(Oe){for(var _t=0;Oe>0;){var Gt=X();if(Gt===null)return;_t=_t<<1|Gt,Oe--}return _t}a(z,"receive");function ne(Oe){var _t=z(Oe);return _t>=1<<Oe-1?_t:_t+(-1<<Oe)+1}a(ne,"receiveAndExtend");function ge(Oe,_t){var Gt=Q(Oe.huffmanTableDC),ht=Gt===0?0:ne(Gt);_t[0]=Oe.pred+=ht;for(var bn=1;bn<64;){var Vt=Q(Oe.huffmanTableAC),Ut=Vt&15,ae=Vt>>4;if(Ut===0){if(ae<15)break;bn+=16;continue}bn+=ae;var Pe=t[bn];_t[Pe]=ne(Ut),bn++}}a(ge,"decodeBaseline");function we(Oe,_t){var Gt=Q(Oe.huffmanTableDC),ht=Gt===0?0:ne(Gt)<<j;_t[0]=Oe.pred+=ht}a(we,"decodeDCFirst");function le(Oe,_t){_t[0]|=X()<<j}a(le,"decodeDCSuccessive");var Se=0;function _e(Oe,_t){if(Se>0){Se--;return}for(var Gt=T,ht=P;Gt<=ht;){var bn=Q(Oe.huffmanTableAC),Vt=bn&15,Ut=bn>>4;if(Vt===0){if(Ut<15){Se=z(Ut)+(1<<Ut)-1;break}Gt+=16;continue}Gt+=Ut;var 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=P,bn=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,bn=ae>>4;if(Pe===0)bn<15?(Se=z(bn)+(1<<bn),ue=4):(bn=16,ue=1);else{if(Pe!==1)throw new Error("invalid ACn encoding");de=ne(Pe),ue=bn?2:3}continue;case 1:case 2:_t[Vt]?_t[Vt]+=(X()<<j)*Ut:(bn--,bn===0&&(ue=ue==2?3:0));break;case 3:_t[Vt]?_t[Vt]+=(X()<<j)*Ut:(_t[Vt]=de<<j,ue=0);break;case 4:_t[Vt]&&(_t[Vt]+=(X()<<j)*Ut);break}Gt++}ue===4&&(Se--,Se===0&&(ue=0))}a(ot,"decodeACSuccessive");function Ve(Oe,_t,Gt,ht,bn){var Vt=Gt/U|0,Ut=Gt%U,ae=Vt*Oe.v+ht,Pe=Ut*Oe.h+bn;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,bn=Gt%Oe.blocksPerLine;Oe.blocks[ht]===void 0&&$.tolerantDecoding||_t(Oe,Oe.blocks[ht][bn])}a(it,"decodeBlock");var Ce=E.length,ke,oe,Le,Ee,ut,ze;C?T===0?ze=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(f,"decodeScan");function h(b,S){var k=[],E=S.blocksPerLine,_=S.blocksPerColumn,T=E<<3,P=new Int32Array(64),D=new Uint8Array(64);function j(N,M,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);M[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,P);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(h,"buildComponentData");function g(b){return b<0?0:b>255?255:b}a(g,"clampTo8bit"),d.prototype={load:a(function(S){var k=new XMLHttpRequest;k.open("GET",S,!0),k.responseType="arraybuffer",k.onload=(function(){var E=new Uint8Array(k.response||k.mozResponseArrayBuffer);this.parse(E),this.onload&&this.onload()}).bind(this),k.send(null)},"load"),parse:a(function(S){var k=this.opts.maxResolutionInMP*1e3*1e3,E=0,_=S.length;function T(){var ae=S[E]<<8|S[E+1];return E+=2,ae}a(T,"readUint16");function P(){var ae=T(),Pe=S.subarray(E,E+ae-2);return E+=Pe.length,Pe}a(P,"readDataBlock");function D(ae){var Pe=1,Ge=1,ct,$t;for($t in ae.components)ae.components.hasOwnProperty($t)&&(ct=ae.components[$t],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($t in ae.components)if(ae.components.hasOwnProperty($t)){ct=ae.components[$t];var rn=Math.ceil(Math.ceil(ae.samplesPerLine/8)*ct.h/Pe),xn=Math.ceil(Math.ceil(ae.scanLines/8)*ct.v/Ge),jt=Xe*ct.h,jr=cn*ct.v,Br=jr*jt,gs=[];w(Br*256);for(var Ni=0;Ni<jr;Ni++){for(var fr=[],ys=0;ys<jt;ys++)fr.push(new Int32Array(64));gs.push(fr)}ct.blocksPerLine=rn,ct.blocksPerColumn=xn,ct.blocks=gs}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(),M=-1;if(this.comments=[],N!=65496)throw new Error("SOI not found");for(N=T();N!=65497;){var G,X,Q;switch(N){case 65280:break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var z=P();if(N===65534){var ne=String.fromCharCode.apply(null,z);this.comments.push(ne)}N===65504&&z[0]===74&&z[1]===70&&z[2]===73&&z[3]===70&&z[4]===0&&(j={version:{major:z[5],minor:z[6]},densityUnits:z[7],xDensity:z[8]<<8|z[9],yDensity:z[10]<<8|z[11],thumbWidth:z[12],thumbHeight:z[13],thumbData:z.subarray(14,14+3*z[12]*z[13])}),N===65505&&z[0]===69&&z[1]===120&&z[2]===105&&z[3]===102&&z[4]===0&&(this.exifBuffer=z.subarray(5,z.length)),N===65518&&z[0]===65&&z[1]===100&&z[2]===111&&z[3]===98&&z[4]===101&&z[5]===0&&($={version:z[6],flags0:z[7]<<8|z[8],flags1:z[9]<<8|z[10],transformCode:z[11]});break;case 65499:for(var ge=T(),we=ge+E-2;E<we;){var le=S[E++];w(256);var Se=new Int32Array(64);if(le>>4===0)for(X=0;X<64;X++){var _e=t[X];Se[_e]=S[E++]}else if(le>>4===1)for(X=0;X<64;X++){var _e=t[X];Se[_e]=T()}else throw new Error("DQT: invalid table spec");U[le&15]=Se}break;case 65472:case 65473:case 65474:T(),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++],bn=S[E++],Vt=f(S,E,J,yt,I,Gt,ht,bn>>4,bn&15,this.opts);E+=Vt;break;case 65535:S[E]!==255&&E--;break;default:if(S[E-3]==255&&S[E-2]>=192&&S[E-2]<=254){E-=3;break}else if(N===224||N==225){if(M!==-1)throw new Error(`first unknown JPEG marker at offset ${M.toString(16)}, second unknown JPEG marker ${N.toString(16)} at offset ${(E-1).toString(16)}`);M=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:h(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,P,D,j,$,W,J,I,U,C,R=0,O,N,M,G,X,Q,z,ne,ge,we,le,Se=S*k*this.components.length;w(Se);var _e=new Uint8Array(Se);switch(this.components.length){case 1:for(T=this.components[0],C=0;C<k;C++)for($=T.lines[0|C*T.scaleY*_],U=0;U<S;U++)O=$[0|U*T.scaleX*E],_e[R++]=O;break;case 2:for(T=this.components[0],P=this.components[1],C=0;C<k;C++)for($=T.lines[0|C*T.scaleY*_],W=P.lines[0|C*P.scaleY*_],U=0;U<S;U++)O=$[0|U*T.scaleX*E],_e[R++]=O,O=W[0|U*P.scaleX*E],_e[R++]=O;break;case 3:for(le=!0,this.adobe&&this.adobe.transformCode?le=!0:typeof this.opts.colorTransform<"u"&&(le=!!this.opts.colorTransform),T=this.components[0],P=this.components[1],D=this.components[2],C=0;C<k;C++)for($=T.lines[0|C*T.scaleY*_],W=P.lines[0|C*P.scaleY*_],J=D.lines[0|C*D.scaleY*_],U=0;U<S;U++)le?(O=$[0|U*T.scaleX*E],N=W[0|U*P.scaleX*E],M=J[0|U*D.scaleX*E],ne=g(O+1.402*(M-128)),ge=g(O-.3441363*(N-128)-.71413636*(M-128)),we=g(O+1.772*(N-128))):(ne=$[0|U*T.scaleX*E],ge=W[0|U*P.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],P=this.components[1],D=this.components[2],j=this.components[3],C=0;C<k;C++)for($=T.lines[0|C*T.scaleY*_],W=P.lines[0|C*P.scaleY*_],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*P.scaleX*E],M=J[0|U*D.scaleX*E],G=I[0|U*j.scaleX*E],X=255-g(O+1.402*(M-128)),Q=255-g(O-.3441363*(N-128)-.71413636*(M-128)),z=255-g(O+1.772*(N-128))):(X=$[0|U*T.scaleX*E],Q=W[0|U*P.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,P=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=P[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=P[D++],O=P[D++],N=P[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=P[D++],C=P[D++],J=P[D++],I=P[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 BX<"u"?BX.exports=S3e:typeof window<"u"&&(window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=S3e);function S3e(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 UX;s.opts=r,UX.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),s.parse(i);var o=r.formatAsRGBA?4:3,c=s.width*s.height*o;try{UX.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(S3e,"decode")});var _3e=be((wzn,E3e)=>{var tAt=x3e(),nAt=k3e();E3e.exports={encode:tAt,decode:nAt}});function o7e(e,t){let n=0,r=0,s=a(o=>{let c;for(let[l,u]of o.entries()){let d=u;if(u.type==="image"){if(n===t[r]){if(u.offloaded===!0)throw new Error(`image/offload: image index ${n} is already offloaded`);d={...u,offloaded:!0},r+=1}n+=1}d!==u&&(c??=o.slice(0,l)),c?.push(d)}return c??o},"visit")(e.content);if(r!==t.length)throw new Error(`image/offload: image index ${t[r]} does not exist`);return gn({...e,content:s})}var a7e=ce(()=>{es();a(o7e,"offloadMessageImages")});function c7e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function l7e(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0&&!Object.is(e,-0)}var B5,qQ=ce(()=>{a7e();a(c7e,"isRecord");a(l7e,"isIndex");B5={type:"image/offload",project(e,t){let n=e.data;if(!c7e(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(!c7e(s)||Object.keys(s).length!==2||!l7e(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(!l7e(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,o7e(u,s.imageIndexes))}return r}}});var rO,IIe=ce(()=>{qQ();rO=[B5]});async function DIe(e,t,n){let r=n===void 0?void 0:{signal:n},i=await e.open(t,"read",r),s;try{s=await i.read(0,void 0,r)}catch(c){try{await i.close()}catch{}throw c}await i.close();let{events:o}=s;return{eventState:s.eventState,header:i.header,inheritedEventCount:i.inheritedEventCount,events:[...o,...eI(o)]}}function See(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 Dr(`session source headers conflict for session "${e.id}"`,"SESSION_QUERY_SOURCE_CONFLICT")}function iO(e,t,n,r){try{r?.throwIfAborted();let i=n(t);return r?.throwIfAborted(),{sessionId:e,status:"fulfilled",value:i}}catch(i){return r?.aborted&&r.throwIfAborted(),{sessionId:e,status:"rejected",reason:i}}}function kee(e){return{header:e.header,events:e.snapshotEvents()}}function sO(e,t){return e.map(n=>t.get(n))}async function Eee(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 Dr(`session persistence listing failed: ${Aee(n)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:n})}}async function CIe(e,t,n){try{return await DIe(e,t,n)}catch(r){throw n?.aborted&&n.throwIfAborted(),r instanceof Error&&r.name==="SessionPersistenceCorruptionError"?new Dr(`stored session "${t}" is corrupt: ${Aee(r)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:r}):new Dr(`failed to read stored session "${t}": ${Aee(r)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:r})}}function RIe(e){return{header:structuredClone(e.header),inheritedEventCount:e.inheritedEventCount,events:e.snapshotEvents().map(t=>structuredClone(t))}}function l9t(e,t){return t.header.createdAt-e.header.createdAt||e.header.id.localeCompare(t.header.id)}function oO(e){return new Dr(`session "${e}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND")}function Aee(e){return e instanceof Error?e.message:"unknown error"}function r4(e){if(e?.aborted===!0)throw new Dr("session observation was aborted","SESSION_QUERY_ABORTED",{cause:e.reason})}function OIe(e,t){return $Ie(t,"SessionPersistenceNotFoundError")?Iee(e,t):$Ie(t,"SessionPersistenceCorruptionError")?new Dr(`stored session "${e}" is corrupt: ${t.message}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:t}):new Dr(`failed to observe session "${e}": ${aO(t)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:t})}function Iee(e,t){return new Dr(`session "${e}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND",t===void 0?void 0:{cause:t})}function aO(e){return e instanceof Error?e.message:"unknown error"}function $Ie(e,t){return e instanceof Error&&e.name===t}function d9t(e){switch(e.type){case"user/message":return _ee(e.data.content);case"assistant/message":return _ee(e.data.message.content);case"tool/call":return i4([e.data.name,e.data.arguments]);case"tool/result":return i4([_ee(e.data.message.content),e.data.error?.name??"",e.data.error?.code??""]);case"todo/write":return i4(e.data.todos.flatMap(t=>[t.status,t.content]));case"turn/end":return p9t(e.data.reason);case"turn/start":case"step/start":case"step/end":case"assistant/attempt":case"request/header":return"";default:return""}}function p9t(e){switch(e.kind){case"error":return i4(["error",e.error.message]);case"aborted":return"aborted";case"max-tokens":case"interrupted":return e.kind;case"completed":return"";default:return""}}function _ee(e){return i4(e.flatMap(f9t))}function f9t(e){switch(e.type){case"text":return[e.text];case"reasoning":return[];case"tool-call":return[e.name,e.arguments];default:return[]}}function i4(e){return e.map(t=>t.trim()).filter(Boolean).join(`
|
|
157
157
|
`)}function Ree(e,t){let n=h9t(t),r=[];for(let i of t){let s=d9t(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 h9t(e){let t;try{t=oF(e,rO)}catch(r){throw new Dr(`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 Oee(e,t=[]){let n=t.map(g9t);return e.filter(r=>n.every(i=>i(r)))}function dO(e,t=[]){let n=t.map(y9t);return e.filter(r=>n.every(i=>i(r)))}function $ee(e){return MIe(e),e.map(t=>{switch(t.kind){case"id":return{kind:t.kind,values:lO(t.kind,t.values)};case"cwd":return{kind:t.kind,values:NIe(t.kind,t.values)};case"created-at":return LIe(t.kind,t);case"parent":return{kind:t.kind,values:NIe(t.kind,t.values)};case"availability":{let n=lO(t.kind,t.values);return hO(t.kind,n,["live","persisted"]),{kind:t.kind,values:n}}default:return fO(t)}})}function pO(e){return MIe(e),e.map(t=>{switch(t.kind){case"seq":case"time":return LIe(t.kind,t);case"type":return{kind:t.kind,values:lO(t.kind,t.values)};case"surface":{let n=lO(t.kind,t.values);return hO(t.kind,n,["current","shadowed","log-only"]),{kind:t.kind,values:n}}case"text":if(typeof t.text!="string")throw o2("text filter text must be a string");return{kind:t.kind,text:t.text};default:return fO(t)}})}function m9t(e){let t=e.trim();if(t.length===0)throw new Dr("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 g9t(e){switch(e.kind){case"id":return t=>e.values.includes(t.header.id);case"cwd":return t=>e.values.includes(t.header.cwd??null);case"created-at":{let t=uO(e.kind,e);return n=>Cee(n.header.createdAt,t)}case"parent":return t=>e.values.includes(t.header.parentSession??null);case"availability":return hO(e.kind,e.values,["live","persisted"]),t=>e.values.some(n=>n==="live"?t.live:t.persisted);default:return fO(e)}}function y9t(e){switch(e.kind){case"seq":{let t=uO(e.kind,e);return n=>Cee(n.seq,t)}case"time":{let t=uO(e.kind,e);return n=>Cee(n.time,t)}case"type":return t=>e.values.includes(t.type);case"surface":return hO(e.kind,e.values,["current","shadowed","log-only"]),t=>e.values.includes(t.surface);case"text":{let t=m9t(e.text);return n=>t.test(n.text)}default:return fO(e)}}function lO(e,t){if(!jIe(t)||t.some(n=>typeof n!="string"))throw o2(`${e} filter values must be an array of strings`);return[...t]}function MIe(e){if(!Array.isArray(e))throw o2("filters must be an array")}function NIe(e,t){if(!jIe(t)||t.some(n=>n!==null&&typeof n!="string"))throw o2(`${e} filter values must be an array of strings or null`);return[...t]}function LIe(e,t){let n={kind:e,...t.from===void 0?{}:{from:t.from},...t.to===void 0?{}:{to:t.to}};return uO(e,n),n}function fO(e){let t=e.kind;throw o2(`unknown filter kind ${typeof t=="string"?`"${t}"`:"(missing)"}`)}function hO(e,t,n){for(let r of t)if(!n.includes(r))throw new Dr(`session ${e} filter contains unknown value "${r}"`,"SESSION_QUERY_INVALID_FILTER")}function uO(e,t){if(t.from!==void 0&&!Number.isFinite(t.from))throw Tee(e,"from must be finite");if(t.to!==void 0&&!Number.isFinite(t.to))throw Tee(e,"to must be finite");if(t.from!==void 0&&t.to!==void 0&&t.from>t.to)throw Tee(e,"from must be less than or equal to to");return t}function Cee(e,t){return(t.from===void 0||e>=t.from)&&(t.to===void 0||e<=t.to)}function Tee(e,t){return o2(`${e} filter ${t}`)}function o2(e){return new Dr(`session ${e}`,"SESSION_QUERY_INVALID_FILTER")}function jIe(e){return Array.isArray(e)}function v9t(e,t){return Nee(e,t).records}function w9t(e,t){return Nee(e,t).currentSeqs.map(n=>{let r=t[n];if(r===void 0||r.seq!==n||!Dg(r))throw new Dr(`invalid session surface: current node ${n} is not a surface event`,"SESSION_QUERY_INVALID_SURFACE");return vE(r)})}function b9t(e,t,n){let r=t[n];if(r===void 0||r.seq!==n)throw new Dr(`session "${e}" has no event at seq ${n}`,"SESSION_QUERY_EVENT_NOT_FOUND");let i=Nee(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||PIe(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:[...PIe(r)],derivedEventSeqs:c}}function x9t(e,t){let n=new Map(e.map(p=>[p.header.id,p])),r=n.get(t);if(r===void 0)throw new Dr(`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 Dr(`session lineage contains a cycle at "${c}"`,"SESSION_QUERY_INVALID_LINEAGE");s.add(c);let p=n.get(c);if(p===void 0){o=c;break}i.push(p),c=p.header.parentSession}let l=new Map;for(let p of e){let f=p.header.parentSession;if(f===void 0)continue;let h=l.get(f)??[];h.push(p),l.set(f,h)}for(let p of l.values())p.sort((f,h)=>f.header.createdAt-h.header.createdAt||f.header.id.localeCompare(h.header.id));let u=S9t(l,t),d={target:cO(r),ancestors:i.map(cO),descendants:u};return o!==void 0?{...d,complete:!1,unresolvedParentId:o}:{...d,complete:!0,root:cO(i.at(-1)??r)}}function Nee(e,t){let n;try{n=oF(t,rO)}catch(o){throw new Dr(`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 PIe(e){return e.sourceEventSeqs??[]}function S9t(e,t){let n=[],r=[{sessionId:t,descendants:n}];for(;r.length>0;){let i=r.pop(),s=[];for(let o of e.get(i.sessionId)??[]){let c={session:cO(o),descendants:[]};s.push(c),i.descendants.push(c)}for(let o=s.length-1;o>=0;o-=1){let c=s[o];r.push({sessionId:c.session.header.id,descendants:c.descendants})}}return n}function cO(e){return{...e,header:structuredClone(e.header)}}var Dr,c9t,u9t,FIe,Pee=ce(()=>{IIe();Jn();Ls();t1();mr();Dr=class extends Wr{static{a(this,"SessionQueryError")}constructor(e,t,n){super(e,t,n)}};a(DIe,"readColdSessionLog");a(See,"assertSessionHeadersCompatible");c9t=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 Eee(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&&See(i.header,s.header),r.set(i.id,{header:structuredClone(i.header),live:!0,persisted:s!==void 0})}return[...r.values()].sort(l9t)}async load(e,t){t?.throwIfAborted();let n=this._ctx.sessions.get(e);if(n!==void 0){let l=RIe(n);return t?.throwIfAborted(),l}let r=this._persistence;if(r===void 0)throw oO(e);let i=(await Eee(r,t)).find(l=>l.id===e);if(t?.throwIfAborted(),i===void 0)throw oO(e);let s=await CIe(r,e,t);t?.throwIfAborted();let o=this._ctx.sessions.get(e);if(o!==void 0){let l=RIe(o);return t?.throwIfAborted(),l}See(s.header,i);let c={header:structuredClone(s.header),inheritedEventCount:s.inheritedEventCount,events:s.events.map(l=>structuredClone(l))};return t?.throwIfAborted(),c}async projectMany(e,t,n){let r=[...new Set(e)];n?.throwIfAborted();let i=new Map,s=[];for(let g of r){let y=this._ctx.sessions.get(g);y===void 0?s.push(g):i.set(g,iO(g,kee(y),t,n))}if(s.length===0)return sO(r,i);let o=this._persistence;if(o===void 0){for(let g of s)i.set(g,{sessionId:g,status:"rejected",reason:oO(g)});return sO(r,i)}let c;try{c=await Eee(o,n),n?.throwIfAborted()}catch(g){n?.aborted&&n.throwIfAborted();for(let y of s)i.set(y,{sessionId:y,status:"rejected",reason:g});return sO(r,i)}let l=new Map(c.map(g=>[g.id,g])),u=a(async g=>{let y=l.get(g);if(y===void 0){let v=this._ctx.sessions.get(g);i.set(g,v===void 0?{sessionId:g,status:"rejected",reason:oO(g)}:iO(g,kee(v),t,n));return}try{n?.throwIfAborted();let v=await CIe(o,g,n);n?.throwIfAborted();let w=this._ctx.sessions.get(g);if(w!==void 0){i.set(g,iO(g,kee(w),t,n));return}See(v.header,y),i.set(g,iO(g,{header:v.header,events:v.events},t,n))}catch(v){n?.aborted&&n.throwIfAborted(),i.set(g,{sessionId:g,status:"rejected",reason:v})}},"resolvePersisted"),d=0,p=a(async()=>{for(;;){n?.throwIfAborted();let g=d;if(g>=s.length)return;d+=1,await u(s[g])}},"worker"),f=Math.min(this._persistedReadConcurrency,s.length),h=await Promise.allSettled(Array.from({length:f},()=>p()));n?.aborted&&n.throwIfAborted();for(let g of h)if(g.status==="rejected")throw g.reason;return n?.throwIfAborted(),sO(r,i)}};a(iO,"projectSource");a(kee,"sourceLive");a(sO,"orderedResults");a(Eee,"listPersisted");a(CIe,"inspectPersisted");a(RIe,"snapshotLive");a(l9t,"compareSessions");a(oO,"notFound$1");a(Aee,"errorMessage$1");u9t=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(;;){r4(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 Iee(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);r4(n);let p=this.ctx.sessions.get(e);if(p!==void 0)return this.live(p,r);let f=d.events,h;try{h=this.ctx.sessions.prepare(e,{seed:f,meta:structuredClone(d.header),inheritedEventCount:d.inheritedEventCount,eventState:d.eventState})}catch(g){if(this.ctx.sessions.get(e)!==void 0)continue;throw new Dr(`stored session "${e}" is corrupt: ${aO(g)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:g})}l={persistenceIdentity:s.identity,revision:o.revision,session:h,events:Object.freeze(f),refs:0},this.store(e,l)}let u;try{u=r==="none"?void 0:this.preparedProjections(l)}catch(d){throw new Dr(`failed to project session "${e}": ${aO(d)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:d})}return this.preparedLease(e,l,u)}}async statSource(e,t,n){let r;try{r=await e.stat(t,n===void 0?void 0:{signal:n})}catch(i){throw r4(n),OIe(t,i)}if(r4(n),r===void 0)throw Iee(t);if(r.header.id!==t)throw new Dr(`session persistence returned "${r.header.id}" for "${t}"`,"SESSION_QUERY_SOURCE_CONFLICT");return r}async loadSource(e,t,n){try{return await DIe(e,t,n)}catch(r){throw r4(n),OIe(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 Dr(`failed to project session "${e.id}": ${aO(o)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:o})}let s=a(()=>{let o=!1;return{source:"live",header:e.header,inheritedEventCount:e.inheritedEventCount,get events(){return r??=e.snapshotEvents(In(0),n),r},cursor:n===0?-1: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,In(0)):n.hydratePrepared(e.session,e.events)}};a(r4,"throwIfObservationAborted");a(OIe,"mapPersistenceFailure");a(Iee,"notFound");a(aO,"errorMessage");a($Ie,"hasErrorName");a(d9t,"extractSessionEventText");a(p9t,"turnEndText");a(_ee,"contentText");a(f9t,"blockText");a(i4,"joinText");a(Ree,"buildSessionEventSearchDocuments");a(h9t,"classifySurface");a(Oee,"filterSessionResults");a(dO,"filterSessionEventDocuments");a($ee,"materializeSessionResultFilters");a(pO,"materializeSessionEventResultFilters");a(m9t,"compileSessionTextFilter");a(g9t,"sessionPredicate");a(y9t,"eventPredicate");a(lO,"copyStrings");a(MIe,"assertArray");a(NIe,"copyNullableStrings");a(LIe,"copyRange");a(fO,"unknownFilter");a(hO,"assertAllowedValues");a(uO,"validateRange");a(Cee,"matchesRange");a(Tee,"invalidRange");a(o2,"invalidFilter");a(jIe,"isRuntimeArray");a(v9t,"eventRecords");a(w9t,"currentSurfaceEvents");a(b9t,"traceEvent");a(x9t,"traceSession");a(Nee,"analyzeEventLog");a(PIe,"eventSources");a(S9t,"buildDescendants");a(cO,"cloneRecord");FIe=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 Dr("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 Dr("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 Dr("session-query: preparedSessionCacheSize must be a positive safe integer","SESSION_QUERY_INVALID_CONFIG");this._corpus=new c9t(e,n),this._observations=new u9t(e,r)}observeSession(e,t={}){return this._observations.read(e,t)}listSessions(e){return this._corpus.listSessions(e)}async readSession(e){let t=await this._corpus.load(e);return X0.create(e,t.events,t.header,t.inheritedEventCount,rO),{session:structuredClone(t.header),inheritedEventCount:t.inheritedEventCount,events:t.events.map(vE)}}async filterSessions(e,t){let n=$ee(e);return this._filterSessions(n,t)}async readTitle(e,t){return(await this.readTitleSnapshot(e,t)).title}async readTitleSnapshot(e,t){let n=(await this.readTitleSnapshots([e],t))[0];if(n.status==="rejected")throw n.reason;return n.value}async readTitleSnapshots(e,t){return this._corpus.projectMany(e,n=>{let r=e1(n.events);return{session:structuredClone(n.header),...r===void 0?{}:{title:r}}},t)}async listEvents(e){return v9t(e,(await this._corpus.load(e)).events)}async filterEvents(e,t){let n=pO(t);return this._filterEvents(e,n)}async _filterSessions(e,t){return Oee(await this._corpus.listSessions(t),e)}async _filterEvents(e,t){return dO(Ree(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:w9t(e,t.events)}}async traceSession(e,t){let n=await this._corpus.listSessions(t);return t?.throwIfAborted(),x9t(n,e)}async traceEvent(e,t){let n=await this._corpus.load(e.sessionId,t);return t?.throwIfAborted(),{session:n.header,...b9t(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 Dr(`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=vE(o),d=s.events.slice(c,l+1).map(p=>p===o?u:vE(p));return{session:structuredClone(s.header),inheritedEventCount:s.inheritedEventCount,target:u,events:d,startSeq:c,endSeq:l}}_readWindow(e,t){if(t===void 0)return 0;if(!Number.isInteger(t)||t<0||t>this._readWindowMax)throw new Dr(`${e} must be an integer between 0 and ${this._readWindowMax}`,"SESSION_QUERY_INVALID_WINDOW");return t}}});var a2=be((wGn,JIe)=>{"use strict";JIe.exports=lv;lv.CAPTURING_PHASE=1;lv.AT_TARGET=2;lv.BUBBLING_PHASE=3;function lv(e,t){if(this.type="",this.target=null,this.currentTarget=null,this.eventPhase=lv.AT_TARGET,this.bubbles=!1,this.cancelable=!1,this.isTrusted=!1,this.defaultPrevented=!1,this.timeStamp=Date.now(),this._propagationStopped=!1,this._immediatePropagationStopped=!1,this._initialized=!0,this._dispatching=!1,e&&(this.type=e),t)for(var n in t)this[n]=t[n]}a(lv,"Event");lv.prototype=Object.create(Object.prototype,{constructor:{value:lv},stopPropagation:{value:a(function(){this._propagationStopped=!0},"stopPropagation")},stopImmediatePropagation:{value:a(function(){this._propagationStopped=!0,this._immediatePropagationStopped=!0},"stopImmediatePropagation")},preventDefault:{value:a(function(){this.cancelable&&(this.defaultPrevented=!0)},"preventDefault")},initEvent:{value:a(function(t,n,r){this._initialized=!0,!this._dispatching&&(this._propagationStopped=!1,this._immediatePropagationStopped=!1,this.defaultPrevented=!1,this.isTrusted=!1,this.target=null,this.type=t,this.bubbles=n,this.cancelable=r)},"initEvent")}})});var Uee=be((xGn,QIe)=>{"use strict";var XIe=a2();QIe.exports=qee;function qee(){XIe.call(this),this.view=null,this.detail=0}a(qee,"UIEvent");qee.prototype=Object.create(XIe.prototype,{constructor:{value:qee},initUIEvent:{value:a(function(e,t,n,r,i){this.initEvent(e,t,n),this.view=r,this.detail=i},"value")}})});var zee=be((kGn,t8e)=>{"use strict";var e8e=Uee();t8e.exports=Bee;function Bee(){e8e.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(Bee,"MouseEvent");Bee.prototype=Object.create(e8e.prototype,{constructor:{value:Bee},initMouseEvent:{value:a(function(e,t,n,r,i,s,o,c,l,u,d,p,f,h,g){switch(this.initEvent(e,t,n,r,i),this.screenX=s,this.screenY=o,this.clientX=c,this.clientY=l,this.ctrlKey=u,this.altKey=d,this.shiftKey=p,this.metaKey=f,this.button=h,h){case 0:this.buttons=1;break;case 1:this.buttons=4;break;case 2:this.buttons=2;break;default:this.buttons=0;break}this.relatedTarget=g},"value")},getModifierState:{value:a(function(e){switch(e){case"Alt":return this.altKey;case"Control":return this.ctrlKey;case"Shift":return this.shiftKey;case"Meta":return this.metaKey;default:return!1}},"value")}})});var bO=be((_Gn,r8e)=>{"use strict";r8e.exports=wO;var F9t=1,q9t=3,U9t=4,B9t=5,z9t=7,W9t=8,H9t=9,V9t=11,G9t=12,K9t=13,Z9t=14,Y9t=15,J9t=17,X9t=18,Q9t=19,eRt=20,tRt=21,nRt=22,rRt=23,iRt=24,sRt=25,oRt=[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"],aRt=[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."],n8e={INDEX_SIZE_ERR:F9t,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:q9t,WRONG_DOCUMENT_ERR:U9t,INVALID_CHARACTER_ERR:B9t,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:z9t,NOT_FOUND_ERR:W9t,NOT_SUPPORTED_ERR:H9t,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:V9t,SYNTAX_ERR:G9t,INVALID_MODIFICATION_ERR:K9t,NAMESPACE_ERR:Z9t,INVALID_ACCESS_ERR:Y9t,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:J9t,SECURITY_ERR:X9t,NETWORK_ERR:Q9t,ABORT_ERR:eRt,URL_MISMATCH_ERR:tRt,QUOTA_EXCEEDED_ERR:nRt,TIMEOUT_ERR:rRt,INVALID_NODE_TYPE_ERR:iRt,DATA_CLONE_ERR:sRt};function wO(e){Error.call(this),Error.captureStackTrace(this,this.constructor),this.code=e,this.message=aRt[e],this.name=oRt[e]}a(wO,"DOMException");wO.prototype.__proto__=Error.prototype;for(vO in n8e)Wee={value:n8e[vO]},Object.defineProperty(wO,vO,Wee),Object.defineProperty(wO.prototype,vO,Wee);var Wee,vO});var xO=be(i8e=>{i8e.isApiWritable=!globalThis.__domino_frozen__});var xo=be(Fi=>{"use strict";var bo=bO(),jo=bo,cRt=xO().isApiWritable;Fi.NAMESPACE={HTML:"http://www.w3.org/1999/xhtml",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/",MATHML:"http://www.w3.org/1998/Math/MathML",SVG:"http://www.w3.org/2000/svg",XLINK:"http://www.w3.org/1999/xlink"};Fi.IndexSizeError=function(){throw new bo(jo.INDEX_SIZE_ERR)};Fi.HierarchyRequestError=function(){throw new bo(jo.HIERARCHY_REQUEST_ERR)};Fi.WrongDocumentError=function(){throw new bo(jo.WRONG_DOCUMENT_ERR)};Fi.InvalidCharacterError=function(){throw new bo(jo.INVALID_CHARACTER_ERR)};Fi.NoModificationAllowedError=function(){throw new bo(jo.NO_MODIFICATION_ALLOWED_ERR)};Fi.NotFoundError=function(){throw new bo(jo.NOT_FOUND_ERR)};Fi.NotSupportedError=function(){throw new bo(jo.NOT_SUPPORTED_ERR)};Fi.InvalidStateError=function(){throw new bo(jo.INVALID_STATE_ERR)};Fi.SyntaxError=function(){throw new bo(jo.SYNTAX_ERR)};Fi.InvalidModificationError=function(){throw new bo(jo.INVALID_MODIFICATION_ERR)};Fi.NamespaceError=function(){throw new bo(jo.NAMESPACE_ERR)};Fi.InvalidAccessError=function(){throw new bo(jo.INVALID_ACCESS_ERR)};Fi.TypeMismatchError=function(){throw new bo(jo.TYPE_MISMATCH_ERR)};Fi.SecurityError=function(){throw new bo(jo.SECURITY_ERR)};Fi.NetworkError=function(){throw new bo(jo.NETWORK_ERR)};Fi.AbortError=function(){throw new bo(jo.ABORT_ERR)};Fi.UrlMismatchError=function(){throw new bo(jo.URL_MISMATCH_ERR)};Fi.QuotaExceededError=function(){throw new bo(jo.QUOTA_EXCEEDED_ERR)};Fi.TimeoutError=function(){throw new bo(jo.TIMEOUT_ERR)};Fi.InvalidNodeTypeError=function(){throw new bo(jo.INVALID_NODE_TYPE_ERR)};Fi.DataCloneError=function(){throw new bo(jo.DATA_CLONE_ERR)};Fi.nyi=function(){throw new Error("NotYetImplemented")};Fi.shouldOverride=function(){throw new Error("Abstract function; should be overriding in subclass.")};Fi.assert=function(e,t){if(!e)throw new Error("Assertion failed: "+(t||"")+`
|
|
158
158
|
`+new Error().stack)};Fi.expose=function(e,t){for(var n in e)Object.defineProperty(t.prototype,n,{value:e[n],writable:cRt})};Fi.merge=function(e,t){for(var n in t)e[n]=t[n]};Fi.documentOrder=function(e,t){return 3-(e.compareDocumentPosition(t)&6)};Fi.toASCIILowerCase=function(e){return e.replace(/[A-Z]+/g,function(t){return t.toLowerCase()})};Fi.toASCIIUpperCase=function(e){return e.replace(/[a-z]+/g,function(t){return t.toUpperCase()})}});var Hee=be((CGn,o8e)=>{"use strict";var uv=a2(),lRt=zee(),uRt=xo();o8e.exports=s8e;function s8e(){}a(s8e,"EventTarget");s8e.prototype={addEventListener:a(function(t,n,r){if(n){r===void 0&&(r=!1),this._listeners||(this._listeners=Object.create(null)),this._listeners[t]||(this._listeners[t]=[]);for(var i=this._listeners[t],s=0,o=i.length;s<o;s++){var c=i[s];if(c.listener===n&&c.capture===r)return}var l={listener:n,capture:r};typeof n=="function"&&(l.f=n),i.push(l)}},"addEventListener"),removeEventListener:a(function(t,n,r){if(r===void 0&&(r=!1),this._listeners){var i=this._listeners[t];if(i)for(var s=0,o=i.length;s<o;s++){var c=i[s];if(c.listener===n&&c.capture===r){i.length===1?this._listeners[t]=void 0:i.splice(s,1);return}}}},"removeEventListener"),dispatchEvent:a(function(t){return this._dispatchEvent(t,!1)},"dispatchEvent"),_dispatchEvent:a(function(t,n){typeof n!="boolean"&&(n=!1);function r(u,d){var p=d.type,f=d.eventPhase;if(d.currentTarget=u,f!==uv.CAPTURING_PHASE&&u._handlers&&u._handlers[p]){var h=u._handlers[p],g;if(typeof h=="function")g=h.call(d.currentTarget,d);else{var y=h.handleEvent;if(typeof y!="function")throw new TypeError("handleEvent property of event handler object isnot a function.");g=y.call(h,d)}d.type==="mouseover"?g===!0&&d.preventDefault():g===!1&&d.preventDefault()}var v=u._listeners&&u._listeners[p];if(v){v=v.slice();for(var w=0,b=v.length;w<b;w++){if(d._immediatePropagationStopped)return;var S=v[w];if(!(f===uv.CAPTURING_PHASE&&!S.capture||f===uv.BUBBLING_PHASE&&S.capture))if(S.f)S.f.call(d.currentTarget,d);else{var k=S.listener.handleEvent;if(typeof k!="function")throw new TypeError("handleEvent property of event listener object is not a function.");k.call(S.listener,d)}}}}a(r,"invoke"),(!t._initialized||t._dispatching)&&uRt.InvalidStateError(),t.isTrusted=n,t._dispatching=!0,t.target=this;for(var i=[],s=this.parentNode;s;s=s.parentNode)i.push(s);t.eventPhase=uv.CAPTURING_PHASE;for(var o=i.length-1;o>=0&&(r(i[o],t),!t._propagationStopped);o--);if(t._propagationStopped||(t.eventPhase=uv.AT_TARGET,r(this,t)),t.bubbles&&!t._propagationStopped){t.eventPhase=uv.BUBBLING_PHASE;for(var c=0,l=i.length;c<l&&(r(i[c],t),!t._propagationStopped);c++);}if(t._dispatching=!1,t.eventPhase=uv.AT_TARGET,t.currentTarget=null,n&&!t.defaultPrevented&&t instanceof lRt)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 Vee=be((OGn,a8e)=>{"use strict";var Rm=xo(),bd=a8e.exports={valid:a(function(e){return Rm.assert(e,"list falsy"),Rm.assert(e._previousSibling,"previous falsy"),Rm.assert(e._nextSibling,"next falsy"),!0},"valid"),insertBefore:a(function(e,t){Rm.assert(bd.valid(e)&&bd.valid(t));var n=e,r=e._previousSibling,i=t,s=t._previousSibling;n._previousSibling=s,r._nextSibling=i,s._nextSibling=n,i._previousSibling=r,Rm.assert(bd.valid(e)&&bd.valid(t))},"insertBefore"),replace:a(function(e,t){Rm.assert(bd.valid(e)&&(t===null||bd.valid(t))),t!==null&&bd.insertBefore(t,e),bd.remove(e),Rm.assert(bd.valid(e)&&(t===null||bd.valid(t)))},"replace"),remove:a(function(e){Rm.assert(bd.valid(e));var t=e._previousSibling;if(t!==e){var n=e._nextSibling;t._nextSibling=n,n._previousSibling=t,e._previousSibling=e._nextSibling=e,Rm.assert(bd.valid(e))}},"remove")}});var Gee=be((NGn,m8e)=>{"use strict";m8e.exports={serializeOne:yRt,\u0275escapeMatchingClosingTag:p8e,\u0275escapeClosingCommentTag:f8e,\u0275escapeProcessingInstructionContent:h8e};var d8e=xo(),dv=d8e.NAMESPACE,c8e={STYLE:!0,SCRIPT:!0,XMP:!0,IFRAME:!0,NOEMBED:!0,NOFRAMES:!0,PLAINTEXT:!0},dRt={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},pRt={},l8e=/[&<>\u00A0]/g,u8e=/[&"<>\u00A0]/g;function fRt(e){return l8e.test(e)?e.replace(l8e,t=>{switch(t){case"&":return"&";case"<":return"<";case">":return">";case"\xA0":return" "}}):e}a(fRt,"escape");function hRt(e){return u8e.test(e)?e.replace(u8e,t=>{switch(t){case"<":return"<";case">":return">";case"&":return"&";case'"':return""";case"\xA0":return" "}}):e}a(hRt,"escapeAttr");function mRt(e){var t=e.namespaceURI;return t?t===dv.XML?"xml:"+e.localName:t===dv.XLINK?"xlink:"+e.localName:t===dv.XMLNS?e.localName==="xmlns"?"xmlns":"xmlns:"+e.localName:e.name:e.localName}a(mRt,"attrname");function p8e(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(p8e,"escapeMatchingClosingTag");var gRt=/--!?>/;function f8e(e){return gRt.test(e)?e.replace(/(--\!?)>/g,"$1>"):e}a(f8e,"escapeClosingCommentTag");function h8e(e){return e.includes(">")?e.replaceAll(">",">"):e}a(h8e,"escapeProcessingInstructionContent");function yRt(e,t){var n="";switch(e.nodeType){case 1:var r=e.namespaceURI,i=r===dv.HTML,s=i||r===dv.SVG||r===dv.MATHML?e.localName:e.tagName;n+="<"+s;for(var o=0,c=e._numattrs;o<c;o++){var l=e._attr(o);n+=" "+mRt(l),l.value!==void 0&&(n+='="'+hRt(l.value)+'"')}if(n+=">",!(i&&dRt[s])){var u=e.serialize();c8e[s.toUpperCase()]&&(u=p8e(u,s)),i&&pRt[s]&&u.charAt(0)===`
|
|
@@ -5927,7 +5927,7 @@ The web search request used endpoint ${JSON.stringify(e)}. Search endpoint confi
|
|
|
5927
5927
|
.error { padding: .75rem; border-radius: .5rem; background: #461d2b; color: #ffd6df; }
|
|
5928
5928
|
.hint { margin: 1.5rem 0 0; font-size: .875rem; }
|
|
5929
5929
|
code { padding: .1rem .3rem; border-radius: .3rem; background: #0c1222; color: #edf2ff; }
|
|
5930
|
-
`}a(nje,"pageStyles");F6();var uoe="enabled",doe=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")}),y3=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")}),poe=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===uoe?"available":"needs-binding","probe")}),Hen=Object.freeze([poe,y3,doe]);function foe(e,t=Hen){return t.filter(n=>n.probe(e)==="available")}a(foe,"availableEdgeRuntimeProviders");function hoe(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(hoe,"resolveEdgeRuntimeSelection");function JN(e){let t=foe(e),{bash:n,container:r}=hoe(t);return t.find(i=>i.id===(r??n)).shell}a(JN,"resolveEdgeRuntimeShell");function Ven(){return"dsh-edge@0.23.0-alpha.2/direct"}a(Ven,"resolveEdgeDeploymentId");function H2(e){return{baseURL:yX(e.DEEPSEEK_BASE_URL),maxTokens:bX(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Xy(e.DEEPSEEK_MODEL),reasoningEffort:vX(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:A4(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:wX(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:s0(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(H2,"resolveEdgeDeploymentConfig");function Gen(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(Gen,"edgeDeploymentApiKeyConfigured");function Ken(e){let t=yX(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(Ken,"projectedEdgeBaseURL");function moe(e,t){return{shell:JN(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:Ven(),apiKeyConfigured:Gen(e),baseURL:Ken(e.DEEPSEEK_BASE_URL),maxTokens:bX(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Xy(e.DEEPSEEK_MODEL),reasoningEffort:vX(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:A4(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:wX(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:s0(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(moe,"resolveEdgeDeploymentProfile");function XN(e){H2(e);let t=moe(e);return{ok:!0,service:"dsh-edge",storage:t.storage,attachmentStorage:t.attachmentStorage,shell:t.shell,agent:"upstream-react-loop-agent",access:"single-owner-cookie",deploymentId:t.deploymentId,...e.CF_VERSION_METADATA===void 0?{}:{workerVersionId:e.CF_VERSION_METADATA.id},version:By,upstreamVersion:NEe,status:"ready"}}a(XN,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as i0n}from"node:async_hooks";import{RpcTarget as Zen}from"cloudflare:workers";function Yen(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(Yen,"startHeartbeat");async function Jen(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(Jen,"probeComputerdHealth");var Xen="computer.internal",Qen="/health",goe="/api",etn=8080,ttn=3e4,ntn=2e4,rtn=1,itn=2e3,stn=250,otn=2e3;function atn(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(atn,"bearerMatches");var eP=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??Xen,containerPort:e.containerPort??etn,connectTimeoutMs:e.connectTimeoutMs??ttn,heartbeatIntervalMs:e.heartbeatIntervalMs??ntn,restartAttempts:e.restartAttempts??rtn,healthProbeTimeoutMs:e.healthProbeTimeoutMs??itn,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??stn,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??otn}}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 Oc(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 Oc(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=AM(o),l,u=new Promise(p=>{let f=!1,h=a(()=>{f||(f=!0,l?.(),p(),this.#c=void 0)},"onClose");o.addEventListener("close",h,{once:!0}),o.addEventListener("error",h,{once:!0}),c.onRpcBroken(h)});this.#e.heartbeatIntervalMs>0&&(l=Yen({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(zS),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(CA),i.delete(zS);let c=new Request(e,{headers:i});return this.#t.gateway.fetch(new Request(o,c))}if(new URL(e.url).pathname!==goe)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${goe} requires a websocket upgrade`,{status:400});if(!atn(e.headers.get("authorization"),this.#n))return new Response("unauthorized",{status:401,headers:{"www-authenticate":"Bearer"}});let t=new WebSocketPair,[n,r]=[t[0],t[1]];if(r.accept(),this.#s)this.#s(r);else return r.close(1011,"no pending connect"),new Response("no pending connect",{status:409});return new Response(null,{status:101,webSocket:n})}#u(){this.#i=new Promise((e,t)=>{this.#s=e,this.#a=t}),this.#i.catch(()=>{})}#o(){this.#i=void 0,this.#s=void 0,this.#a=void 0}async#p(e,t,n,r,i){let s=this.#e.restartAttempts+1,o=Math.max(0,n-Date.now()),c=Math.max(250,Math.floor(o/s)),l=0,u=0,d,p=i;for(;l<s;){l++;let f=Math.min(n,Date.now()+c);if(await this.#m(e,f).then(()=>!0,h=>(d=h,!1)))return p;if(l<s)try{({runtimeId:p}=await e.restart({env:t,enableInternet:this.#t.mode==="direct"})),u++}catch(h){throw this.#a?.(h),this.#o(),new Oc(this.#d("restart",{attempt:l,maxAttempts:s,restarts:u,lastError:h}),{cause:h})}}throw this.#a?.(new Error("computerd never became healthy")),this.#o(),new Oc(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 Jen(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 ctn(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=${rje(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 Oc(`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:Qen,api:goe,healthTimeoutMs:r})})}catch(s){throw this.#a?.(s),this.#o(),new Oc(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${rje(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 Oc(`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 Oc(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#o()}}};function ctn(e){return new Promise(t=>setTimeout(t,e))}a(ctn,"sleep");function rje(e){return e instanceof Error?e.message:String(e)}a(rje,"describeError");var ije="computer:container-client-secret",ltn=16;function utn(){let e=crypto.getRandomValues(new Uint8Array(ltn));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(utn,"generate");var dtn=class{static{a(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(ije);if(typeof e=="string"&&e.length>0)return e;let t=utn();return await this.storage.put(ije,t),t}},sje="computer:container-launch-record";async function oje(e){return{enableInternet:e.enableInternet,envDigest:await ftn(e.env)}}a(oje,"launchRecordFor");function ptn(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}a(ptn,"sameLaunch");async function ftn(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(ftn,"digestEnv");var htn=class{static{a(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(sje)??null}async set(e){await this.storage.put(sje,e)}},aje=new WeakMap;function woe(e){let t=aje.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},aje.set(e,t)),t}a(woe,"getContainerLifecycle");function QN(e){return woe(e).exit}a(QN,"containerExitInfo");function cje(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}a(cje,"formatExitReason");function lje(e,t,n){let r=woe(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>uje(r,i,void 0,n),s=>uje(r,i,s,n))}a(lje,"installContainerMonitor");async function yoe(e,t){let n=woe(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}a(yoe,"destroyContainerExpectingExit");async function uje(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=cje(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:cje(c),exitedAt:Date.now()})}}a(uje,"recordExit");var voe="computer:container-runtime-identity",mtn=class{static{a(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(voe)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(voe,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(voe)}},gtn=class extends Zen{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 mtn(e.storage),this.#n=new dtn(e.storage),this.#i=new htn(e.storage)}async start(e){let t=QN(this.#t),n=await this.#n.ensure(),r=await oje(e);if(t!==null){try{await yoe(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||!ptn(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 yoe(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return lje(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await yoe(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await oje(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),lje(this.#t,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:QN(this.#t)}}async exitInfo(){return QN(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=QN(this.#t);if(r!==null)throw new Oc(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function dje(e){class t extends e{static{a(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new gtn(this.ctx)}}return t}a(dje,"withWorkspaceContainer");var ytn={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function fje(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=ytn[s]??s,l=e[c];if(l===void 0)return;let u=l[o];return typeof u=="function"?u:void 0}a(fje,"resolve");function vtn(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}a(vtn,"errorResponse");async function boe(e,t,n,r,i){let s=fje(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}a(boe,"callEdgeApi");async function hje(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(fje(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 boe(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 vtn(o,{code:"internal",message:String(l),details:{}})}}a(hje,"dispatchEdgeApi");mr();Ls();t1();import{DurableObject as s0n}from"cloudflare:workers";var tP=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 wtn(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 wtn(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(wtn,"untilAborted");import{WorkerEntrypoint as Rar}from"cloudflare:workers";var uw=hl(mje());import{gunzipSync as Ern}from"node:zlib";var v3=class{static{a(this,"Diff")}diff(t,n,r={}){let i;typeof r=="function"?(i=r,r={}):"callback"in r&&(i=r.callback);let s=this.castInput(t,r),o=this.castInput(n,r),c=this.removeEmpty(this.tokenize(s,r)),l=this.removeEmpty(this.tokenize(o,r));return this.diffWithOptionsObj(c,l,r,i)}diffWithOptionsObj(t,n,r,i){var s;let o=a(b=>{if(b=this.postProcess(b,r),i){setTimeout(function(){i(b)},0);return}else return b},"done"),c=n.length,l=t.length,u=1,d=c+l;r.maxEditLength!=null&&(d=Math.min(d,r.maxEditLength));let p=(s=r.timeout)!==null&&s!==void 0?s:1/0,f=Date.now()+p,h=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(h[0],n,t,0,r);if(h[0].oldPos+1>=l&&g+1>=c)return o(this.buildValues(h[0].lastComponent,n,t));let y=-1/0,v=1/0,w=a(()=>{for(let b=Math.max(y,-u);b<=Math.min(v,u);b+=2){let S,k=h[b-1],E=h[b+1];k&&(h[b-1]=void 0);let _=!1;if(E){let P=E.oldPos-b;_=E&&0<=P&&P<c}let T=k&&k.oldPos+1<l;if(!_&&!T){h[b]=void 0;continue}if(!T||_&&k.oldPos<E.oldPos?S=this.addToPath(E,!0,!1,0,r):S=this.addToPath(k,!1,!0,1,r),g=this.extractCommon(S,n,t,b,r),S.oldPos+1>=l&&g+1>=c)return o(this.buildValues(S.lastComponent,n,t))||!0;h[b]=S,S.oldPos+1>=l&&(v=Math.min(v,b-1)),g+1>=c&&(y=Math.max(y,b+1))}u++},"execEditLength");if(i)a(function b(){setTimeout(function(){if(u>d||Date.now()>f)return i(void 0);w()||b()},0)},"exec")();else for(;u<=d&&Date.now()<=f;){let b=w();if(b)return b}}addToPath(t,n,r,i,s){let o=t.lastComponent;return o&&!s.oneChangePerToken&&o.added===n&&o.removed===r?{oldPos:t.oldPos+i,lastComponent:{count:o.count+1,added:n,removed:r,previousComponent:o.previousComponent}}:{oldPos:t.oldPos+i,lastComponent:{count:1,added:n,removed:r,previousComponent:o}}}extractCommon(t,n,r,i,s){let o=n.length,c=r.length,l=t.oldPos,u=l-i,d=0;for(;u+1<o&&l+1<c&&this.equals(r[l+1],n[u+1],s);)u++,l++,d++,s.oneChangePerToken&&(t.lastComponent={count:1,previousComponent:t.lastComponent,added:!1,removed:!1});return d&&!s.oneChangePerToken&&(t.lastComponent={count:d,previousComponent:t.lastComponent,added:!1,removed:!1}),t.oldPos=l,u}equals(t,n,r){return r.comparator?r.comparator(t,n):t===n||!!r.ignoreCase&&t.toLowerCase()===n.toLowerCase()}removeEmpty(t){let n=[];for(let r=0;r<t.length;r++)t[r]&&n.push(t[r]);return n}castInput(t,n){return t}tokenize(t,n){return Array.from(t)}join(t){return t.join("")}postProcess(t,n){return t}get useLongestToken(){return!1}buildValues(t,n,r){let i=[],s;for(;t;)i.push(t),s=t.previousComponent,delete t.previousComponent,t=s;i.reverse();let o=i.length,c=0,l=0,u=0;for(;c<o;c++){let d=i[c];if(d.removed)d.value=this.join(r.slice(u,u+d.count)),u+=d.count;else{if(!d.added&&this.useLongestToken){let p=n.slice(l,l+d.count);p=p.map(function(f,h){let g=r[u+h];return g.length>f.length?g:f}),d.value=this.join(p)}else d.value=this.join(n.slice(l,l+d.count));l+=d.count,d.added||(u+=d.count)}}return i}};var xoe=class extends v3{static{a(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=xtn}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
|
|
5930
|
+
`}a(nje,"pageStyles");F6();var uoe="enabled",doe=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")}),y3=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")}),poe=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===uoe?"available":"needs-binding","probe")}),Hen=Object.freeze([poe,y3,doe]);function foe(e,t=Hen){return t.filter(n=>n.probe(e)==="available")}a(foe,"availableEdgeRuntimeProviders");function hoe(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(hoe,"resolveEdgeRuntimeSelection");function JN(e){let t=foe(e),{bash:n,container:r}=hoe(t);return t.find(i=>i.id===(r??n)).shell}a(JN,"resolveEdgeRuntimeShell");function Ven(){return"dsh-edge@0.23.0/direct"}a(Ven,"resolveEdgeDeploymentId");function H2(e){return{baseURL:yX(e.DEEPSEEK_BASE_URL),maxTokens:bX(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Xy(e.DEEPSEEK_MODEL),reasoningEffort:vX(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:A4(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:wX(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:s0(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(H2,"resolveEdgeDeploymentConfig");function Gen(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(Gen,"edgeDeploymentApiKeyConfigured");function Ken(e){let t=yX(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(Ken,"projectedEdgeBaseURL");function moe(e,t){return{shell:JN(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:Ven(),apiKeyConfigured:Gen(e),baseURL:Ken(e.DEEPSEEK_BASE_URL),maxTokens:bX(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Xy(e.DEEPSEEK_MODEL),reasoningEffort:vX(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:A4(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:wX(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:s0(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(moe,"resolveEdgeDeploymentProfile");function XN(e){H2(e);let t=moe(e);return{ok:!0,service:"dsh-edge",storage:t.storage,attachmentStorage:t.attachmentStorage,shell:t.shell,agent:"upstream-react-loop-agent",access:"single-owner-cookie",deploymentId:t.deploymentId,...e.CF_VERSION_METADATA===void 0?{}:{workerVersionId:e.CF_VERSION_METADATA.id},version:By,upstreamVersion:NEe,status:"ready"}}a(XN,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as i0n}from"node:async_hooks";import{RpcTarget as Zen}from"cloudflare:workers";function Yen(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(Yen,"startHeartbeat");async function Jen(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(Jen,"probeComputerdHealth");var Xen="computer.internal",Qen="/health",goe="/api",etn=8080,ttn=3e4,ntn=2e4,rtn=1,itn=2e3,stn=250,otn=2e3;function atn(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(atn,"bearerMatches");var eP=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??Xen,containerPort:e.containerPort??etn,connectTimeoutMs:e.connectTimeoutMs??ttn,heartbeatIntervalMs:e.heartbeatIntervalMs??ntn,restartAttempts:e.restartAttempts??rtn,healthProbeTimeoutMs:e.healthProbeTimeoutMs??itn,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??stn,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??otn}}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 Oc(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 Oc(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=AM(o),l,u=new Promise(p=>{let f=!1,h=a(()=>{f||(f=!0,l?.(),p(),this.#c=void 0)},"onClose");o.addEventListener("close",h,{once:!0}),o.addEventListener("error",h,{once:!0}),c.onRpcBroken(h)});this.#e.heartbeatIntervalMs>0&&(l=Yen({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(zS),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(CA),i.delete(zS);let c=new Request(e,{headers:i});return this.#t.gateway.fetch(new Request(o,c))}if(new URL(e.url).pathname!==goe)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${goe} requires a websocket upgrade`,{status:400});if(!atn(e.headers.get("authorization"),this.#n))return new Response("unauthorized",{status:401,headers:{"www-authenticate":"Bearer"}});let t=new WebSocketPair,[n,r]=[t[0],t[1]];if(r.accept(),this.#s)this.#s(r);else return r.close(1011,"no pending connect"),new Response("no pending connect",{status:409});return new Response(null,{status:101,webSocket:n})}#u(){this.#i=new Promise((e,t)=>{this.#s=e,this.#a=t}),this.#i.catch(()=>{})}#o(){this.#i=void 0,this.#s=void 0,this.#a=void 0}async#p(e,t,n,r,i){let s=this.#e.restartAttempts+1,o=Math.max(0,n-Date.now()),c=Math.max(250,Math.floor(o/s)),l=0,u=0,d,p=i;for(;l<s;){l++;let f=Math.min(n,Date.now()+c);if(await this.#m(e,f).then(()=>!0,h=>(d=h,!1)))return p;if(l<s)try{({runtimeId:p}=await e.restart({env:t,enableInternet:this.#t.mode==="direct"})),u++}catch(h){throw this.#a?.(h),this.#o(),new Oc(this.#d("restart",{attempt:l,maxAttempts:s,restarts:u,lastError:h}),{cause:h})}}throw this.#a?.(new Error("computerd never became healthy")),this.#o(),new Oc(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 Jen(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 ctn(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=${rje(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 Oc(`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:Qen,api:goe,healthTimeoutMs:r})})}catch(s){throw this.#a?.(s),this.#o(),new Oc(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${rje(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 Oc(`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 Oc(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#o()}}};function ctn(e){return new Promise(t=>setTimeout(t,e))}a(ctn,"sleep");function rje(e){return e instanceof Error?e.message:String(e)}a(rje,"describeError");var ije="computer:container-client-secret",ltn=16;function utn(){let e=crypto.getRandomValues(new Uint8Array(ltn));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(utn,"generate");var dtn=class{static{a(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(ije);if(typeof e=="string"&&e.length>0)return e;let t=utn();return await this.storage.put(ije,t),t}},sje="computer:container-launch-record";async function oje(e){return{enableInternet:e.enableInternet,envDigest:await ftn(e.env)}}a(oje,"launchRecordFor");function ptn(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}a(ptn,"sameLaunch");async function ftn(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(ftn,"digestEnv");var htn=class{static{a(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(sje)??null}async set(e){await this.storage.put(sje,e)}},aje=new WeakMap;function woe(e){let t=aje.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},aje.set(e,t)),t}a(woe,"getContainerLifecycle");function QN(e){return woe(e).exit}a(QN,"containerExitInfo");function cje(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}a(cje,"formatExitReason");function lje(e,t,n){let r=woe(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>uje(r,i,void 0,n),s=>uje(r,i,s,n))}a(lje,"installContainerMonitor");async function yoe(e,t){let n=woe(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}a(yoe,"destroyContainerExpectingExit");async function uje(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=cje(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:cje(c),exitedAt:Date.now()})}}a(uje,"recordExit");var voe="computer:container-runtime-identity",mtn=class{static{a(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(voe)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(voe,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(voe)}},gtn=class extends Zen{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 mtn(e.storage),this.#n=new dtn(e.storage),this.#i=new htn(e.storage)}async start(e){let t=QN(this.#t),n=await this.#n.ensure(),r=await oje(e);if(t!==null){try{await yoe(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||!ptn(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 yoe(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return lje(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await yoe(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await oje(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),lje(this.#t,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:QN(this.#t)}}async exitInfo(){return QN(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=QN(this.#t);if(r!==null)throw new Oc(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function dje(e){class t extends e{static{a(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new gtn(this.ctx)}}return t}a(dje,"withWorkspaceContainer");var ytn={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function fje(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=ytn[s]??s,l=e[c];if(l===void 0)return;let u=l[o];return typeof u=="function"?u:void 0}a(fje,"resolve");function vtn(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}a(vtn,"errorResponse");async function boe(e,t,n,r,i){let s=fje(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}a(boe,"callEdgeApi");async function hje(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(fje(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 boe(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 vtn(o,{code:"internal",message:String(l),details:{}})}}a(hje,"dispatchEdgeApi");mr();Ls();t1();import{DurableObject as s0n}from"cloudflare:workers";var tP=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 wtn(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 wtn(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(wtn,"untilAborted");import{WorkerEntrypoint as Rar}from"cloudflare:workers";var uw=hl(mje());import{gunzipSync as Ern}from"node:zlib";var v3=class{static{a(this,"Diff")}diff(t,n,r={}){let i;typeof r=="function"?(i=r,r={}):"callback"in r&&(i=r.callback);let s=this.castInput(t,r),o=this.castInput(n,r),c=this.removeEmpty(this.tokenize(s,r)),l=this.removeEmpty(this.tokenize(o,r));return this.diffWithOptionsObj(c,l,r,i)}diffWithOptionsObj(t,n,r,i){var s;let o=a(b=>{if(b=this.postProcess(b,r),i){setTimeout(function(){i(b)},0);return}else return b},"done"),c=n.length,l=t.length,u=1,d=c+l;r.maxEditLength!=null&&(d=Math.min(d,r.maxEditLength));let p=(s=r.timeout)!==null&&s!==void 0?s:1/0,f=Date.now()+p,h=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(h[0],n,t,0,r);if(h[0].oldPos+1>=l&&g+1>=c)return o(this.buildValues(h[0].lastComponent,n,t));let y=-1/0,v=1/0,w=a(()=>{for(let b=Math.max(y,-u);b<=Math.min(v,u);b+=2){let S,k=h[b-1],E=h[b+1];k&&(h[b-1]=void 0);let _=!1;if(E){let P=E.oldPos-b;_=E&&0<=P&&P<c}let T=k&&k.oldPos+1<l;if(!_&&!T){h[b]=void 0;continue}if(!T||_&&k.oldPos<E.oldPos?S=this.addToPath(E,!0,!1,0,r):S=this.addToPath(k,!1,!0,1,r),g=this.extractCommon(S,n,t,b,r),S.oldPos+1>=l&&g+1>=c)return o(this.buildValues(S.lastComponent,n,t))||!0;h[b]=S,S.oldPos+1>=l&&(v=Math.min(v,b-1)),g+1>=c&&(y=Math.max(y,b+1))}u++},"execEditLength");if(i)a(function b(){setTimeout(function(){if(u>d||Date.now()>f)return i(void 0);w()||b()},0)},"exec")();else for(;u<=d&&Date.now()<=f;){let b=w();if(b)return b}}addToPath(t,n,r,i,s){let o=t.lastComponent;return o&&!s.oneChangePerToken&&o.added===n&&o.removed===r?{oldPos:t.oldPos+i,lastComponent:{count:o.count+1,added:n,removed:r,previousComponent:o.previousComponent}}:{oldPos:t.oldPos+i,lastComponent:{count:1,added:n,removed:r,previousComponent:o}}}extractCommon(t,n,r,i,s){let o=n.length,c=r.length,l=t.oldPos,u=l-i,d=0;for(;u+1<o&&l+1<c&&this.equals(r[l+1],n[u+1],s);)u++,l++,d++,s.oneChangePerToken&&(t.lastComponent={count:1,previousComponent:t.lastComponent,added:!1,removed:!1});return d&&!s.oneChangePerToken&&(t.lastComponent={count:d,previousComponent:t.lastComponent,added:!1,removed:!1}),t.oldPos=l,u}equals(t,n,r){return r.comparator?r.comparator(t,n):t===n||!!r.ignoreCase&&t.toLowerCase()===n.toLowerCase()}removeEmpty(t){let n=[];for(let r=0;r<t.length;r++)t[r]&&n.push(t[r]);return n}castInput(t,n){return t}tokenize(t,n){return Array.from(t)}join(t){return t.join("")}postProcess(t,n){return t}get useLongestToken(){return!1}buildValues(t,n,r){let i=[],s;for(;t;)i.push(t),s=t.previousComponent,delete t.previousComponent,t=s;i.reverse();let o=i.length,c=0,l=0,u=0;for(;c<o;c++){let d=i[c];if(d.removed)d.value=this.join(r.slice(u,u+d.count)),u+=d.count;else{if(!d.added&&this.useLongestToken){let p=n.slice(l,l+d.count);p=p.map(function(f,h){let g=r[u+h];return g.length>f.length?g:f}),d.value=this.join(p)}else d.value=this.join(n.slice(l,l+d.count));l+=d.count,d.added||(u+=d.count)}}return i}};var xoe=class extends v3{static{a(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=xtn}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
|
|
5931
5931
|
`))&&(t=t.trim()),(!r.newlineIsToken||!n.includes(`
|
|
5932
5932
|
`))&&(n=n.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
|
|
5933
5933
|
`)&&(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=Ts(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"?$3(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=>$3(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`;Ts(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=Ts(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=Ts(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=Ts(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(Ts(e,T,n,r,i,s,a,Be,c).valid){if(R!==void 0){let yt=Ts(e,R,n,r,i,s,a,`${l}/then`,c);yt.valid||ke.push({instanceLocation:a,keyword:"if",keywordLocation:Be,error:'Instance does not match "then" schema.'},...yt.errors)}}else if(U!==void 0){let yt=Ts(e,U,n,r,i,s,a,`${l}/else`,c);yt.valid||ke.push({instanceLocation:a,keyword:"if",keywordLocation:Be,error:'Instance does not match "else" schema.'},...yt.errors)}}if(d==="object"){if(b!==void 0)for(let it of b)it in e||ke.push({instanceLocation:a,keyword:"required",keywordLocation:`${l}/required`,error:`Instance does not have required property "${it}".`});let Be=Object.keys(e);if(I!==void 0&&Be.length<I&&ke.push({instanceLocation:a,keyword:"minProperties",keywordLocation:`${l}/minProperties`,error:`Instance does not have at least ${I} properties.`}),z!==void 0&&Be.length>z&&ke.push({instanceLocation:a,keyword:"maxProperties",keywordLocation:`${l}/maxProperties`,error:`Instance does not have at least ${z} properties.`}),A!==void 0){let it=`${l}/propertyNames`;for(let Ge in e){let mt=`${a}/${Oc(Ge)}`,Re=Ts(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=Ts(e,N[it],n,r,i,s,a,`${Ge}/${Oc(it)}`,c);mt.valid||ke.push({instanceLocation:a,keyword:"dependentSchemas",keywordLocation:Ge,error:`Instance has "${it}" but does not match dependant schema.`},...mt.errors)}}if(D!==void 0){let it=`${l}/dependencies`;for(let Ge in D)if(Ge in e){let mt=D[Ge];if(Array.isArray(mt))for(let Re of mt)Re in e||ke.push({instanceLocation:a,keyword:"dependencies",keywordLocation:it,error:`Instance has "${Ge}" but does not have "${Re}".`});else{let Re=Ts(e,mt,n,r,i,s,a,`${it}/${Oc(Ge)}`);Re.valid||ke.push({instanceLocation:a,keyword:"dependencies",keywordLocation:it,error:`Instance has "${Ge}" but does not match dependant schema.`},...Re.errors)}}}let Le=Object.create(null),yt=!1;if(B!==void 0){let it=`${l}/properties`;for(let Ge in B){if(!(Ge in e))continue;let mt=`${a}/${Oc(Ge)}`,Re=Ts(e[Ge],B[Ge],n,r,i,s,mt,`${it}/${Oc(Ge)}`);if(Re.valid)c[Ge]=Le[Ge]=!0;else if(yt=i,ke.push({instanceLocation:a,keyword:"properties",keywordLocation:it,error:`Property "${Ge}" does not match schema.`},...Re.errors),yt)break}}if(!yt&&$!==void 0){let it=`${l}/patternProperties`;for(let Ge in $){let mt=new RegExp(Ge,"u"),Re=$[Ge];for(let kt in e){if(!mt.test(kt))continue;let zt=`${a}/${Oc(kt)}`,pt=Ts(e[kt],Re,n,r,i,s,zt,`${it}/${Oc(Ge)}`);pt.valid?c[kt]=Le[kt]=!0:(yt=i,ke.push({instanceLocation:a,keyword:"patternProperties",keywordLocation:it,error:`Property "${kt}" matches pattern "${Ge}" but does not match associated schema.`},...pt.errors))}}}if(!yt&&G!==void 0){let it=`${l}/additionalProperties`;for(let Ge in e){if(Le[Ge])continue;let mt=`${a}/${Oc(Ge)}`,Re=Ts(e[Ge],G,n,r,i,s,mt,it);Re.valid?c[Ge]=!0:(yt=i,ke.push({instanceLocation:a,keyword:"additionalProperties",keywordLocation:it,error:`Property "${Ge}" does not match additional properties schema.`},...Re.errors))}}else if(!yt&&X!==void 0){let it=`${l}/unevaluatedProperties`;for(let Ge in e)if(!c[Ge]){let mt=`${a}/${Oc(Ge)}`,Re=Ts(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=Ts(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(V!==void 0){let it=`${l}/items`;if(Array.isArray(V)){let Ge=Math.min(V.length,Be);for(;Le<Ge;Le++){let mt=Ts(e[Le],V[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=Ts(e[Le],V,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=Ts(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=Ts(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=Ts(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)&&$3(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:bve(e);rt!==void 0&&Be<rt&&ke.push({instanceLocation:a,keyword:"minLength",keywordLocation:`${l}/minLength`,error:`String is too short (${Be} < ${rt}).`}),Ie!==void 0&&Be>Ie&&ke.push({instanceLocation:a,keyword:"maxLength",keywordLocation:`${l}/maxLength`,error:`String is too long (${Be} > ${Ie}).`}),Se!==void 0&&!new RegExp(Se,"u").test(e)&&ke.push({instanceLocation:a,keyword:"pattern",keywordLocation:`${l}/pattern`,error:"String does not match pattern."}),H!==void 0&&LV[H]&&!LV[H](e)&&ke.push({instanceLocation:a,keyword:"format",keywordLocation:`${l}/format`,error:`String does not match format "${H}".`})}return{valid:ke.length===0,errors:ke}}var UV=oe(()=>{MV();rA();jV();nA();FV();o(Ts,"validate")});var iA,xve=oe(()=>{rA();UV();iA=class{static{o(this,"Validator")}schema;draft;shortCircuit;lookup;constructor(t,n="2019-09",r=!0){this.schema=t,this.draft=n,this.shortCircuit=r,this.lookup=lh(t)}validate(t){return Ts(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,n){n&&(t={...t,$id:n}),lh(t,this.lookup)}}});var Sve=oe(()=>{MV();rA();jV();nA();wve();FV();UV();xve()});var sA,kve=oe(()=>{Sve();sA=class{static{o(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let n=new iA(t,this.draft,this.shortcircuit);return r=>{let i=n.validate(r);return i.valid?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:i.errors.map(s=>`${s.instanceLocation}: ${s.error}`).join("; ")}}}}});var ua,aA=oe(()=>{"use strict";ua={probeTimeoutMs:3e4,callTimeoutMs:6e4,maxToolsPerServer:128,maxCatalogPages:10,maxCatalogBytes:131072,maxDescriptionLength:512,maxErrorMessageChars:300,maxPublicNameLength:64,maxInstructionsLength:1024,metaToolThreshold:20}});import{createHash as rht}from"node:crypto";function sht(e){let t=e.replace(/[.*+?^${}()|[\]\\]/gu,n=>n==="*"?"\0":`\\${n}`);return new RegExp(`^${t.replaceAll("\0",".*")}$`)}function Eve(e,t,n){let r=t??"read_only";return r==="allow_all"?"allow":r==="approve_all"?"ask":n===!0?"allow":n===!1?"ask":iht.some(i=>sht(i).test(e))?"allow":"ask"}function jp(e){return e.replace(/Bearer\s+[^\s"']+/giu,"Bearer ***").replace(/(https?:\/\/[^\s"'?]+)\?[^\s"']*/giu,"$1?***").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/gu,"").slice(0,ua.maxErrorMessageChars)}function _ve(e,t){let n=`mcp__${e}__${t}`,r=n.replace(/[^A-Za-z0-9_-]/gu,"_");if(r===n&&r.length<=ua.maxPublicNameLength)return r;let i=aht(e,t),s=ua.maxPublicNameLength-i.length-1;return`${r.slice(0,s)}_${i}`}function aht(e,t){return rht("sha256").update(`${e}\0${t}`).digest("hex").slice(0,12)}function Tve(e){if(!(e==null||typeof e!="object"))try{let t=JSON.parse(JSON.stringify(e));return Ng(t),t}catch{return}}function cht(e){return oht.has(e)}function Ave(e){return e.type!=="image"||e.data===void 0||e.mimeType===void 0||!cht(e.mimeType)||!lht.test(e.data)?void 0:{data:Uint8Array.from(atob(e.data),n=>n.charCodeAt(0)),mediaType:e.mimeType}}function Ive(e){return e.some(t=>t.type==="image"&&t.data!==void 0)}function CS(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 iht,oht,lht,oA=oe(()=>{"use strict";Fs();aA();iht=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];o(sht,"globToRegExp");o(Eve,"evaluateMcpToolPolicy");o(jp,"scrubMcpErrorMessage");o(_ve,"publicToolName");o(aht,"hashSuffix");o(Tve,"supportedOutputSchema");oht=new Set(["image/png","image/jpeg"]),lht=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;o(cht,"isImageMediaType");o(Ave,"decodeImageBlock");o(Ive,"containsImage");o(CS,"mapMcpResultToContentBlocks")});var qV,Cve=oe(()=>{qV={name:"dsh-edge",version:"0.23.0-alpha.2",description:"Your DeepSeek Harness, anywhere \u2014 deploy a persistent personal coding agent to Cloudflare Workers in one command",author:"pawaca",license:"MIT",type:"module",bin:{"dsh-edge":"scripts/cli.mjs"},files:["dist","worker","scripts/*.d.mts","scripts/*.mjs","wrangler.jsonc","README.md","README.zh.md","LICENSE","THIRD_PARTY_NOTICES.md"],repository:{type:"git",url:"git+https://github.com/pawaca/dsh-edge.git",directory:"apps/dsh-edge"},homepage:"https://github.com/pawaca/dsh-edge#readme",bugs:{url:"https://github.com/pawaca/dsh-edge/issues"},keywords:["deepseek","deepseek-harness","ai-agents","byok","cloudflare-workers","durable-objects","self-hosted"],engines:{node:">=22.14.0"},publishConfig:{access:"public"},dshEdge:{upstreamVersion:"0.2.0-rc.2"},scripts:{"bundle:direct":"pnpm run web:build && pnpm --dir standalone run build:worker:direct && node standalone/scripts/promote.mjs direct","bundle:isolated":"pnpm run web:build && pnpm --dir standalone run build:worker:isolated && node standalone/scripts/promote.mjs isolated","bundle:workers":"pnpm --dir standalone run build && pnpm --dir standalone run verify && node standalone/scripts/promote.mjs all",dev:"pnpm run bundle:direct && node scripts/dev.mjs direct","dev:isolated":"pnpm run bundle:isolated && node scripts/dev.mjs isolated","dev:container":"pnpm run bundle:isolated && node scripts/dev.mjs container","dsh-edge":"node scripts/cli.mjs","example:install":"node examples/install-keyless.mjs","install:cloudflare":"pnpm run bundle:workers && node scripts/cli.mjs install","legal:write":"node scripts/legal-files.mjs write","pack:verify":"node scripts/verify-packed.mjs",prepack:"node scripts/legal-files.mjs verify && pnpm run bundle:workers","web:build":"pnpm --dir standalone run build:web && node standalone/scripts/promote.mjs web",test:"vitest run --root ../.. --project edge-runtime","test:integration":"pnpm run bundle:workers && node tests/run-session-integration.mjs","test:container":"pnpm run bundle:isolated && node tests/container.integration.mjs","test:snapshot":"vitest run --root ../.. --config apps/dsh-edge/vitest.snapshot.config.ts",typecheck:"tsc --noEmit"},dependencies:{"@clack/prompts":"1.7.0","compare-versions":"6.1.1",execa:"^10.0.1","jsonc-parser":"^3.3.1",wrangler:"4.129.0",yaml:"2.9.0"},devDependencies:{"@cfworker/json-schema":"^4.1.1","@cloudflare/computer":"0.3.1","@cloudflare/workers-types":"5.20260904.1","@deepseek-ai/cordis":"4.0.4","@deepseek-ai/cosmokit":"1.8.5","@deepseek-ai/dsh-agent":"0.2.0-rc.2","@deepseek-ai/dsh-agent-instructions":"0.2.0-rc.2","@deepseek-ai/dsh-agent-loop":"0.2.0-rc.2","@deepseek-ai/dsh-anonymous-user-id":"0.2.0-rc.2","@deepseek-ai/dsh-api-gateway":"0.2.0-rc.2","@deepseek-ai/dsh-api-job-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-remotes":"0.2.0-rc.2","@deepseek-ai/dsh-api-session-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-settings-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-workspace-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-workspace-files":"0.2.0-rc.2","@deepseek-ai/dsh-attachment":"0.2.0-rc.2","@deepseek-ai/dsh-brand":"0.2.0-rc.2","@deepseek-ai/dsh-client-locale":"0.2.0-rc.2","@deepseek-ai/dsh-client-store":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-chat":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-conversation":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-settings":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-settings-general":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-theme":"0.2.0-rc.2","@deepseek-ai/dsh-command-compact":"0.2.0-rc.2","@deepseek-ai/dsh-command-goal":"0.2.0-rc.2","@deepseek-ai/dsh-commands":"0.2.0-rc.2","@deepseek-ai/dsh-compaction":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-basic":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-image-offload":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-tool-result-pruner":"0.2.0-rc.2","@deepseek-ai/dsh-credentials":"0.2.0-rc.2","@deepseek-ai/dsh-file-reference":"0.2.0-rc.2","@deepseek-ai/dsh-fs":"0.2.0-rc.2","@deepseek-ai/dsh-fs-observation-policy":"0.2.0-rc.2","@deepseek-ai/dsh-goal":"0.2.0-rc.2","@deepseek-ai/dsh-goal-round-driver":"0.2.0-rc.2","@deepseek-ai/dsh-home-paths":"0.2.0-rc.2","@deepseek-ai/dsh-host-directory-picker":"0.2.0-rc.2","@deepseek-ai/dsh-host-plugin-inventory":"0.2.0-rc.2","@deepseek-ai/dsh-invariants":"0.2.0-rc.2","@deepseek-ai/dsh-jobs":"0.2.0-rc.2","@deepseek-ai/dsh-jobs-local":"0.2.0-rc.2","@deepseek-ai/dsh-launch-environment":"0.2.0-rc.2","@deepseek-ai/dsh-llm":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek-api-key":"0.2.0-rc.2","@deepseek-ai/dsh-llm-retry":"0.2.0-rc.2","@deepseek-ai/dsh-message-feedback":"0.2.0-rc.2","@deepseek-ai/dsh-output-retention":"0.2.0-rc.2","@deepseek-ai/dsh-plan-mode":"0.2.0-rc.2","@deepseek-ai/dsh-ptc-runtime":"0.2.0-rc.2","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.0-rc.2","@deepseek-ai/dsh-sandbox":"0.2.0-rc.2","@deepseek-ai/dsh-schedule":"0.2.0-rc.2","@deepseek-ai/dsh-scope":"0.2.0-rc.2","@deepseek-ai/dsh-session":"0.2.0-rc.2","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.0-rc.2","@deepseek-ai/dsh-session-format":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-catalog":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.0-rc.2","@deepseek-ai/dsh-session-persistence":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection-cache":"0.2.0-rc.2","@deepseek-ai/dsh-session-stats":"0.2.0-rc.2","@deepseek-ai/dsh-session-query":"0.2.0-rc.2","@deepseek-ai/dsh-session-reference":"0.2.0-rc.2","@deepseek-ai/dsh-session-title":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-llm":"0.2.0-rc.2","@deepseek-ai/dsh-settings":"0.2.0-rc.2","@deepseek-ai/dsh-skill":"0.2.0-rc.2","@deepseek-ai/dsh-spill":"0.2.0-rc.2","@deepseek-ai/dsh-spill-policy":"0.2.0-rc.2","@deepseek-ai/dsh-storage":"0.2.0-rc.2","@deepseek-ai/dsh-storage-domain":"0.2.0-rc.2","@deepseek-ai/dsh-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-in-process-driver":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-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 v0,Rve,Ove,RS=oe(()=>{"use strict";Cve();v0=qV.version,Rve=qV.dshEdge.upstreamVersion,Ove=`npx dsh-edge@${v0.includes("-")?"next":"latest"} upgrade`});function hht(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 mht(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function ch(e){let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("MCP server URL must use http: or https: protocol.");let n=t.hostname.toLowerCase(),r=n.endsWith(".")?n.slice(0,-1):n,i=r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r;if(!(i==="localhost"||i==="127.0.0.1"||i==="::1")){for(let s of dht)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(mht(i)){let s=hht(i),a=s??i;for(let l of pht)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 fht)if(l.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function ght(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function Nve(e,t,n){ch(e);let r=new tA(new URL(e),{requestInit:{headers:ght(t),signal:n},fetch:w0}),i=new Q8({name:"dsh-edge",version:v0},{capabilities:{},jsonSchemaValidator:yht});return await i.connect(r),{client:i,close:o(async()=>{await i.close().catch(()=>{})},"close")}}async function $ve(e,t,n){let r=AbortSignal.timeout(ua.probeTimeoutMs),i;try{i=await Nve(t,n,r)}catch(l){throw new Error(jp(l instanceof Error?l.message:String(l)))}let{client:s,close:a}=i;try{let l=[],c=new Set,u=new Set,d;for(let h=0;h<ua.maxCatalogPages;h++){let g=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let y of g.tools){if(l.length>=ua.maxToolsPerServer)break;let v=_ve(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=Tve(y.outputSchema);l.push({name:y.name,publicName:v,description:y.description??"",inputSchema:y.inputSchema??{type:"object"},...S!==void 0?{outputSchema:S}:{},...b!==void 0?{annotations:{readOnlyHint:b}}:{}})}if(l.length>=ua.maxToolsPerServer||(d=g.nextCursor??void 0,d===void 0))break;if(u.has(d))throw new Error("Server repeated a tools/list continuation cursor");u.add(d)}let p=s.getServerVersion?.(),m=s.getInstructions?.();return{tools:l,serverInfo:p?{name:p.name,version:p.version}:void 0,instructions:typeof m=="string"&&m.length>0?m.slice(0,ua.maxInstructionsLength):void 0}}finally{await a()}}async function lA(e,t,n,r,i,s){let a=s??ua.callTimeoutMs,l=i?AbortSignal.any([i,AbortSignal.timeout(a)]):AbortSignal.timeout(a),c;try{c=await Nve(e,r,l)}catch(u){throw new Error(jp(u instanceof Error?u.message:String(u)))}try{let u=await c.client.callTool({name:t,arguments:n},void 0,{signal:l});return{content:u.content??[],structuredContent:u.structuredContent,isError:u.isError===!0}}catch(u){throw new Error(jp(u instanceof Error?u.message:String(u)))}finally{await c.close()}}var dht,pht,fht,yht,w0,OS=oe(()=>{"use strict";M3e();mve();kve();oA();aA();RS();dht=[".internal",".local",".localhost"],pht=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],fht=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];o(hht,"extractMappedIPv4");o(mht,"isIpAddress");o(ch,"assertSafeUrl");o(ght,"buildHeaders");yht=new sA,w0=o(async(e,t)=>{let n=await globalThis.fetch(e,{...t,redirect:"manual"});if(n.status>=300&&n.status<400)throw new Error(`MCP server returned HTTP ${String(n.status)} redirect; redirects are blocked for security.`);return n},"noRedirectFetch");o(Nve,"connectClient");o($ve,"probe");o(lA,"callTool")});import{Buffer as vht}from"node:buffer";function Sht(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&xht.has(e.code)}function Dve(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&bht.has(e.code)}function Mve(e,t,n){let r=vht.from(e,"base64");if(e.length===0&&t==="reject"||r.toString("base64")!==e)throw new or(n==="INVALID_IMAGE_BASE64"?"Image upload is not canonical base64.":"File upload is not canonical base64.",n);return new Uint8Array(r)}function kht(e){return Mve(e,"reject","INVALID_IMAGE_BASE64")}function Eht(e){return{data:kht(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function NS(e,t){return e.saveImages(t.map(Eht))}async function _ht(e,t){return e.saveFile({data:Mve(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function Lve(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 BV(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 Pve,wht,bht,xht,or,zV,uh=oe(()=>{Gn();Pve=["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"],wht=[...Pve,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],bht=new Set(Pve),xht=new Set(wht),or=class extends Error{static{o(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};o(Sht,"isAttachmentError");o(Dve,"isImageAdmissionError");o(Mve,"decodeCanonicalBase64");o(kht,"decodeBase64");o(Eht,"saveInput");o(NS,"admitEncodedImages");o(_ht,"admitEncodedFile");o(Lve,"requestImageDimensions");o(BV,"longEdgeDimensions");zV=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 or("Image batch exceeds the configured image-count limit.","TOO_MANY_IMAGES");if(e.reduce((i,s)=>i+s.data.byteLength,0)>n)throw new or("Image batch exceeds the configured aggregate image-byte limit.","IMAGES_TOO_LARGE");for(let i of e)if(!r.includes(i.mediaType))throw new or(`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 NS(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 _ht(this,e)}isAttachmentError(e){return Sht(e)}imageHostPath(e){}saveFile(e){return Promise.reject(new or("The mounted attachment provider cannot store verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}saveFileStream(e){return Promise.reject(new or("The mounted attachment provider cannot stream verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}async*readFileStream(e,t){t?.throwIfAborted(),await Promise.reject(new or("The mounted attachment provider cannot read verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}fileHostPath(e){}readImageRequest(e,t,n){return n?.throwIfAborted(),Promise.reject(new or("The mounted attachment provider cannot derive model-request images.","ATTACHMENT_PROJECTION_UNSUPPORTED"))}}});var uA={};cn(uA,{buildAuthorizationUrl:()=>Pht,discoverEndpoints:()=>Nht,exchangeCode:()=>Dht,isTokenExpired:()=>Lht,refreshToken:()=>Mht,registerClient:()=>$ht});function qve(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 Oht(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 Nht(e){let t=AbortSignal.timeout(cA),n=new URL(e),r=n.pathname==="/"?"/.well-known/oauth-protected-resource":`/.well-known/oauth-protected-resource${n.pathname}`,i=new URL(r,n.origin);ch(i.href);let s=await w0(i.href,{signal:t});if(!s.ok)throw new Error(`PRM discovery failed: HTTP ${s.status}`);let l=(await s.json()).authorization_servers?.[0];if(typeof l!="string")throw new Error("No authorization server in PRM");let c=new URL(l),u=c.pathname==="/"?"/.well-known/oauth-authorization-server":`/.well-known/oauth-authorization-server${c.pathname}`,d=new URL(u,c.origin);ch(d.href);let p=await w0(d.href,{signal:t});if(!p.ok)throw new Error(`AS metadata failed: HTTP ${p.status}`);let m=await p.json();if(typeof m.authorization_endpoint!="string"||typeof m.token_endpoint!="string")throw new Error("Missing required endpoints in AS metadata");return{authorization:m.authorization_endpoint,token:m.token_endpoint,registration:m.registration_endpoint}}async function $ht(e,t,n){let r=AbortSignal.timeout(cA);ch(e);let i=await w0(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_name:n,redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}),signal:r});if(!i.ok)throw new Error(`DCR failed: HTTP ${i.status}`);let s=await i.json();if(typeof s.client_id!="string")throw new Error("DCR response missing client_id");return{clientId:s.client_id,clientSecret:s.client_secret}}async function Pht(e,t,n,r,i){let s=qve(32),a=qve(64),l=await Oht(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 Dht(e,t,n,r,i,s){let a=AbortSignal.timeout(cA),l=new URLSearchParams({grant_type:"authorization_code",code:n,redirect_uri:i,client_id:t.clientId,code_verifier:r});s!==void 0&&l.set("resource",s),t.clientSecret!==void 0&&l.set("client_secret",t.clientSecret),ch(e);let c=await w0(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:l.toString(),signal:a});if(!c.ok)throw new Error(`Token exchange failed: HTTP ${c.status}`);return Bve(await c.json())}async function Mht(e,t,n,r){let i=AbortSignal.timeout(cA),s=new URLSearchParams({grant_type:"refresh_token",refresh_token:n,client_id:t.clientId});r!==void 0&&s.set("resource",r),t.clientSecret!==void 0&&s.set("client_secret",t.clientSecret),ch(e);let a=await w0(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:s.toString(),signal:i});if(!a.ok)throw new Error(`Token refresh failed: HTTP ${a.status}`);return Bve(await a.json())}function Bve(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 Lht(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var cA,dA=oe(()=>{"use strict";OS();cA=1e4;o(qve,"randomString");o(Oht,"sha256Base64Url");o(Nht,"discoverEndpoints");o($ht,"registerClient");o(Pht,"buildAuthorizationUrl");o(Dht,"exchangeCode");o(Mht,"refreshToken");o(Bve,"parseTokenResponse");o(Lht,"isTokenExpired")});var jn,Jve,P3=oe(()=>{Gn();dr();jn=class extends jr{static{o(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},Jve=class extends St{static{o(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new jn("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function LS(e){return SA.test(e)}function kA(e){return e.invocation.modelInvocable}function M3(e){return e.invocation.userInvocable}function lG(e){let t=x1t(e);return[`<skill_content name="${S1t(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 iht,oht,lht,oA=oe(()=>{"use strict";Fs();aA();iht=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];o(sht,"globToRegExp");o(Eve,"evaluateMcpToolPolicy");o(jp,"scrubMcpErrorMessage");o(_ve,"publicToolName");o(aht,"hashSuffix");o(Tve,"supportedOutputSchema");oht=new Set(["image/png","image/jpeg"]),lht=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;o(cht,"isImageMediaType");o(Ave,"decodeImageBlock");o(Ive,"containsImage");o(CS,"mapMcpResultToContentBlocks")});var qV,Cve=oe(()=>{qV={name:"dsh-edge",version:"0.23.0",description:"Your DeepSeek Harness, anywhere \u2014 deploy a persistent personal coding agent to Cloudflare Workers in one command",author:"pawaca",license:"MIT",type:"module",bin:{"dsh-edge":"scripts/cli.mjs"},files:["dist","worker","scripts/*.d.mts","scripts/*.mjs","wrangler.jsonc","README.md","README.zh.md","LICENSE","THIRD_PARTY_NOTICES.md"],repository:{type:"git",url:"git+https://github.com/pawaca/dsh-edge.git",directory:"apps/dsh-edge"},homepage:"https://github.com/pawaca/dsh-edge#readme",bugs:{url:"https://github.com/pawaca/dsh-edge/issues"},keywords:["deepseek","deepseek-harness","ai-agents","byok","cloudflare-workers","durable-objects","self-hosted"],engines:{node:">=22.14.0"},publishConfig:{access:"public"},dshEdge:{upstreamVersion:"0.2.0-rc.2"},scripts:{"bundle:direct":"pnpm run web:build && pnpm --dir standalone run build:worker:direct && node standalone/scripts/promote.mjs direct","bundle:isolated":"pnpm run web:build && pnpm --dir standalone run build:worker:isolated && node standalone/scripts/promote.mjs isolated","bundle:workers":"pnpm --dir standalone run build && pnpm --dir standalone run verify && node standalone/scripts/promote.mjs all",dev:"pnpm run bundle:direct && node scripts/dev.mjs direct","dev:isolated":"pnpm run bundle:isolated && node scripts/dev.mjs isolated","dev:container":"pnpm run bundle:isolated && node scripts/dev.mjs container","dsh-edge":"node scripts/cli.mjs","example:install":"node examples/install-keyless.mjs","install:cloudflare":"pnpm run bundle:workers && node scripts/cli.mjs install","legal:write":"node scripts/legal-files.mjs write","pack:verify":"node scripts/verify-packed.mjs",prepack:"node scripts/legal-files.mjs verify && pnpm run bundle:workers","web:build":"pnpm --dir standalone run build:web && node standalone/scripts/promote.mjs web",test:"vitest run --root ../.. --project edge-runtime","test:integration":"pnpm run bundle:workers && node tests/run-session-integration.mjs","test:container":"pnpm run bundle:isolated && node tests/container.integration.mjs","test:snapshot":"vitest run --root ../.. --config apps/dsh-edge/vitest.snapshot.config.ts",typecheck:"tsc --noEmit"},dependencies:{"@clack/prompts":"1.7.0","compare-versions":"6.1.1",execa:"^10.0.1","jsonc-parser":"^3.3.1",wrangler:"4.129.0",yaml:"2.9.0"},devDependencies:{"@cfworker/json-schema":"^4.1.1","@cloudflare/computer":"0.3.1","@cloudflare/workers-types":"5.20260904.1","@deepseek-ai/cordis":"4.0.4","@deepseek-ai/cosmokit":"1.8.5","@deepseek-ai/dsh-agent":"0.2.0-rc.2","@deepseek-ai/dsh-agent-instructions":"0.2.0-rc.2","@deepseek-ai/dsh-agent-loop":"0.2.0-rc.2","@deepseek-ai/dsh-anonymous-user-id":"0.2.0-rc.2","@deepseek-ai/dsh-api-gateway":"0.2.0-rc.2","@deepseek-ai/dsh-api-job-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-remotes":"0.2.0-rc.2","@deepseek-ai/dsh-api-session-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-settings-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-workspace-controller":"0.2.0-rc.2","@deepseek-ai/dsh-api-workspace-files":"0.2.0-rc.2","@deepseek-ai/dsh-attachment":"0.2.0-rc.2","@deepseek-ai/dsh-brand":"0.2.0-rc.2","@deepseek-ai/dsh-client-locale":"0.2.0-rc.2","@deepseek-ai/dsh-client-store":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-chat":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-conversation":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-settings":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-settings-general":"0.2.0-rc.2","@deepseek-ai/dsh-client-ui-theme":"0.2.0-rc.2","@deepseek-ai/dsh-command-compact":"0.2.0-rc.2","@deepseek-ai/dsh-command-goal":"0.2.0-rc.2","@deepseek-ai/dsh-commands":"0.2.0-rc.2","@deepseek-ai/dsh-compaction":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-basic":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-image-offload":"0.2.0-rc.2","@deepseek-ai/dsh-compaction-tool-result-pruner":"0.2.0-rc.2","@deepseek-ai/dsh-credentials":"0.2.0-rc.2","@deepseek-ai/dsh-file-reference":"0.2.0-rc.2","@deepseek-ai/dsh-fs":"0.2.0-rc.2","@deepseek-ai/dsh-fs-observation-policy":"0.2.0-rc.2","@deepseek-ai/dsh-goal":"0.2.0-rc.2","@deepseek-ai/dsh-goal-round-driver":"0.2.0-rc.2","@deepseek-ai/dsh-home-paths":"0.2.0-rc.2","@deepseek-ai/dsh-host-directory-picker":"0.2.0-rc.2","@deepseek-ai/dsh-host-plugin-inventory":"0.2.0-rc.2","@deepseek-ai/dsh-invariants":"0.2.0-rc.2","@deepseek-ai/dsh-jobs":"0.2.0-rc.2","@deepseek-ai/dsh-jobs-local":"0.2.0-rc.2","@deepseek-ai/dsh-launch-environment":"0.2.0-rc.2","@deepseek-ai/dsh-llm":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-llm-deepseek-api-key":"0.2.0-rc.2","@deepseek-ai/dsh-llm-retry":"0.2.0-rc.2","@deepseek-ai/dsh-message-feedback":"0.2.0-rc.2","@deepseek-ai/dsh-output-retention":"0.2.0-rc.2","@deepseek-ai/dsh-plan-mode":"0.2.0-rc.2","@deepseek-ai/dsh-ptc-runtime":"0.2.0-rc.2","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.0-rc.2","@deepseek-ai/dsh-sandbox":"0.2.0-rc.2","@deepseek-ai/dsh-schedule":"0.2.0-rc.2","@deepseek-ai/dsh-scope":"0.2.0-rc.2","@deepseek-ai/dsh-session":"0.2.0-rc.2","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.0-rc.2","@deepseek-ai/dsh-session-format":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-catalog":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.0-rc.2","@deepseek-ai/dsh-session-persistence":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection-cache":"0.2.0-rc.2","@deepseek-ai/dsh-session-stats":"0.2.0-rc.2","@deepseek-ai/dsh-session-query":"0.2.0-rc.2","@deepseek-ai/dsh-session-reference":"0.2.0-rc.2","@deepseek-ai/dsh-session-title":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-llm":"0.2.0-rc.2","@deepseek-ai/dsh-settings":"0.2.0-rc.2","@deepseek-ai/dsh-skill":"0.2.0-rc.2","@deepseek-ai/dsh-spill":"0.2.0-rc.2","@deepseek-ai/dsh-spill-policy":"0.2.0-rc.2","@deepseek-ai/dsh-storage":"0.2.0-rc.2","@deepseek-ai/dsh-storage-domain":"0.2.0-rc.2","@deepseek-ai/dsh-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-in-process-driver":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-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 v0,Rve,Ove,RS=oe(()=>{"use strict";Cve();v0=qV.version,Rve=qV.dshEdge.upstreamVersion,Ove=`npx dsh-edge@${v0.includes("-")?"next":"latest"} upgrade`});function hht(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 mht(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function ch(e){let t=new URL(e);if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("MCP server URL must use http: or https: protocol.");let n=t.hostname.toLowerCase(),r=n.endsWith(".")?n.slice(0,-1):n,i=r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r;if(!(i==="localhost"||i==="127.0.0.1"||i==="::1")){for(let s of dht)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(mht(i)){let s=hht(i),a=s??i;for(let l of pht)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 fht)if(l.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function ght(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function Nve(e,t,n){ch(e);let r=new tA(new URL(e),{requestInit:{headers:ght(t),signal:n},fetch:w0}),i=new Q8({name:"dsh-edge",version:v0},{capabilities:{},jsonSchemaValidator:yht});return await i.connect(r),{client:i,close:o(async()=>{await i.close().catch(()=>{})},"close")}}async function $ve(e,t,n){let r=AbortSignal.timeout(ua.probeTimeoutMs),i;try{i=await Nve(t,n,r)}catch(l){throw new Error(jp(l instanceof Error?l.message:String(l)))}let{client:s,close:a}=i;try{let l=[],c=new Set,u=new Set,d;for(let h=0;h<ua.maxCatalogPages;h++){let g=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let y of g.tools){if(l.length>=ua.maxToolsPerServer)break;let v=_ve(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=Tve(y.outputSchema);l.push({name:y.name,publicName:v,description:y.description??"",inputSchema:y.inputSchema??{type:"object"},...S!==void 0?{outputSchema:S}:{},...b!==void 0?{annotations:{readOnlyHint:b}}:{}})}if(l.length>=ua.maxToolsPerServer||(d=g.nextCursor??void 0,d===void 0))break;if(u.has(d))throw new Error("Server repeated a tools/list continuation cursor");u.add(d)}let p=s.getServerVersion?.(),m=s.getInstructions?.();return{tools:l,serverInfo:p?{name:p.name,version:p.version}:void 0,instructions:typeof m=="string"&&m.length>0?m.slice(0,ua.maxInstructionsLength):void 0}}finally{await a()}}async function lA(e,t,n,r,i,s){let a=s??ua.callTimeoutMs,l=i?AbortSignal.any([i,AbortSignal.timeout(a)]):AbortSignal.timeout(a),c;try{c=await Nve(e,r,l)}catch(u){throw new Error(jp(u instanceof Error?u.message:String(u)))}try{let u=await c.client.callTool({name:t,arguments:n},void 0,{signal:l});return{content:u.content??[],structuredContent:u.structuredContent,isError:u.isError===!0}}catch(u){throw new Error(jp(u instanceof Error?u.message:String(u)))}finally{await c.close()}}var dht,pht,fht,yht,w0,OS=oe(()=>{"use strict";M3e();mve();kve();oA();aA();RS();dht=[".internal",".local",".localhost"],pht=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],fht=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];o(hht,"extractMappedIPv4");o(mht,"isIpAddress");o(ch,"assertSafeUrl");o(ght,"buildHeaders");yht=new sA,w0=o(async(e,t)=>{let n=await globalThis.fetch(e,{...t,redirect:"manual"});if(n.status>=300&&n.status<400)throw new Error(`MCP server returned HTTP ${String(n.status)} redirect; redirects are blocked for security.`);return n},"noRedirectFetch");o(Nve,"connectClient");o($ve,"probe");o(lA,"callTool")});import{Buffer as vht}from"node:buffer";function Sht(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&xht.has(e.code)}function Dve(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&bht.has(e.code)}function Mve(e,t,n){let r=vht.from(e,"base64");if(e.length===0&&t==="reject"||r.toString("base64")!==e)throw new or(n==="INVALID_IMAGE_BASE64"?"Image upload is not canonical base64.":"File upload is not canonical base64.",n);return new Uint8Array(r)}function kht(e){return Mve(e,"reject","INVALID_IMAGE_BASE64")}function Eht(e){return{data:kht(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function NS(e,t){return e.saveImages(t.map(Eht))}async function _ht(e,t){return e.saveFile({data:Mve(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function Lve(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 BV(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 Pve,wht,bht,xht,or,zV,uh=oe(()=>{Gn();Pve=["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"],wht=[...Pve,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],bht=new Set(Pve),xht=new Set(wht),or=class extends Error{static{o(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};o(Sht,"isAttachmentError");o(Dve,"isImageAdmissionError");o(Mve,"decodeCanonicalBase64");o(kht,"decodeBase64");o(Eht,"saveInput");o(NS,"admitEncodedImages");o(_ht,"admitEncodedFile");o(Lve,"requestImageDimensions");o(BV,"longEdgeDimensions");zV=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 or("Image batch exceeds the configured image-count limit.","TOO_MANY_IMAGES");if(e.reduce((i,s)=>i+s.data.byteLength,0)>n)throw new or("Image batch exceeds the configured aggregate image-byte limit.","IMAGES_TOO_LARGE");for(let i of e)if(!r.includes(i.mediaType))throw new or(`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 NS(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 _ht(this,e)}isAttachmentError(e){return Sht(e)}imageHostPath(e){}saveFile(e){return Promise.reject(new or("The mounted attachment provider cannot store verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}saveFileStream(e){return Promise.reject(new or("The mounted attachment provider cannot stream verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}async*readFileStream(e,t){t?.throwIfAborted(),await Promise.reject(new or("The mounted attachment provider cannot read verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}fileHostPath(e){}readImageRequest(e,t,n){return n?.throwIfAborted(),Promise.reject(new or("The mounted attachment provider cannot derive model-request images.","ATTACHMENT_PROJECTION_UNSUPPORTED"))}}});var uA={};cn(uA,{buildAuthorizationUrl:()=>Pht,discoverEndpoints:()=>Nht,exchangeCode:()=>Dht,isTokenExpired:()=>Lht,refreshToken:()=>Mht,registerClient:()=>$ht});function qve(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 Oht(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 Nht(e){let t=AbortSignal.timeout(cA),n=new URL(e),r=n.pathname==="/"?"/.well-known/oauth-protected-resource":`/.well-known/oauth-protected-resource${n.pathname}`,i=new URL(r,n.origin);ch(i.href);let s=await w0(i.href,{signal:t});if(!s.ok)throw new Error(`PRM discovery failed: HTTP ${s.status}`);let l=(await s.json()).authorization_servers?.[0];if(typeof l!="string")throw new Error("No authorization server in PRM");let c=new URL(l),u=c.pathname==="/"?"/.well-known/oauth-authorization-server":`/.well-known/oauth-authorization-server${c.pathname}`,d=new URL(u,c.origin);ch(d.href);let p=await w0(d.href,{signal:t});if(!p.ok)throw new Error(`AS metadata failed: HTTP ${p.status}`);let m=await p.json();if(typeof m.authorization_endpoint!="string"||typeof m.token_endpoint!="string")throw new Error("Missing required endpoints in AS metadata");return{authorization:m.authorization_endpoint,token:m.token_endpoint,registration:m.registration_endpoint}}async function $ht(e,t,n){let r=AbortSignal.timeout(cA);ch(e);let i=await w0(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_name:n,redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}),signal:r});if(!i.ok)throw new Error(`DCR failed: HTTP ${i.status}`);let s=await i.json();if(typeof s.client_id!="string")throw new Error("DCR response missing client_id");return{clientId:s.client_id,clientSecret:s.client_secret}}async function Pht(e,t,n,r,i){let s=qve(32),a=qve(64),l=await Oht(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 Dht(e,t,n,r,i,s){let a=AbortSignal.timeout(cA),l=new URLSearchParams({grant_type:"authorization_code",code:n,redirect_uri:i,client_id:t.clientId,code_verifier:r});s!==void 0&&l.set("resource",s),t.clientSecret!==void 0&&l.set("client_secret",t.clientSecret),ch(e);let c=await w0(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:l.toString(),signal:a});if(!c.ok)throw new Error(`Token exchange failed: HTTP ${c.status}`);return Bve(await c.json())}async function Mht(e,t,n,r){let i=AbortSignal.timeout(cA),s=new URLSearchParams({grant_type:"refresh_token",refresh_token:n,client_id:t.clientId});r!==void 0&&s.set("resource",r),t.clientSecret!==void 0&&s.set("client_secret",t.clientSecret),ch(e);let a=await w0(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:s.toString(),signal:i});if(!a.ok)throw new Error(`Token refresh failed: HTTP ${a.status}`);return Bve(await a.json())}function Bve(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 Lht(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var cA,dA=oe(()=>{"use strict";OS();cA=1e4;o(qve,"randomString");o(Oht,"sha256Base64Url");o(Nht,"discoverEndpoints");o($ht,"registerClient");o(Pht,"buildAuthorizationUrl");o(Dht,"exchangeCode");o(Mht,"refreshToken");o(Bve,"parseTokenResponse");o(Lht,"isTokenExpired")});var jn,Jve,P3=oe(()=>{Gn();dr();jn=class extends jr{static{o(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},Jve=class extends St{static{o(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new jn("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function LS(e){return SA.test(e)}function kA(e){return e.invocation.modelInvocable}function M3(e){return e.invocation.userInvocable}function lG(e){let t=x1t(e);return[`<skill_content name="${S1t(e.name)}">`,"<skill_resources>",...t,"</skill_resources>","","<skill_instructions>",e.content,"</skill_instructions>","</skill_content>"].join(`
|
|
156
156
|
`)}function x1t(e){let t=e.resourceBase;if(t===void 0)return[`Resources for this skill are managed by provider "${D3(e.provider)}".`,"Load referenced resources only as needed."];switch(t.kind){case"directory":return[`Base directory for this skill: ${D3(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: ${D3(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: ${D3(t.description)}`,"Load referenced resources only as needed."];default:return ai(t,"SkillResourceBase.kind")}}function S1t(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<")}function D3(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function E1t(e,t){if(Array.isArray(e))return{candidates:e,complete:!0};if(e===null||typeof e!="object")throw ywe(t);let n=e;if(!Array.isArray(n.candidates)||typeof n.complete!="boolean")throw ywe(t);return n}function ywe(e){return new TypeError(`skill provider "${e}" list() must return an array or { candidates, complete } observation`)}function T1t(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:b1t,locator:e,...e.path!==void 0?{path:e.path}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}function A1t(e,t){if(typeof e.name!="string")throw new TypeError(`skill provider "${t}" returned a non-string skill name`);if(!SA.test(e.name))throw new Error(`skill provider "${t}" returned invalid skill name "${e.name}"`);if(typeof e.description!="string")throw new TypeError(`skill provider "${t}" returned skill "${e.name}" with a non-string description`);if(e.description.length===0)throw new Error(`skill provider "${t}" returned skill "${e.name}" without a description`);if(cG(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 I1t(e){if(!SA.test(e.name))throw new Error(`invalid skill name "${e.name}"`);if(e.description.length===0)throw new Error(`skill "${e.name}" requires a description`);cG(e.invocation,`runtime skill "${e.name}"`)}function C1t(e){let t=e.name,n=e.description,r=e.whenToUse,i=e.invocation,s=e.source,a=e.provider,l=e.content,c=e.path;if(typeof t!="string")throw new TypeError("loaded skill name must be a string");if(!SA.test(t))throw new Error(`loaded skill has invalid name "${t}"`);if(typeof n!="string")throw new TypeError(`loaded skill "${t}" description must be a string`);if(n.length===0)throw new Error(`loaded skill "${t}" requires a description`);if(cG(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 R1t(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 cG(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 O1t(e,t){return xwe(e.name,t.name)}function xwe(e,t){return e<t?-1:e>t?1:0}function N1t(e,t){return e.candidate.rank-t.candidate.rank||e.providerOrder-t.providerOrder||e.localOrder-t.localOrder}function $1t(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 vwe(e,t){return t===void 0?e:(MS(t),new Promise((n,r)=>{let i=o(()=>{t.removeEventListener("abort",s)},"cleanup"),s=o(()=>{i(),r(xA(t.reason))},"onAbort");t.addEventListener("abort",s,{once:!0}),e.then(a=>{i(),n(a)},a=>{i(),r(xA(a))})}))}function MS(e){if(e?.aborted===!0)throw xA(e.reason)}function xA(e){try{if(e instanceof Error)return e}catch{}return new Error(bA(e))}function bA(e){try{return String(e)}catch{return"[unrenderable thrown value]"}}var SA,gwe,w1t,wA,b1t,wwe,k1t,bwe,_1t,x0=oe(()=>{Gn();Bi();gl();un();SA=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,gwe=128,w1t=2,wA="runtime",b1t=250,wwe=600;o(LS,"isSkillName");o(kA,"isModelInvocable");o(M3,"isUserInvocable");o(lG,"renderSkillContent");o(x1t,"renderResourceHint");o(S1t,"escapeAttr");o(D3,"escapeText");k1t=class{static{o(this,"SkillLayer")}providers;runtime=new Map;constructor(e){this.providers=new bp(t=>new Error(e===void 0?`a skill provider named "${t}" is already registered`:`a skill provider named "${t}" is already registered in this scope`))}isEmpty(){return this.providers.isEmpty()&&this.runtime.size===0}},bwe=class extends St{static{o(this,"SkillRegistry")}static Config=L.object({collectCacheMaxEntries:L.number().default(gwe)});collectCacheMaxEntries;layers=new xp(e=>new k1t(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??gwe,$1t("collectCacheMaxEntries",this.collectCacheMaxEntries)}registerProvider(e){let t=new AbortController,n,r,i={signal:t.signal,invalidate:o(()=>{let s=n;s!==void 0&&s.layer.providers.get(s.name)?.provider===r&&this.invalidateCache()},"invalidate")};try{r=e(i);let s=r.name;if(s===wA)throw new Error(`"${wA}" is reserved for runtime skill registrations`);let a=this.nextProviderOrder;return this.nextProviderOrder+=1,this.layers.effect(this.ctx,l=>{let c=l.providers.insert(s,{provider:r,order:a});return n={layer:l,name:s},()=>{n=void 0,c(),t.abort(new Error(`skill provider "${s}" disposed`))}},{label:"skills.registerProvider()"})}catch(s){throw t.abort(s),s}}register(e){I1t(e);let t=ml(this.ctx),n=t===void 0?this.layers.global:this.layers.peek(t);if(n!==void 0&&n.runtime.has(e.name))return this.ctx.logger.warn(`runtime skill "${e.name}" ignored because it is already registered`),()=>{};let r={...e,invocation:e.invocation??{modelInvocable:!0,userInvocable:!0},provider:e.provider??wA};return this.layers.effect(this.ctx,i=>(i.runtime.set(r.name,r),()=>{i.runtime.delete(r.name)}),{label:"skills.register()"})}async list(e={}){return(await this.snapshot(e)).skills}async snapshot(e={}){let t=await this.collect(e);return{skills:[...t.entries.values()].map(n=>R1t(n.candidate)).sort(O1t),complete:t.cacheable}}async get(e,t={}){if(!LS(e))return;let n=await this.collect(t);MS(t.signal);let r=n.entries.get(e);if(r===void 0)return;let i=await vwe(r.provider.get(r.candidate,t),t.signal);if(i!==void 0){if(C1t(i),i.name!==r.candidate.name){this.invalidateEntry(r);return}return i}}async collect(e){MS(e.signal);let t=1;for(;;){let n=this.revision,r=this.collectCacheKey(e.cwd,ax(e.scope),n),i=this.collectCache.get(r);if(i!==void 0)return{entries:i,cacheable:!0};let s=await this.collectFresh(e);if(MS(e.signal),n!==this.revision){if(t<w1t){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(N1t);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){MS(t.signal);let n=[],r=!0,i=0;for(let s of[...e.runtime.values()].sort((a,l)=>xwe(a.name,l.name)))n.push({candidate:T1t(s),provider:_1t,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 vwe(s.list(t),t.signal)}catch(d){if(t.signal?.aborted===!0)throw xA(t.signal.reason);r=!1,this.ctx.logger.warn(`skill provider "${s.name}" skipped: ${bA(d)}`)}if(c===void 0)continue;let u=E1t(c,s.name);u.complete||(r=!1);for(let d of u.candidates)A1t(d,s.name),n.push({candidate:d,provider:s,providerOrder:a,localOrder:l,layer:e}),l+=1}return{entries:n,cacheable:r}}invalidateCache(){this.revision+=1,this.collectCache.clear(),this.notifyChange()}invalidateEntry(e){e.layer.providers.get(e.provider.name)?.provider===e.provider&&this.invalidateCache()}scopeId(e){let t=this.scopeIds.get(e);return t===void 0&&(t=this.nextScopeId,this.nextScopeId+=1,this.scopeIds.set(e,t)),t}collectCacheKey(e,t,n){return JSON.stringify({cwd:e,scopes:t.map(r=>this.scopeId(r)),revision:n})}notifyChange(){for(let e of this.ctx.events.dispatch("emit",["skills/change"]))try{let t=e();Promise.resolve(t).catch(n=>{this.ctx.logger.warn(`skills/change listener rejected: ${bA(n)}`)})}catch(t){this.ctx.logger.warn(`skills/change listener threw: ${bA(t)}`)}}};o(E1t,"normalizeProviderObservation");o(ywe,"invalidProviderObservation");_1t={name:wA,list(){return Promise.resolve([])},get(e){return Promise.resolve(e.locator)}};o(T1t,"runtimeCandidate");o(A1t,"validateCandidate");o(I1t,"validateRuntimeSkill");o(C1t,"validateDefinition");o(R1t,"toSummary");o(cG,"validateInvocation");o(O1t,"compareSkillSummary");o(xwe,"compareCodePoints");o(N1t,"compareIndexedCandidates");o($1t,"assertPositiveInteger");o(vwe,"waitWithAbort");o(MS,"throwIfAborted");o(xA,"toError");o(bA,"errorMessage")});var Eu,F3=oe(()=>{Eu=class{static{o(this,"Deque")}buffer=new Array(16);head=0;count=0;get size(){return this.count}pushBack(e){this.ensureCapacity();let t=this.head+this.count;this.buffer[t<this.buffer.length?t:t-this.buffer.length]=e,this.count+=1}pushFront(e){this.ensureCapacity(),this.head=this.head===0?this.buffer.length-1:this.head-1,this.buffer[this.head]=e,this.count+=1}popFront(){if(this.count===0)return;let e=this.buffer[this.head];return this.buffer[this.head]=void 0,this.head+=1,this.head===this.buffer.length&&(this.head=0),this.count-=1,this.compact(),e}clear(){this.buffer=new Array(16),this.head=0,this.count=0}ensureCapacity(){this.count<this.buffer.length||this.resize(this.buffer.length*2)}compact(){if(this.count===0){this.head=0;return}this.buffer.length>16&&this.count<=this.buffer.length/4&&this.resize(Math.max(16,this.buffer.length/2))}resize(e){let t=new Array(e),n=this.head;for(let r=0;r<this.count;r+=1)t[r]=this.buffer[n],n+=1,n===this.buffer.length&&(n=0);this.buffer=t,this.head=0}}});var ph,Bbe,KG=oe(()=>{Gn();ph=class extends Error{static{o(this,"DirectoryPickerError")}code;path;constructor(e,t,n){super(n),this.code=e,this.path=t,this.name="DirectoryPickerError"}},Bbe=class extends St{static{o(this,"DirectoryPicker")}constructor(e){super(e,"directoryPicker")}}});var wSe=we((XAn,G9)=>{var vSe=vSe||function(e){return Buffer.from(e).toString("base64")};function Awt(e){var t=this,n=Math.round,r=Math.floor,i=new Array(64),s=new Array(64),a=new Array(64),l=new Array(64),c,u,d,p,m=new Array(65535),h=new Array(65535),g=new Array(64),y=new Array(64),v=[],b=0,S=7,k=new Array(64),x=new Array(64),E=new Array(64),T=new Array(256),R=new Array(2048),U,H=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],B=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],$=[0,1,2,3,4,5,6,7,8,9,10,11],G=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],X=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],I=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],z=[0,1,2,3,4,5,6,7,8,9,10,11],A=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],C=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function N(ie){for(var Me=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99],ke=0;ke<64;ke++){var lt=r((Me[ke]*ie+50)/100);lt<1?lt=1:lt>255&&(lt=255),i[H[ke]]=lt}for(var Be=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99],Le=0;Le<64;Le++){var yt=r((Be[Le]*ie+50)/100);yt<1?yt=1:yt>255&&(yt=255),s[H[Le]]=yt}for(var it=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379],Ge=0,mt=0;mt<8;mt++)for(var Re=0;Re<8;Re++)a[Ge]=1/(i[H[Ge]]*it[mt]*it[Re]*8),l[Ge]=1/(s[H[Ge]]*it[mt]*it[Re]*8),Ge++}o(N,"initQuantTables");function D(ie,Me){for(var ke=0,lt=0,Be=new Array,Le=1;Le<=16;Le++){for(var yt=1;yt<=ie[Le];yt++)Be[Me[lt]]=[],Be[Me[lt]][0]=ke,Be[Me[lt]][1]=Le,lt++,ke++;ke*=2}return Be}o(D,"computeHuffmanTbl");function P(){c=D(B,$),u=D(I,z),d=D(G,X),p=D(A,C)}o(P,"initHuffmanTbl");function V(){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(V,"initCategoryNumber");function J(){for(var ie=0;ie<256;ie++)R[ie]=19595*ie,R[ie+256>>0]=38470*ie,R[ie+512>>0]=7471*ie+32768,R[ie+768>>0]=-11059*ie,R[ie+1024>>0]=-21709*ie,R[ie+1280>>0]=32768*ie+8421375,R[ie+1536>>0]=-27439*ie,R[ie+1792>>0]=-5329*ie}o(J,"initRGBYUVTable");function K(ie){for(var Me=ie[0],ke=ie[1]-1;ke>=0;)Me&1<<ke&&(b|=1<<S),ke--,S--,S<0&&(b==255?(F(255),F(0)):F(b),S=7,b=0)}o(K,"writeBits");function F(ie){v.push(ie)}o(F,"writeByte");function ee(ie){F(ie>>8&255),F(ie&255)}o(ee,"writeWord");function ge(ie,Me){var ke,lt,Be,Le,yt,it,Ge,mt,Re=0,kt,zt=8,pt=64;for(kt=0;kt<zt;++kt){ke=ie[Re],lt=ie[Re+1],Be=ie[Re+2],Le=ie[Re+3],yt=ie[Re+4],it=ie[Re+5],Ge=ie[Re+6],mt=ie[Re+7];var yn=ke+mt,Bt=ke-mt,jt=lt+Ge,ae=lt-Ge,$e=Be+it,Ve=Be-it,at=Le+yt,Rt=Le-yt,Ye=yn+at,rn=yn-at,Qt=jt+$e,vn=jt-$e;ie[Re]=Ye+Qt,ie[Re+4]=Ye-Qt;var Dt=(vn+rn)*.707106781;ie[Re+2]=rn+Dt,ie[Re+6]=rn-Dt,Ye=Rt+Ve,Qt=Ve+ae,vn=ae+Bt;var Or=(Ye-vn)*.382683433,Mr=.5411961*Ye+Or,es=1.306562965*vn+Or,Ei=Qt*.707106781,cr=Bt+Ei,ts=Bt-Ei;ie[Re+5]=ts+Mr,ie[Re+3]=ts-Mr,ie[Re+1]=cr+es,ie[Re+7]=cr-es,Re+=8}for(Re=0,kt=0;kt<zt;++kt){ke=ie[Re],lt=ie[Re+8],Be=ie[Re+16],Le=ie[Re+24],yt=ie[Re+32],it=ie[Re+40],Ge=ie[Re+48],mt=ie[Re+56];var Es=ke+mt,Bs=ke-mt,ra=lt+Ge,Ft=lt-Ge,Dn=Be+it,ia=Be-it,Ja=Le+yt,wa=Le-yt,ba=Es+Ja,Ca=Es-Ja,Ya=ra+Dn,Eo=ra-Dn;ie[Re]=ba+Ya,ie[Re+32]=ba-Ya;var gc=(Eo+Ca)*.707106781;ie[Re+16]=Ca+gc,ie[Re+48]=Ca-gc,ba=wa+ia,Ya=ia+Ft,Eo=Ft+Bs;var Rl=(ba-Eo)*.382683433,Vu=.5411961*ba+Rl,Gu=1.306562965*Eo+Rl,Zu=Ya*.707106781,Ku=Bs+Zu,kf=Bs-Zu;ie[Re+40]=kf+Vu,ie[Re+24]=kf-Vu,ie[Re+8]=Ku+Gu,ie[Re+56]=Ku-Gu,Re++}var np;for(kt=0;kt<pt;++kt)np=ie[kt]*Me[kt],g[kt]=np>0?np+.5|0:np-.5|0;return g}o(ge,"fDCTQuant");function ve(){ee(65504),ee(16),F(74),F(70),F(73),F(70),F(0),F(1),F(1),F(0),ee(1),ee(1),F(0),F(0)}o(ve,"writeAPP0");function le(ie){if(ie){ee(65505),ie[0]===69&&ie[1]===120&&ie[2]===105&&ie[3]===102?ee(ie.length+2):(ee(ie.length+5+2),F(69),F(120),F(105),F(102),F(0));for(var Me=0;Me<ie.length;Me++)F(ie[Me])}}o(le,"writeAPP1");function xe(ie,Me){ee(65472),ee(17),F(8),ee(Me),ee(ie),F(3),F(1),F(17),F(0),F(2),F(17),F(1),F(3),F(17),F(1)}o(xe,"writeSOF0");function Ee(){ee(65499),ee(132),F(0);for(var ie=0;ie<64;ie++)F(i[ie]);F(1);for(var Me=0;Me<64;Me++)F(s[Me])}o(Ee,"writeDQT");function ce(){ee(65476),ee(418),F(0);for(var ie=0;ie<16;ie++)F(B[ie+1]);for(var Me=0;Me<=11;Me++)F($[Me]);F(16);for(var ke=0;ke<16;ke++)F(G[ke+1]);for(var lt=0;lt<=161;lt++)F(X[lt]);F(1);for(var Be=0;Be<16;Be++)F(I[Be+1]);for(var Le=0;Le<=11;Le++)F(z[Le]);F(17);for(var yt=0;yt<16;yt++)F(A[yt+1]);for(var it=0;it<=161;it++)F(C[it])}o(ce,"writeDHT");function ue(ie){typeof ie>"u"||ie.constructor!==Array||ie.forEach(Me=>{if(typeof Me=="string"){ee(65534);var ke=Me.length;ee(ke+2);var lt;for(lt=0;lt<ke;lt++)F(Me.charCodeAt(lt))}})}o(ue,"writeCOM");function st(){ee(65498),ee(12),F(3),F(1),F(0),F(2),F(17),F(3),F(17),F(0),F(63),F(0)}o(st,"writeSOS");function He(ie,Me,ke,lt,Be){for(var Le=Be[0],yt=Be[240],it,Ge=16,mt=63,Re=64,kt=ge(ie,Me),zt=0;zt<Re;++zt)y[H[zt]]=kt[zt];var pt=y[0]-ke;ke=y[0],pt==0?K(lt[0]):(it=32767+pt,K(lt[h[it]]),K(m[it]));for(var yn=63;yn>0&&y[yn]==0;yn--);if(yn==0)return K(Le),ke;for(var Bt=1,jt;Bt<=yn;){for(var ae=Bt;y[Bt]==0&&Bt<=yn;++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 yn!=mt&&K(Le),ke}o(He,"processDU");function rt(){for(var ie=String.fromCharCode,Me=0;Me<256;Me++)T[Me]=ie(Me)}o(rt,"initCharLookupTable"),this.encode=function(ie,Me){var ke=new Date().getTime();Me&&Ie(Me),v=new Array,b=0,S=7,ee(65496),ve(),ue(ie.comments),le(ie.exifBuffer),Ee(),xe(ie.width,ie.height),ce(),st();var lt=0,Be=0,Le=0;b=0,S=7,this.encode.displayName="_encode_";for(var yt=ie.data,it=ie.width,Ge=ie.height,mt=it*4,Re=it*3,kt,zt=0,pt,yn,Bt,jt,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++],yn=yt[ae++],Bt=yt[ae++],k[at]=(R[pt]+R[yn+256>>0]+R[Bt+512>>0]>>16)-128,x[at]=(R[pt+768>>0]+R[yn+1024>>0]+R[Bt+1280>>0]>>16)-128,E[at]=(R[pt+1280>>0]+R[yn+1536>>0]+R[Bt+1792>>0]>>16)-128;lt=He(k,a,lt,c,d),Be=He(x,l,Be,u,p),Le=He(E,l,Le,u,p),kt+=32}zt+=8}if(S>=0){var Rt=[];Rt[1]=S+1,Rt[0]=(1<<S+1)-1,K(Rt)}if(ee(65497),typeof G9>"u")return new Uint8Array(v);return Buffer.from(v);var Ye,rn};function Ie(ie){if(ie<=0&&(ie=1),ie>100&&(ie=100),U!=ie){var Me=0;ie<50?Me=Math.floor(5e3/ie):Me=Math.floor(200-ie*2),N(Me),U=ie}}o(Ie,"setQuality");function Se(){var ie=new Date().getTime();e||(e=50),rt(),P(),V(),J(),Ie(e);var Me=new Date().getTime()-ie}o(Se,"init"),Se()}o(Awt,"JPEGEncoder");typeof G9<"u"?G9.exports=ySe:typeof window<"u"&&(window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].encode=ySe);function ySe(e,t){typeof t>"u"&&(t=50);var n=new Awt(t),r=n.encode(e,t);return{data:r,width:e.width,height:e.height}}o(ySe,"encode")});var xSe=we((e9n,EK)=>{var kK=o((function(){"use strict";var t=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),n=4017,r=799,i=3406,s=2276,a=1567,l=3784,c=5793,u=2896;function d(){}o(d,"constructor");function p(S,k){for(var x=0,E=[],T,R,U=16;U>0&&!S[U-1];)U--;E.push({children:[],index:0});var H=E[0],B;for(T=0;T<U;T++){for(R=0;R<S[T];R++){for(H=E.pop(),H.children[H.index]=k[x];H.index>0;){if(E.length===0)throw new Error("Could not recreate Huffman Table");H=E.pop()}for(H.index++,E.push(H);E.length<=T;)E.push(B={children:[],index:0}),H.children[H.index]=B.children,H=B;x++}T+1<U&&(E.push(B={children:[],index:0}),H.children[H.index]=B.children,H=B)}return E[0].children}o(p,"buildHuffmanTable");function m(S,k,x,E,T,R,U,H,B,$){var G=x.precision,X=x.samplesPerLine,I=x.scanLines,z=x.mcusPerLine,A=x.progressive,C=x.maxH,N=x.maxV,D=k,P=0,V=0;function J(){if(V>0)return V--,P>>V&1;if(P=S[k++],P==255){var Re=S[k++];if(Re)throw new Error("unexpected marker: "+(P<<8|Re).toString(16))}return V=7,P>>>7}o(J,"readBit");function K(Re){for(var kt=Re,zt;(zt=J())!==null;){if(kt=kt[zt],typeof kt=="number")return kt;if(typeof kt!="object")throw new Error("invalid huffman sequence")}return null}o(K,"decodeHuffman");function F(Re){for(var kt=0;Re>0;){var zt=J();if(zt===null)return;kt=kt<<1|zt,Re--}return kt}o(F,"receive");function ee(Re){var kt=F(Re);return kt>=1<<Re-1?kt:kt+(-1<<Re)+1}o(ee,"receiveAndExtend");function ge(Re,kt){var zt=K(Re.huffmanTableDC),pt=zt===0?0:ee(zt);kt[0]=Re.pred+=pt;for(var yn=1;yn<64;){var Bt=K(Re.huffmanTableAC),jt=Bt&15,ae=Bt>>4;if(jt===0){if(ae<15)break;yn+=16;continue}yn+=ae;var $e=t[yn];kt[$e]=ee(jt),yn++}}o(ge,"decodeBaseline");function ve(Re,kt){var zt=K(Re.huffmanTableDC),pt=zt===0?0:ee(zt)<<B;kt[0]=Re.pred+=pt}o(ve,"decodeDCFirst");function le(Re,kt){kt[0]|=J()<<B}o(le,"decodeDCSuccessive");var xe=0;function Ee(Re,kt){if(xe>0){xe--;return}for(var zt=R,pt=U;zt<=pt;){var yn=K(Re.huffmanTableAC),Bt=yn&15,jt=yn>>4;if(Bt===0){if(jt<15){xe=F(jt)+(1<<jt)-1;break}zt+=16;continue}zt+=jt;var ae=t[zt];kt[ae]=ee(Bt)*(1<<B),zt++}}o(Ee,"decodeACFirst");var ce=0,ue;function st(Re,kt){for(var zt=R,pt=U,yn=0;zt<=pt;){var Bt=t[zt],jt=kt[Bt]<0?-1:1;switch(ce){case 0:var ae=K(Re.huffmanTableAC),$e=ae&15,yn=ae>>4;if($e===0)yn<15?(xe=F(yn)+(1<<yn),ce=4):(yn=16,ce=1);else{if($e!==1)throw new Error("invalid ACn encoding");ue=ee($e),ce=yn?2:3}continue;case 1:case 2:kt[Bt]?kt[Bt]+=(J()<<B)*jt:(yn--,yn===0&&(ce=ce==2?3:0));break;case 3:kt[Bt]?kt[Bt]+=(J()<<B)*jt:(kt[Bt]=ue<<B,ce=0);break;case 4:kt[Bt]&&(kt[Bt]+=(J()<<B)*jt);break}zt++}ce===4&&(xe--,xe===0&&(ce=0))}o(st,"decodeACSuccessive");function He(Re,kt,zt,pt,yn){var Bt=zt/z|0,jt=zt%z,ae=Bt*Re.v+pt,$e=jt*Re.h+yn;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,yn=zt%Re.blocksPerLine;Re.blocks[pt]===void 0&&$.tolerantDecoding||kt(Re,Re.blocks[pt][yn])}o(rt,"decodeBlock");var Ie=E.length,Se,ie,Me,ke,lt,Be;A?R===0?Be=H===0?ve:le:Be=H===0?Ee:st:Be=ge;var Le=0,yt,it;Ie==1?it=E[0].blocksPerLine*E[0].blocksPerColumn:it=z*x.mcusPerColumn,T||(T=it);for(var Ge,mt;Le<it;){for(ie=0;ie<Ie;ie++)E[ie].pred=0;if(xe=0,Ie==1)for(Se=E[0],lt=0;lt<T;lt++)rt(Se,Be,Le),Le++;else for(lt=0;lt<T;lt++){for(ie=0;ie<Ie;ie++)for(Se=E[ie],Ge=Se.h,mt=Se.v,Me=0;Me<mt;Me++)for(ke=0;ke<Ge;ke++)He(Se,Be,Le,Me,ke);if(Le++,Le===it)break}if(Le===it)do{if(S[k]===255&&S[k+1]!==0)break;k+=1}while(k<S.length-2);if(V=0,yt=S[k]<<8|S[k+1],yt<65280)throw new Error("marker was not found");if(yt>=65488&&yt<=65495)k+=2;else break}return k-D}o(m,"decodeScan");function h(S,k){var x=[],E=k.blocksPerLine,T=k.blocksPerColumn,R=E<<3,U=new Int32Array(64),H=new Uint8Array(64);function B(D,P,V){var J=k.quantizationTable,K,F,ee,ge,ve,le,xe,Ee,ce,ue=V,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*V[st+0]+8192>>14,ue[0+rt]=ce,ue[8+rt]=ce,ue[16+rt]=ce,ue[24+rt]=ce,ue[32+rt]=ce,ue[40+rt]=ce,ue[48+rt]=ce,ue[56+rt]=ce;continue}K=c*ue[0+rt]+2048>>12,F=c*ue[32+rt]+2048>>12,ee=ue[16+rt],ge=ue[48+rt],ve=u*(ue[8+rt]-ue[56+rt])+2048>>12,Ee=u*(ue[8+rt]+ue[56+rt])+2048>>12,le=ue[24+rt],xe=ue[40+rt],ce=K-F+1>>1,K=K+F+1>>1,F=ce,ce=ee*l+ge*a+2048>>12,ee=ee*a-ge*l+2048>>12,ge=ce,ce=ve-xe+1>>1,ve=ve+xe+1>>1,xe=ce,ce=Ee+le+1>>1,le=Ee-le+1>>1,Ee=ce,ce=K-ge+1>>1,K=K+ge+1>>1,ge=ce,ce=F-ee+1>>1,F=F+ee+1>>1,ee=ce,ce=ve*s+Ee*i+2048>>12,ve=ve*i-Ee*s+2048>>12,Ee=ce,ce=le*r+xe*n+2048>>12,le=le*n-xe*r+2048>>12,xe=ce,ue[0+rt]=K+Ee,ue[56+rt]=K-Ee,ue[8+rt]=F+xe,ue[48+rt]=F-xe,ue[16+rt]=ee+le,ue[40+rt]=ee-le,ue[24+rt]=ge+ve,ue[32+rt]=ge-ve}for(st=0;st<64;++st){var Ie=128+(ue[st]+8>>4);P[st]=Ie<0?0:Ie>255?255:Ie}}o(B,"quantizeAndInverse"),b(R*T*8);for(var $,G,X=0;X<T;X++){var I=X<<3;for($=0;$<8;$++)x.push(new Uint8Array(R));for(var z=0;z<E;z++){B(k.blocks[X][z],H,U);var A=0,C=z<<3;for(G=0;G<8;G++){var N=x[I+G];for($=0;$<8;$++)N[C+$]=H[A++]}}}return x}o(h,"buildComponentData");function g(S){return S<0?0:S>255?255:S}o(g,"clampTo8bit"),d.prototype={load:o(function(k){var x=new XMLHttpRequest;x.open("GET",k,!0),x.responseType="arraybuffer",x.onload=(function(){var E=new Uint8Array(x.response||x.mozResponseArrayBuffer);this.parse(E),this.onload&&this.onload()}).bind(this),x.send(null)},"load"),parse:o(function(k){var x=this.opts.maxResolutionInMP*1e3*1e3,E=0,T=k.length;function R(){var ae=k[E]<<8|k[E+1];return E+=2,ae}o(R,"readUint16");function U(){var ae=R(),$e=k.subarray(E,E+ae-2);return E+=$e.length,$e}o(U,"readDataBlock");function H(ae){var $e=1,Ve=1,at,Rt;for(Rt in ae.components)ae.components.hasOwnProperty(Rt)&&(at=ae.components[Rt],$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(Rt in ae.components)if(ae.components.hasOwnProperty(Rt)){at=ae.components[Rt];var Qt=Math.ceil(Math.ceil(ae.samplesPerLine/8)*at.h/$e),vn=Math.ceil(Math.ceil(ae.scanLines/8)*at.v/Ve),Dt=Ye*at.h,Or=rn*at.v,Mr=Or*Dt,es=[];b(Mr*256);for(var Ei=0;Ei<Or;Ei++){for(var cr=[],ts=0;ts<Dt;ts++)cr.push(new Int32Array(64));es.push(cr)}at.blocksPerLine=Qt,at.blocksPerColumn=vn,at.blocks=es}ae.maxH=$e,ae.maxV=Ve,ae.mcusPerLine=Ye,ae.mcusPerColumn=rn}o(H,"prepareComponents");var B=null,$=null,G=null,X,I,z=[],A=[],C=[],N=[],D=R(),P=-1;if(this.comments=[],D!=65496)throw new Error("SOI not found");for(D=R();D!=65497;){var V,J,K;switch(D){case 65280:break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var F=U();if(D===65534){var ee=String.fromCharCode.apply(null,F);this.comments.push(ee)}D===65504&&F[0]===74&&F[1]===70&&F[2]===73&&F[3]===70&&F[4]===0&&(B={version:{major:F[5],minor:F[6]},densityUnits:F[7],xDensity:F[8]<<8|F[9],yDensity:F[10]<<8|F[11],thumbWidth:F[12],thumbHeight:F[13],thumbData:F.subarray(14,14+3*F[12]*F[13])}),D===65505&&F[0]===69&&F[1]===120&&F[2]===105&&F[3]===102&&F[4]===0&&(this.exifBuffer=F.subarray(5,F.length)),D===65518&&F[0]===65&&F[1]===100&&F[2]===111&&F[3]===98&&F[4]===101&&F[5]===0&&($={version:F[6],flags0:F[7]<<8|F[8],flags1:F[9]<<8|F[10],transformCode:F[11]});break;case 65499:for(var ge=R(),ve=ge+E-2;E<ve;){var le=k[E++];b(256);var xe=new Int32Array(64);if(le>>4===0)for(J=0;J<64;J++){var Ee=t[J];xe[Ee]=k[E++]}else if(le>>4===1)for(J=0;J<64;J++){var Ee=t[J];xe[Ee]=R()}else throw new Error("DQT: invalid table spec");z[le&15]=xe}break;case 65472:case 65473:case 65474:R(),X={},X.extended=D===65473,X.progressive=D===65474,X.precision=k[E++],X.scanLines=R(),X.samplesPerLine=R(),X.components={},X.componentsOrder=[];var ce=X.scanLines*X.samplesPerLine;if(ce>x){var ue=Math.ceil((ce-x)/1e6);throw new Error(`maxResolutionInMP limit exceeded by ${ue}MP`)}var st=k[E++],He,rt=0,Ie=0;for(V=0;V<st;V++){He=k[E];var Se=k[E+1]>>4,ie=k[E+1]&15,Me=k[E+2];if(Se<=0||ie<=0)throw new Error("Invalid sampling factor, expected values above 0");X.componentsOrder.push(He),X.components[He]={h:Se,v:ie,quantizationIdx:Me},E+=3}H(X),A.push(X);break;case 65476:var ke=R();for(V=2;V<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];V+=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(V=0;V<Ge;V++){Re=X.components[k[E++]];var kt=k[E++];Re.huffmanTableDC=N[kt>>4],Re.huffmanTableAC=C[kt&15],mt.push(Re)}var zt=k[E++],pt=k[E++],yn=k[E++],Bt=m(k,E,X,mt,I,zt,pt,yn>>4,yn&15,this.opts);E+=Bt;break;case 65535:k[E]!==255&&E--;break;default:if(k[E-3]==255&&k[E-2]>=192&&k[E-2]<=254){E-=3;break}else if(D===224||D==225){if(P!==-1)throw new Error(`first unknown JPEG marker at offset ${P.toString(16)}, second unknown JPEG marker ${D.toString(16)} at offset ${(E-1).toString(16)}`);P=E-1;let 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 V=0;V<A.length;V++){var jt=A[V].components;for(var J in jt)jt[J].quantizationTable=z[jt[J].quantizationIdx],delete jt[J].quantizationIdx}this.width=X.samplesPerLine,this.height=X.scanLines,this.jfif=B,this.adobe=$,this.components=[];for(var V=0;V<X.componentsOrder.length;V++){var Re=X.components[X.componentsOrder[V]];this.components.push({lines:h(X,Re),scaleX:Re.h/X.maxH,scaleY:Re.v/X.maxV})}},"parse"),getData:o(function(k,x){var E=this.width/k,T=this.height/x,R,U,H,B,$,G,X,I,z,A,C=0,N,D,P,V,J,K,F,ee,ge,ve,le,xe=k*x*this.components.length;b(xe);var Ee=new Uint8Array(xe);switch(this.components.length){case 1:for(R=this.components[0],A=0;A<x;A++)for($=R.lines[0|A*R.scaleY*T],z=0;z<k;z++)N=$[0|z*R.scaleX*E],Ee[C++]=N;break;case 2:for(R=this.components[0],U=this.components[1],A=0;A<x;A++)for($=R.lines[0|A*R.scaleY*T],G=U.lines[0|A*U.scaleY*T],z=0;z<k;z++)N=$[0|z*R.scaleX*E],Ee[C++]=N,N=G[0|z*U.scaleX*E],Ee[C++]=N;break;case 3:for(le=!0,this.adobe&&this.adobe.transformCode?le=!0:typeof this.opts.colorTransform<"u"&&(le=!!this.opts.colorTransform),R=this.components[0],U=this.components[1],H=this.components[2],A=0;A<x;A++)for($=R.lines[0|A*R.scaleY*T],G=U.lines[0|A*U.scaleY*T],X=H.lines[0|A*H.scaleY*T],z=0;z<k;z++)le?(N=$[0|z*R.scaleX*E],D=G[0|z*U.scaleX*E],P=X[0|z*H.scaleX*E],ee=g(N+1.402*(P-128)),ge=g(N-.3441363*(D-128)-.71413636*(P-128)),ve=g(N+1.772*(D-128))):(ee=$[0|z*R.scaleX*E],ge=G[0|z*U.scaleX*E],ve=X[0|z*H.scaleX*E]),Ee[C++]=ee,Ee[C++]=ge,Ee[C++]=ve;break;case 4:if(!this.adobe)throw new Error("Unsupported color mode (4 components)");for(le=!1,this.adobe&&this.adobe.transformCode?le=!0:typeof this.opts.colorTransform<"u"&&(le=!!this.opts.colorTransform),R=this.components[0],U=this.components[1],H=this.components[2],B=this.components[3],A=0;A<x;A++)for($=R.lines[0|A*R.scaleY*T],G=U.lines[0|A*U.scaleY*T],X=H.lines[0|A*H.scaleY*T],I=B.lines[0|A*B.scaleY*T],z=0;z<k;z++)le?(N=$[0|z*R.scaleX*E],D=G[0|z*U.scaleX*E],P=X[0|z*H.scaleX*E],V=I[0|z*B.scaleX*E],J=255-g(N+1.402*(P-128)),K=255-g(N-.3441363*(D-128)-.71413636*(P-128)),F=255-g(N+1.772*(D-128))):(J=$[0|z*R.scaleX*E],K=G[0|z*U.scaleX*E],F=X[0|z*H.scaleX*E],V=I[0|z*B.scaleX*E]),Ee[C++]=255-J,Ee[C++]=255-K,Ee[C++]=255-F,Ee[C++]=255-V;break;default:throw new Error("Unsupported color mode")}return Ee},"getData"),copyToImageData:o(function(k,x){var E=k.width,T=k.height,R=k.data,U=this.getData(E,T),H=0,B=0,$,G,X,I,z,A,C,N,D;switch(this.components.length){case 1:for(G=0;G<T;G++)for($=0;$<E;$++)X=U[H++],R[B++]=X,R[B++]=X,R[B++]=X,x&&(R[B++]=255);break;case 3:for(G=0;G<T;G++)for($=0;$<E;$++)C=U[H++],N=U[H++],D=U[H++],R[B++]=C,R[B++]=N,R[B++]=D,x&&(R[B++]=255);break;case 4:for(G=0;G<T;G++)for($=0;$<E;$++)z=U[H++],A=U[H++],X=U[H++],I=U[H++],C=255-g(z*(1-I/255)+I),N=255-g(A*(1-I/255)+I),D=255-g(X*(1-I/255)+I),R[B++]=C,R[B++]=N,R[B++]=D,x&&(R[B++]=255);break;default:throw new Error("Unsupported color mode")}},"copyToImageData")};var y=0,v=0;function b(S=0){var k=y+S;if(k>v){var x=Math.ceil((k-v)/1024/1024);throw new Error(`maxMemoryUsageInMB limit exceeded by at least ${x}MB`)}y=k}return o(b,"requestMemoryAllocation"),d.resetMaxMemoryUsage=function(S){y=0,v=S},d.getBytesAllocated=function(){return y},d.requestMemoryAllocation=b,d}),"jpegImage")();typeof EK<"u"?EK.exports=bSe:typeof window<"u"&&(window["jpeg-js"]=window["jpeg-js"]||{},window["jpeg-js"].decode=bSe);function bSe(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 kK;s.opts=r,kK.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),s.parse(i);var a=r.formatAsRGBA?4:3,l=s.width*s.height*a;try{kK.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(bSe,"decode")});var kSe=we((n9n,SSe)=>{var Iwt=wSe(),Cwt=xSe();SSe.exports={encode:Iwt,decode:Cwt}});function i4e(e,t){let n=0,r=0,s=o(a=>{let l;for(let[c,u]of a.entries()){let d=u;if(u.type==="image"){if(n===t[r]){if(u.offloaded===!0)throw new Error(`image/offload: image index ${n} is already offloaded`);d={...u,offloaded:!0},r+=1}n+=1}d!==u&&(l??=a.slice(0,c)),l?.push(d)}return l??a},"visit")(e.content);if(r!==t.length)throw new Error(`image/offload: image index ${t[r]} does not exist`);return fn({...e,content:s})}var s4e=oe(()=>{Bi();o(i4e,"offloadMessageImages")});function a4e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function o4e(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0&&!Object.is(e,-0)}var fI,SJ=oe(()=>{s4e();o(a4e,"isRecord");o(o4e,"isIndex");fI={type:"image/offload",project(e,t){let n=e.data;if(!a4e(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(!a4e(s)||Object.keys(s).length!==2||!o4e(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(!o4e(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,i4e(u,s.imageIndexes))}return r}}});var II,TEe=oe(()=>{SJ();II=[fI]});async function $Ee(e,t,n){let r=n===void 0?void 0:{signal:n},i=await e.open(t,"read",r),s;try{s=await i.read(0,void 0,r)}catch(l){try{await i.close()}catch{}throw l}await i.close();let{events:a}=s;return{eventState:s.eventState,header:i.header,inheritedEventCount:i.inheritedEventCount,events:[...a,...T5(a)]}}function iY(e,t){if(e.id!==t.id||e.createdAt!==t.createdAt||e.cwd!==t.cwd||e.parentSession!==t.parentSession||e.isSeeded!==t.isSeeded||(e.delegationDepth??0)!==(t.delegationDepth??0))throw new Cr(`session source headers conflict for session "${e.id}"`,"SESSION_QUERY_SOURCE_CONFLICT")}function CI(e,t,n,r){try{r?.throwIfAborted();let i=n(t);return r?.throwIfAborted(),{sessionId:e,status:"fulfilled",value:i}}catch(i){return r?.aborted&&r.throwIfAborted(),{sessionId:e,status:"rejected",reason:i}}}function sY(e){return{header:e.header,events:e.snapshotEvents()}}function RI(e,t){return e.map(n=>t.get(n))}async function aY(e,t){try{return(await e.list(t===void 0?void 0:{signal:t})).map(n=>n.header)}catch(n){throw t?.aborted&&t.throwIfAborted(),new Cr(`session persistence listing failed: ${cY(n)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:n})}}async function AEe(e,t,n){try{return await $Ee(e,t,n)}catch(r){throw n?.aborted&&n.throwIfAborted(),r instanceof Error&&r.name==="SessionPersistenceCorruptionError"?new Cr(`stored session "${t}" is corrupt: ${cY(r)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:r}):new Cr(`failed to read stored session "${t}": ${cY(r)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:r})}}function IEe(e){return{header:structuredClone(e.header),inheritedEventCount:e.inheritedEventCount,events:e.snapshotEvents().map(t=>structuredClone(t))}}function Mkt(e,t){return t.header.createdAt-e.header.createdAt||e.header.id.localeCompare(t.header.id)}function OI(e){return new Cr(`session "${e}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND")}function cY(e){return e instanceof Error?e.message:"unknown error"}function Zk(e){if(e?.aborted===!0)throw new Cr("session observation was aborted","SESSION_QUERY_ABORTED",{cause:e.reason})}function CEe(e,t){return REe(t,"SessionPersistenceNotFoundError")?uY(e,t):REe(t,"SessionPersistenceCorruptionError")?new Cr(`stored session "${e}" is corrupt: ${t.message}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:t}):new Cr(`failed to observe session "${e}": ${NI(t)}`,"SESSION_QUERY_PERSISTENCE_FAILED",{cause:t})}function uY(e,t){return new Cr(`session "${e}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND",t===void 0?void 0:{cause:t})}function NI(e){return e instanceof Error?e.message:"unknown error"}function REe(e,t){return e instanceof Error&&e.name===t}function jkt(e){switch(e.type){case"user/message":return oY(e.data.content);case"assistant/message":return oY(e.data.message.content);case"tool/call":return Kk([e.data.name,e.data.arguments]);case"tool/result":return Kk([oY(e.data.message.content),e.data.error?.name??"",e.data.error?.code??""]);case"todo/write":return Kk(e.data.todos.flatMap(t=>[t.status,t.content]));case"turn/end":return Fkt(e.data.reason);case"turn/start":case"step/start":case"step/end":case"assistant/attempt":case"request/header":return"";default:return""}}function Fkt(e){switch(e.kind){case"error":return Kk(["error",e.error.message]);case"aborted":return"aborted";case"max-tokens":case"interrupted":return e.kind;case"completed":return"";default:return""}}function oY(e){return Kk(e.flatMap(Ukt))}function Ukt(e){switch(e.type){case"text":return[e.text];case"reasoning":return[];case"tool-call":return[e.name,e.arguments];default:return[]}}function Kk(e){return e.map(t=>t.trim()).filter(Boolean).join(`
|
|
157
157
|
`)}function pY(e,t){let n=qkt(t),r=[];for(let i of t){let s=jkt(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 qkt(e){let t;try{t=qD(e,II)}catch(r){throw new Cr(`invalid session surface: ${r instanceof Error?r.message:"unknown error"}`,"SESSION_QUERY_INVALID_SURFACE",{cause:r})}let n=new Map;for(let r of t.nodes)n.set(r,"current");for(let r of t.replacements)for(let i of r.shadowedSeqs)n.set(i,"shadowed");return n}function fY(e,t=[]){let n=t.map(zkt);return e.filter(r=>n.every(i=>i(r)))}function MI(e,t=[]){let n=t.map(Wkt);return e.filter(r=>n.every(i=>i(r)))}function hY(e){return PEe(e),e.map(t=>{switch(t.kind){case"id":return{kind:t.kind,values:PI(t.kind,t.values)};case"cwd":return{kind:t.kind,values:OEe(t.kind,t.values)};case"created-at":return DEe(t.kind,t);case"parent":return{kind:t.kind,values:OEe(t.kind,t.values)};case"availability":{let n=PI(t.kind,t.values);return FI(t.kind,n,["live","persisted"]),{kind:t.kind,values:n}}default:return jI(t)}})}function LI(e){return PEe(e),e.map(t=>{switch(t.kind){case"seq":case"time":return DEe(t.kind,t);case"type":return{kind:t.kind,values:PI(t.kind,t.values)};case"surface":{let n=PI(t.kind,t.values);return FI(t.kind,n,["current","shadowed","log-only"]),{kind:t.kind,values:n}}case"text":if(typeof t.text!="string")throw Sv("text filter text must be a string");return{kind:t.kind,text:t.text};default:return jI(t)}})}function Bkt(e){let t=e.trim();if(t.length===0)throw new Cr("session text filter must contain non-whitespace text","SESSION_QUERY_INVALID_FILTER");let n=t.split(/\s+/u).map(r=>r.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")).join("\\s+");return new RegExp(n,"iu")}function zkt(e){switch(e.kind){case"id":return t=>e.values.includes(t.header.id);case"cwd":return t=>e.values.includes(t.header.cwd??null);case"created-at":{let t=DI(e.kind,e);return n=>dY(n.header.createdAt,t)}case"parent":return t=>e.values.includes(t.header.parentSession??null);case"availability":return FI(e.kind,e.values,["live","persisted"]),t=>e.values.some(n=>n==="live"?t.live:t.persisted);default:return jI(e)}}function Wkt(e){switch(e.kind){case"seq":{let t=DI(e.kind,e);return n=>dY(n.seq,t)}case"time":{let t=DI(e.kind,e);return n=>dY(n.time,t)}case"type":return t=>e.values.includes(t.type);case"surface":return FI(e.kind,e.values,["current","shadowed","log-only"]),t=>e.values.includes(t.surface);case"text":{let t=Bkt(e.text);return n=>t.test(n.text)}default:return jI(e)}}function PI(e,t){if(!MEe(t)||t.some(n=>typeof n!="string"))throw Sv(`${e} filter values must be an array of strings`);return[...t]}function PEe(e){if(!Array.isArray(e))throw Sv("filters must be an array")}function OEe(e,t){if(!MEe(t)||t.some(n=>n!==null&&typeof n!="string"))throw Sv(`${e} filter values must be an array of strings or null`);return[...t]}function DEe(e,t){let n={kind:e,...t.from===void 0?{}:{from:t.from},...t.to===void 0?{}:{to:t.to}};return DI(e,n),n}function jI(e){let t=e.kind;throw Sv(`unknown filter kind ${typeof t=="string"?`"${t}"`:"(missing)"}`)}function FI(e,t,n){for(let r of t)if(!n.includes(r))throw new Cr(`session ${e} filter contains unknown value "${r}"`,"SESSION_QUERY_INVALID_FILTER")}function DI(e,t){if(t.from!==void 0&&!Number.isFinite(t.from))throw lY(e,"from must be finite");if(t.to!==void 0&&!Number.isFinite(t.to))throw lY(e,"to must be finite");if(t.from!==void 0&&t.to!==void 0&&t.from>t.to)throw lY(e,"from must be less than or equal to to");return t}function dY(e,t){return(t.from===void 0||e>=t.from)&&(t.to===void 0||e<=t.to)}function lY(e,t){return Sv(`${e} filter ${t}`)}function Sv(e){return new Cr(`session ${e}`,"SESSION_QUERY_INVALID_FILTER")}function MEe(e){return Array.isArray(e)}function Hkt(e,t){return mY(e,t).records}function Vkt(e,t){return mY(e,t).currentSeqs.map(n=>{let r=t[n];if(r===void 0||r.seq!==n||!gm(r))throw new Cr(`invalid session surface: current node ${n} is not a surface event`,"SESSION_QUERY_INVALID_SURFACE");return cx(r)})}function Gkt(e,t,n){let r=t[n];if(r===void 0||r.seq!==n)throw new Cr(`session "${e}" has no event at seq ${n}`,"SESSION_QUERY_EVENT_NOT_FOUND");let i=mY(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||NEe(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:[...NEe(r)],derivedEventSeqs:l}}function Zkt(e,t){let n=new Map(e.map(p=>[p.header.id,p])),r=n.get(t);if(r===void 0)throw new Cr(`session "${t}" not found`,"SESSION_QUERY_SESSION_NOT_FOUND");let i=[],s=new Set([t]),a,l=r.header.parentSession;for(;l!==void 0;){if(s.has(l))throw new Cr(`session lineage contains a cycle at "${l}"`,"SESSION_QUERY_INVALID_LINEAGE");s.add(l);let p=n.get(l);if(p===void 0){a=l;break}i.push(p),l=p.header.parentSession}let c=new Map;for(let p of e){let m=p.header.parentSession;if(m===void 0)continue;let h=c.get(m)??[];h.push(p),c.set(m,h)}for(let p of c.values())p.sort((m,h)=>m.header.createdAt-h.header.createdAt||m.header.id.localeCompare(h.header.id));let u=Kkt(c,t),d={target:$I(r),ancestors:i.map($I),descendants:u};return a!==void 0?{...d,complete:!1,unresolvedParentId:a}:{...d,complete:!0,root:$I(i.at(-1)??r)}}function mY(e,t){let n;try{n=qD(t,II)}catch(a){throw new Cr(`invalid session surface: ${a instanceof Error?a.message:"unknown error"}`,"SESSION_QUERY_INVALID_SURFACE",{cause:a})}let r=new Set(n.nodes),i=new Map,s=new Map;for(let a of n.replacements){let l=a.shadowedSeqs;s.set(a.seq,l);for(let c of l)i.set(c,a.seq)}return{records:t.map(a=>({sessionId:e,seq:a.seq,type:a.type,time:a.time,surface:r.has(a.seq)?"current":i.has(a.seq)?"shadowed":"log-only"})),replacedBy:i,replacedEventSeqs:s,currentSeqs:[...n.nodes]}}function NEe(e){return e.sourceEventSeqs??[]}function Kkt(e,t){let n=[],r=[{sessionId:t,descendants:n}];for(;r.length>0;){let i=r.pop(),s=[];for(let a of e.get(i.sessionId)??[]){let l={session:$I(a),descendants:[]};s.push(l),i.descendants.push(l)}for(let a=s.length-1;a>=0;a-=1){let l=s[a];r.push({sessionId:l.session.header.id,descendants:l.descendants})}}return n}function $I(e){return{...e,header:structuredClone(e.header)}}var Cr,Dkt,Lkt,LEe,gY=oe(()=>{TEe();Gn();ys();Mm();dr();Cr=class extends jr{static{o(this,"SessionQueryError")}constructor(e,t,n){super(e,t,n)}};o($Ee,"readColdSessionLog");o(iY,"assertSessionHeadersCompatible");Dkt=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 aY(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&&iY(i.header,s.header),r.set(i.id,{header:structuredClone(i.header),live:!0,persisted:s!==void 0})}return[...r.values()].sort(Mkt)}async load(e,t){t?.throwIfAborted();let n=this._ctx.sessions.get(e);if(n!==void 0){let c=IEe(n);return t?.throwIfAborted(),c}let r=this._persistence;if(r===void 0)throw OI(e);let i=(await aY(r,t)).find(c=>c.id===e);if(t?.throwIfAborted(),i===void 0)throw OI(e);let s=await AEe(r,e,t);t?.throwIfAborted();let a=this._ctx.sessions.get(e);if(a!==void 0){let c=IEe(a);return t?.throwIfAborted(),c}iY(s.header,i);let l={header:structuredClone(s.header),inheritedEventCount:s.inheritedEventCount,events:s.events.map(c=>structuredClone(c))};return t?.throwIfAborted(),l}async projectMany(e,t,n){let r=[...new Set(e)];n?.throwIfAborted();let i=new Map,s=[];for(let g of r){let y=this._ctx.sessions.get(g);y===void 0?s.push(g):i.set(g,CI(g,sY(y),t,n))}if(s.length===0)return RI(r,i);let a=this._persistence;if(a===void 0){for(let g of s)i.set(g,{sessionId:g,status:"rejected",reason:OI(g)});return RI(r,i)}let l;try{l=await aY(a,n),n?.throwIfAborted()}catch(g){n?.aborted&&n.throwIfAborted();for(let y of s)i.set(y,{sessionId:y,status:"rejected",reason:g});return RI(r,i)}let c=new Map(l.map(g=>[g.id,g])),u=o(async g=>{let y=c.get(g);if(y===void 0){let v=this._ctx.sessions.get(g);i.set(g,v===void 0?{sessionId:g,status:"rejected",reason:OI(g)}:CI(g,sY(v),t,n));return}try{n?.throwIfAborted();let v=await AEe(a,g,n);n?.throwIfAborted();let b=this._ctx.sessions.get(g);if(b!==void 0){i.set(g,CI(g,sY(b),t,n));return}iY(v.header,y),i.set(g,CI(g,{header:v.header,events:v.events},t,n))}catch(v){n?.aborted&&n.throwIfAborted(),i.set(g,{sessionId:g,status:"rejected",reason:v})}},"resolvePersisted"),d=0,p=o(async()=>{for(;;){n?.throwIfAborted();let g=d;if(g>=s.length)return;d+=1,await u(s[g])}},"worker"),m=Math.min(this._persistedReadConcurrency,s.length),h=await Promise.allSettled(Array.from({length:m},()=>p()));n?.aborted&&n.throwIfAborted();for(let g of h)if(g.status==="rejected")throw g.reason;return n?.throwIfAborted(),RI(r,i)}};o(CI,"projectSource");o(sY,"sourceLive");o(RI,"orderedResults");o(aY,"listPersisted");o(AEe,"inspectPersisted");o(IEe,"snapshotLive");o(Mkt,"compareSessions");o(OI,"notFound$1");o(cY,"errorMessage$1");Lkt=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(;;){Zk(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 uY(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);Zk(n);let p=this.ctx.sessions.get(e);if(p!==void 0)return this.live(p,r);let m=d.events,h;try{h=this.ctx.sessions.prepare(e,{seed:m,meta:structuredClone(d.header),inheritedEventCount:d.inheritedEventCount,eventState:d.eventState})}catch(g){if(this.ctx.sessions.get(e)!==void 0)continue;throw new Cr(`stored session "${e}" is corrupt: ${NI(g)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:g})}c={persistenceIdentity:s.identity,revision:a.revision,session:h,events:Object.freeze(m),refs:0},this.store(e,c)}let u;try{u=r==="none"?void 0:this.preparedProjections(c)}catch(d){throw new Cr(`failed to project session "${e}": ${NI(d)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:d})}return this.preparedLease(e,c,u)}}async statSource(e,t,n){let r;try{r=await e.stat(t,n===void 0?void 0:{signal:n})}catch(i){throw Zk(n),CEe(t,i)}if(Zk(n),r===void 0)throw uY(t);if(r.header.id!==t)throw new Cr(`session persistence returned "${r.header.id}" for "${t}"`,"SESSION_QUERY_SOURCE_CONFLICT");return r}async loadSource(e,t,n){try{return await $Ee(e,t,n)}catch(r){throw Zk(n),CEe(t,r)}}cachedEntry(e,t,n){let r=this.cache.get(t);if(!(r===void 0||r.persistenceIdentity!==e||r.revision!==n))return this.cache.delete(t),this.cache.set(t,r),r}store(e,t){this.cache.delete(e),this.cache.set(e,t),this.evictPastCapacity(t)}evictPastCapacity(e){if(!(this.cache.size<=this.cacheCapacity)){for(let[t,n]of this.cache)if(!(n===e||n.refs>0)&&(this.cache.delete(t),this.cache.size<=this.cacheCapacity))return}}preparedLease(e,t,n){t.refs+=1;let r=o(()=>{let i=!1;return{source:"prepared",header:t.session.header,inheritedEventCount:t.session.inheritedEventCount,events:t.events,cursor:t.events.at(-1)?.seq??-1,revision:t.revision,...n===void 0?{}:{projections:n},retain:o(()=>{if(i)throw new Error(`session observation "${e}" is disposed`);return t.refs+=1,r()},"retain"),[Symbol.dispose]:()=>{i||(i=!0,t.refs-=1,t.refs===0&&this.evictPastCapacity())}}},"lease");return r()}live(e,t){let n=e.seq,r,i;try{i=t==="none"?void 0:this.ctx.get("sessionProjections")?.snapshot(e)}catch(a){throw new Cr(`failed to project session "${e.id}": ${NI(a)}`,"SESSION_QUERY_CORRUPT_SESSION",{cause:a})}let s=o(()=>{let a=!1;return{source:"live",header:e.header,inheritedEventCount:e.inheritedEventCount,get events(){return r??=e.snapshotEvents(_n(0),n),r},cursor:n===0?-1: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,_n(0)):n.hydratePrepared(e.session,e.events)}};o(Zk,"throwIfObservationAborted");o(CEe,"mapPersistenceFailure");o(uY,"notFound");o(NI,"errorMessage");o(REe,"hasErrorName");o(jkt,"extractSessionEventText");o(Fkt,"turnEndText");o(oY,"contentText");o(Ukt,"blockText");o(Kk,"joinText");o(pY,"buildSessionEventSearchDocuments");o(qkt,"classifySurface");o(fY,"filterSessionResults");o(MI,"filterSessionEventDocuments");o(hY,"materializeSessionResultFilters");o(LI,"materializeSessionEventResultFilters");o(Bkt,"compileSessionTextFilter");o(zkt,"sessionPredicate");o(Wkt,"eventPredicate");o(PI,"copyStrings");o(PEe,"assertArray");o(OEe,"copyNullableStrings");o(DEe,"copyRange");o(jI,"unknownFilter");o(FI,"assertAllowedValues");o(DI,"validateRange");o(dY,"matchesRange");o(lY,"invalidRange");o(Sv,"invalidFilter");o(MEe,"isRuntimeArray");o(Hkt,"eventRecords");o(Vkt,"currentSurfaceEvents");o(Gkt,"traceEvent");o(Zkt,"traceSession");o(mY,"analyzeEventLog");o(NEe,"eventSources");o(Kkt,"buildDescendants");o($I,"cloneRecord");LEe=class extends St{static{o(this,"SessionQueryEngine")}static inject=["sessions"];_readWindowMax;_corpus;_observations;constructor(e,t={}){if(super(e,"sessionQuery"),this._readWindowMax=t.readWindowMax??50,!Number.isInteger(this._readWindowMax)||this._readWindowMax<0)throw new Cr("session-query: readWindowMax must be a non-negative integer","SESSION_QUERY_INVALID_CONFIG");let n=t.persistedReadConcurrency??4;if(!Number.isSafeInteger(n)||n<1)throw new Cr("session-query: persistedReadConcurrency must be a positive safe integer","SESSION_QUERY_INVALID_CONFIG");let r=t.preparedSessionCacheSize??5;if(!Number.isSafeInteger(r)||r<1)throw new Cr("session-query: preparedSessionCacheSize must be a positive safe integer","SESSION_QUERY_INVALID_CONFIG");this._corpus=new Dkt(e,n),this._observations=new Lkt(e,r)}observeSession(e,t={}){return this._observations.read(e,t)}listSessions(e){return this._corpus.listSessions(e)}async readSession(e){let t=await this._corpus.load(e);return Ig.create(e,t.events,t.header,t.inheritedEventCount,II),{session:structuredClone(t.header),inheritedEventCount:t.inheritedEventCount,events:t.events.map(cx)}}async filterSessions(e,t){let n=hY(e);return this._filterSessions(n,t)}async readTitle(e,t){return(await this.readTitleSnapshot(e,t)).title}async readTitleSnapshot(e,t){let n=(await this.readTitleSnapshots([e],t))[0];if(n.status==="rejected")throw n.reason;return n.value}async readTitleSnapshots(e,t){return this._corpus.projectMany(e,n=>{let r=Dm(n.events);return{session:structuredClone(n.header),...r===void 0?{}:{title:r}}},t)}async listEvents(e){return Hkt(e,(await this._corpus.load(e)).events)}async filterEvents(e,t){let n=LI(t);return this._filterEvents(e,n)}async _filterSessions(e,t){return fY(await this._corpus.listSessions(t),e)}async _filterEvents(e,t){return MI(pY(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:Vkt(e,t.events)}}async traceSession(e,t){let n=await this._corpus.listSessions(t);return t?.throwIfAborted(),Zkt(n,e)}async traceEvent(e,t){let n=await this._corpus.load(e.sessionId,t);return t?.throwIfAborted(),{session:n.header,...Gkt(e.sessionId,n.events,e.seq)}}async readEvent(e,t){let n=this._readWindow("before",e.before),r=this._readWindow("after",e.after),i=e.sessionId,s=e.seq;return this._readEvent(i,s,n,r,t)}async _readEvent(e,t,n,r,i){let s=await this._corpus.load(e,i);i?.throwIfAborted();let a=s.events[t];if(a===void 0||a.seq!==t)throw new Cr(`session "${e}" has no event at seq ${t}`,"SESSION_QUERY_EVENT_NOT_FOUND");let l=sn(Math.max(0,t-n)),c=sn(Math.min(s.events.length-1,t+r)),u=cx(a),d=s.events.slice(l,c+1).map(p=>p===a?u:cx(p));return{session:structuredClone(s.header),inheritedEventCount:s.inheritedEventCount,target:u,events:d,startSeq:l,endSeq:c}}_readWindow(e,t){if(t===void 0)return 0;if(!Number.isInteger(t)||t<0||t>this._readWindowMax)throw new Cr(`${e} must be an integer between 0 and ${this._readWindowMax}`,"SESSION_QUERY_INVALID_WINDOW");return t}}});var kv=we((nOn,KEe)=>{"use strict";KEe.exports=j0;j0.CAPTURING_PHASE=1;j0.AT_TARGET=2;j0.BUBBLING_PHASE=3;function j0(e,t){if(this.type="",this.target=null,this.currentTarget=null,this.eventPhase=j0.AT_TARGET,this.bubbles=!1,this.cancelable=!1,this.isTrusted=!1,this.defaultPrevented=!1,this.timeStamp=Date.now(),this._propagationStopped=!1,this._immediatePropagationStopped=!1,this._initialized=!0,this._dispatching=!1,e&&(this.type=e),t)for(var n in t)this[n]=t[n]}o(j0,"Event");j0.prototype=Object.create(Object.prototype,{constructor:{value:j0},stopPropagation:{value:o(function(){this._propagationStopped=!0},"stopPropagation")},stopImmediatePropagation:{value:o(function(){this._propagationStopped=!0,this._immediatePropagationStopped=!0},"stopImmediatePropagation")},preventDefault:{value:o(function(){this.cancelable&&(this.defaultPrevented=!0)},"preventDefault")},initEvent:{value:o(function(t,n,r){this._initialized=!0,!this._dispatching&&(this._propagationStopped=!1,this._immediatePropagationStopped=!1,this.defaultPrevented=!1,this.isTrusted=!1,this.target=null,this.type=t,this.bubbles=n,this.cancelable=r)},"initEvent")}})});var kY=we((iOn,YEe)=>{"use strict";var JEe=kv();YEe.exports=SY;function SY(){JEe.call(this),this.view=null,this.detail=0}o(SY,"UIEvent");SY.prototype=Object.create(JEe.prototype,{constructor:{value:SY},initUIEvent:{value:o(function(e,t,n,r,i){this.initEvent(e,t,n),this.view=r,this.detail=i},"value")}})});var _Y=we((aOn,QEe)=>{"use strict";var XEe=kY();QEe.exports=EY;function EY(){XEe.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(EY,"MouseEvent");EY.prototype=Object.create(XEe.prototype,{constructor:{value:EY},initMouseEvent:{value:o(function(e,t,n,r,i,s,a,l,c,u,d,p,m,h,g){switch(this.initEvent(e,t,n,r,i),this.screenX=s,this.screenY=a,this.clientX=l,this.clientY=c,this.ctrlKey=u,this.altKey=d,this.shiftKey=p,this.metaKey=m,this.button=h,h){case 0:this.buttons=1;break;case 1:this.buttons=4;break;case 2:this.buttons=2;break;default:this.buttons=0;break}this.relatedTarget=g},"value")},getModifierState:{value:o(function(e){switch(e){case"Alt":return this.altKey;case"Control":return this.ctrlKey;case"Shift":return this.shiftKey;case"Meta":return this.metaKey;default:return!1}},"value")}})});var HI=we((lOn,t_e)=>{"use strict";t_e.exports=WI;var p4t=1,f4t=3,h4t=4,m4t=5,g4t=7,y4t=8,v4t=9,w4t=11,b4t=12,x4t=13,S4t=14,k4t=15,E4t=17,_4t=18,T4t=19,A4t=20,I4t=21,C4t=22,R4t=23,O4t=24,N4t=25,$4t=[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"],P4t=[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."],e_e={INDEX_SIZE_ERR:p4t,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:f4t,WRONG_DOCUMENT_ERR:h4t,INVALID_CHARACTER_ERR:m4t,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:g4t,NOT_FOUND_ERR:y4t,NOT_SUPPORTED_ERR:v4t,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:w4t,SYNTAX_ERR:b4t,INVALID_MODIFICATION_ERR:x4t,NAMESPACE_ERR:S4t,INVALID_ACCESS_ERR:k4t,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:E4t,SECURITY_ERR:_4t,NETWORK_ERR:T4t,ABORT_ERR:A4t,URL_MISMATCH_ERR:I4t,QUOTA_EXCEEDED_ERR:C4t,TIMEOUT_ERR:R4t,INVALID_NODE_TYPE_ERR:O4t,DATA_CLONE_ERR:N4t};function WI(e){Error.call(this),Error.captureStackTrace(this,this.constructor),this.code=e,this.message=P4t[e],this.name=$4t[e]}o(WI,"DOMException");WI.prototype.__proto__=Error.prototype;for(zI in e_e)TY={value:e_e[zI]},Object.defineProperty(WI,zI,TY),Object.defineProperty(WI.prototype,zI,TY);var TY,zI});var VI=we(n_e=>{n_e.isApiWritable=!globalThis.__domino_frozen__});var Js=we(Ri=>{"use strict";var Ks=HI(),pa=Ks,D4t=VI().isApiWritable;Ri.NAMESPACE={HTML:"http://www.w3.org/1999/xhtml",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/",MATHML:"http://www.w3.org/1998/Math/MathML",SVG:"http://www.w3.org/2000/svg",XLINK:"http://www.w3.org/1999/xlink"};Ri.IndexSizeError=function(){throw new Ks(pa.INDEX_SIZE_ERR)};Ri.HierarchyRequestError=function(){throw new Ks(pa.HIERARCHY_REQUEST_ERR)};Ri.WrongDocumentError=function(){throw new Ks(pa.WRONG_DOCUMENT_ERR)};Ri.InvalidCharacterError=function(){throw new Ks(pa.INVALID_CHARACTER_ERR)};Ri.NoModificationAllowedError=function(){throw new Ks(pa.NO_MODIFICATION_ALLOWED_ERR)};Ri.NotFoundError=function(){throw new Ks(pa.NOT_FOUND_ERR)};Ri.NotSupportedError=function(){throw new Ks(pa.NOT_SUPPORTED_ERR)};Ri.InvalidStateError=function(){throw new Ks(pa.INVALID_STATE_ERR)};Ri.SyntaxError=function(){throw new Ks(pa.SYNTAX_ERR)};Ri.InvalidModificationError=function(){throw new Ks(pa.INVALID_MODIFICATION_ERR)};Ri.NamespaceError=function(){throw new Ks(pa.NAMESPACE_ERR)};Ri.InvalidAccessError=function(){throw new Ks(pa.INVALID_ACCESS_ERR)};Ri.TypeMismatchError=function(){throw new Ks(pa.TYPE_MISMATCH_ERR)};Ri.SecurityError=function(){throw new Ks(pa.SECURITY_ERR)};Ri.NetworkError=function(){throw new Ks(pa.NETWORK_ERR)};Ri.AbortError=function(){throw new Ks(pa.ABORT_ERR)};Ri.UrlMismatchError=function(){throw new Ks(pa.URL_MISMATCH_ERR)};Ri.QuotaExceededError=function(){throw new Ks(pa.QUOTA_EXCEEDED_ERR)};Ri.TimeoutError=function(){throw new Ks(pa.TIMEOUT_ERR)};Ri.InvalidNodeTypeError=function(){throw new Ks(pa.INVALID_NODE_TYPE_ERR)};Ri.DataCloneError=function(){throw new Ks(pa.DATA_CLONE_ERR)};Ri.nyi=function(){throw new Error("NotYetImplemented")};Ri.shouldOverride=function(){throw new Error("Abstract function; should be overriding in subclass.")};Ri.assert=function(e,t){if(!e)throw new Error("Assertion failed: "+(t||"")+`
|
|
158
158
|
`+new Error().stack)};Ri.expose=function(e,t){for(var n in e)Object.defineProperty(t.prototype,n,{value:e[n],writable:D4t})};Ri.merge=function(e,t){for(var n in t)e[n]=t[n]};Ri.documentOrder=function(e,t){return 3-(e.compareDocumentPosition(t)&6)};Ri.toASCIILowerCase=function(e){return e.replace(/[A-Z]+/g,function(t){return t.toLowerCase()})};Ri.toASCIIUpperCase=function(e){return e.replace(/[a-z]+/g,function(t){return t.toUpperCase()})}});var AY=we((pOn,i_e)=>{"use strict";var F0=kv(),M4t=_Y(),L4t=Js();i_e.exports=r_e;function r_e(){}o(r_e,"EventTarget");r_e.prototype={addEventListener:o(function(t,n,r){if(n){r===void 0&&(r=!1),this._listeners||(this._listeners=Object.create(null)),this._listeners[t]||(this._listeners[t]=[]);for(var i=this._listeners[t],s=0,a=i.length;s<a;s++){var l=i[s];if(l.listener===n&&l.capture===r)return}var c={listener:n,capture:r};typeof n=="function"&&(c.f=n),i.push(c)}},"addEventListener"),removeEventListener:o(function(t,n,r){if(r===void 0&&(r=!1),this._listeners){var i=this._listeners[t];if(i)for(var s=0,a=i.length;s<a;s++){var l=i[s];if(l.listener===n&&l.capture===r){i.length===1?this._listeners[t]=void 0:i.splice(s,1);return}}}},"removeEventListener"),dispatchEvent:o(function(t){return this._dispatchEvent(t,!1)},"dispatchEvent"),_dispatchEvent:o(function(t,n){typeof n!="boolean"&&(n=!1);function r(u,d){var p=d.type,m=d.eventPhase;if(d.currentTarget=u,m!==F0.CAPTURING_PHASE&&u._handlers&&u._handlers[p]){var h=u._handlers[p],g;if(typeof h=="function")g=h.call(d.currentTarget,d);else{var y=h.handleEvent;if(typeof y!="function")throw new TypeError("handleEvent property of event handler object isnot a function.");g=y.call(h,d)}d.type==="mouseover"?g===!0&&d.preventDefault():g===!1&&d.preventDefault()}var v=u._listeners&&u._listeners[p];if(v){v=v.slice();for(var b=0,S=v.length;b<S;b++){if(d._immediatePropagationStopped)return;var k=v[b];if(!(m===F0.CAPTURING_PHASE&&!k.capture||m===F0.BUBBLING_PHASE&&k.capture))if(k.f)k.f.call(d.currentTarget,d);else{var x=k.listener.handleEvent;if(typeof x!="function")throw new TypeError("handleEvent property of event listener object is not a function.");x.call(k.listener,d)}}}}o(r,"invoke"),(!t._initialized||t._dispatching)&&L4t.InvalidStateError(),t.isTrusted=n,t._dispatching=!0,t.target=this;for(var i=[],s=this.parentNode;s;s=s.parentNode)i.push(s);t.eventPhase=F0.CAPTURING_PHASE;for(var a=i.length-1;a>=0&&(r(i[a],t),!t._propagationStopped);a--);if(t._propagationStopped||(t.eventPhase=F0.AT_TARGET,r(this,t)),t.bubbles&&!t._propagationStopped){t.eventPhase=F0.BUBBLING_PHASE;for(var l=0,c=i.length;l<c&&(r(i[l],t),!t._propagationStopped);l++);}if(t._dispatching=!1,t.eventPhase=F0.AT_TARGET,t.currentTarget=null,n&&!t.defaultPrevented&&t instanceof M4t)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 IY=we((hOn,s_e)=>{"use strict";var xh=Js(),Cu=s_e.exports={valid:o(function(e){return xh.assert(e,"list falsy"),xh.assert(e._previousSibling,"previous falsy"),xh.assert(e._nextSibling,"next falsy"),!0},"valid"),insertBefore:o(function(e,t){xh.assert(Cu.valid(e)&&Cu.valid(t));var n=e,r=e._previousSibling,i=t,s=t._previousSibling;n._previousSibling=s,r._nextSibling=i,s._nextSibling=n,i._previousSibling=r,xh.assert(Cu.valid(e)&&Cu.valid(t))},"insertBefore"),replace:o(function(e,t){xh.assert(Cu.valid(e)&&(t===null||Cu.valid(t))),t!==null&&Cu.insertBefore(t,e),Cu.remove(e),xh.assert(Cu.valid(e)&&(t===null||Cu.valid(t)))},"replace"),remove:o(function(e){xh.assert(Cu.valid(e));var t=e._previousSibling;if(t!==e){var n=e._nextSibling;t._nextSibling=n,n._previousSibling=t,e._previousSibling=e._nextSibling=e,xh.assert(Cu.valid(e))}},"remove")}});var CY=we((gOn,f_e)=>{"use strict";f_e.exports={serializeOne:W4t,\u0275escapeMatchingClosingTag:u_e,\u0275escapeClosingCommentTag:d_e,\u0275escapeProcessingInstructionContent:p_e};var c_e=Js(),U0=c_e.NAMESPACE,a_e={STYLE:!0,SCRIPT:!0,XMP:!0,IFRAME:!0,NOEMBED:!0,NOFRAMES:!0,PLAINTEXT:!0},j4t={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},F4t={},o_e=/[&<>\u00A0]/g,l_e=/[&"<>\u00A0]/g;function U4t(e){return o_e.test(e)?e.replace(o_e,t=>{switch(t){case"&":return"&";case"<":return"<";case">":return">";case"\xA0":return" "}}):e}o(U4t,"escape");function q4t(e){return l_e.test(e)?e.replace(l_e,t=>{switch(t){case"<":return"<";case">":return">";case"&":return"&";case'"':return""";case"\xA0":return" "}}):e}o(q4t,"escapeAttr");function B4t(e){var t=e.namespaceURI;return t?t===U0.XML?"xml:"+e.localName:t===U0.XLINK?"xlink:"+e.localName:t===U0.XMLNS?e.localName==="xmlns"?"xmlns":"xmlns:"+e.localName:e.name:e.localName}o(B4t,"attrname");function u_e(e,t){let n="</"+t;if(!e.toLowerCase().includes(n))return e;let r=[...e],i=e.matchAll(new RegExp(n,"ig"));for(let s of i)r[s.index]="<";return r.join("")}o(u_e,"escapeMatchingClosingTag");var z4t=/--!?>/;function d_e(e){return z4t.test(e)?e.replace(/(--\!?)>/g,"$1>"):e}o(d_e,"escapeClosingCommentTag");function p_e(e){return e.includes(">")?e.replaceAll(">",">"):e}o(p_e,"escapeProcessingInstructionContent");function W4t(e,t){var n="";switch(e.nodeType){case 1:var r=e.namespaceURI,i=r===U0.HTML,s=i||r===U0.SVG||r===U0.MATHML?e.localName:e.tagName;n+="<"+s;for(var a=0,l=e._numattrs;a<l;a++){var c=e._attr(a);n+=" "+B4t(c),c.value!==void 0&&(n+='="'+q4t(c.value)+'"')}if(n+=">",!(i&&j4t[s])){var u=e.serialize();a_e[s.toUpperCase()]&&(u=u_e(u,s)),i&&F4t[s]&&u.charAt(0)===`
|
|
@@ -5927,7 +5927,7 @@ The web search request used endpoint ${JSON.stringify(e)}. Search endpoint confi
|
|
|
5927
5927
|
.error { padding: .75rem; border-radius: .5rem; background: #461d2b; color: #ffd6df; }
|
|
5928
5928
|
.hint { margin: 1.5rem 0 0; font-size: .875rem; }
|
|
5929
5929
|
code { padding: .1rem .3rem; border-radius: .3rem; background: #0c1222; color: #edf2ff; }
|
|
5930
|
-
`}o(e$e,"pageStyles");RS();var Vne="enabled",Gne=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")}),lE=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")}),Zne=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:o(e=>e.DSH_EDGE_CONTAINER_RUNTIME===Vne?"available":"needs-binding","probe")}),vHt=Object.freeze([Zne,lE,Gne]);function Kne(e,t=vHt){return t.filter(n=>n.probe(e)==="available")}o(Kne,"availableEdgeRuntimeProviders");function Jne(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(Jne,"resolveEdgeRuntimeSelection");function SO(e){let t=Kne(e),{bash:n,container:r}=Jne(t);return t.find(i=>i.id===(r??n)).shell}o(SO,"resolveEdgeRuntimeShell");function wHt(){return"dsh-edge@0.23.0-alpha.2/isolated"}o(wHt,"resolveEdgeDeploymentId");function ow(e){return{baseURL:QZ(e.DEEPSEEK_BASE_URL),maxTokens:nK(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:A0(e.DEEPSEEK_MODEL),reasoningEffort:eK(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:v4(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:tK(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:U1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}o(ow,"resolveEdgeDeploymentConfig");function bHt(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}o(bHt,"edgeDeploymentApiKeyConfigured");function xHt(e){let t=QZ(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}o(xHt,"projectedEdgeBaseURL");function Yne(e,t){return{shell:SO(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:wHt(),apiKeyConfigured:bHt(e),baseURL:xHt(e.DEEPSEEK_BASE_URL),maxTokens:nK(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:A0(e.DEEPSEEK_MODEL),reasoningEffort:eK(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:v4(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:tK(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:U1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}o(Yne,"resolveEdgeDeploymentProfile");function kO(e){ow(e);let t=Yne(e);return{ok:!0,service:"dsh-edge",storage:t.storage,attachmentStorage:t.attachmentStorage,shell:t.shell,agent:"upstream-react-loop-agent",access:"single-owner-cookie",deploymentId:t.deploymentId,...e.CF_VERSION_METADATA===void 0?{}:{workerVersionId:e.CF_VERSION_METADATA.id},version:v0,upstreamVersion:Rve,status:"ready"}}o(kO,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as qtn}from"node:async_hooks";import{RpcTarget as SHt}from"cloudflare:workers";function kHt(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(kHt,"startHeartbeat");async function EHt(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(EHt,"probeComputerdHealth");var _Ht="computer.internal",THt="/health",Xne="/api",AHt=8080,IHt=3e4,CHt=2e4,RHt=1,OHt=2e3,NHt=250,$Ht=2e3;function PHt(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(PHt,"bearerMatches");var _O=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??_Ht,containerPort:e.containerPort??AHt,connectTimeoutMs:e.connectTimeoutMs??IHt,heartbeatIntervalMs:e.heartbeatIntervalMs??CHt,restartAttempts:e.restartAttempts??RHt,healthProbeTimeoutMs:e.healthProbeTimeoutMs??OHt,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??NHt,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??$Ht}}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 Yo(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 Yo(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=l$(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=kHt({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(Pw),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(t_),i.delete(Pw);let l=new Request(e,{headers:i});return this.#t.gateway.fetch(new Request(a,l))}if(new URL(e.url).pathname!==Xne)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${Xne} requires a websocket upgrade`,{status:400});if(!PHt(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 Yo(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 Yo(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 EHt(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 DHt(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=${t$e(t.lastError)}`}async#f(e,t){let n;try{let r=await e.fetchPort(this.#e.containerPort,"http://container/api",{signal:AbortSignal.timeout(Math.min(this.#e.healthProbeTimeoutMs,Math.max(50,t-Date.now())))});n=r.status,await r.text().catch(()=>"")}catch{return}if(n!==401)throw this.#o?.(new Error("container is not enforcing RPC_CLIENT_SECRET")),this.#a(),new Yo(`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:THt,api:Xne,healthTimeoutMs:r})})}catch(s){throw this.#o?.(s),this.#a(),new Yo(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${t$e(s)}`,{cause:s})}if(!i.ok){let s=await i.text().catch(()=>""),a=new Error(`/connect ${i.status}`);throw this.#o?.(a),this.#a(),new Yo(`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 Yo(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#a()}}};function DHt(e){return new Promise(t=>setTimeout(t,e))}o(DHt,"sleep");function t$e(e){return e instanceof Error?e.message:String(e)}o(t$e,"describeError");var n$e="computer:container-client-secret",MHt=16;function LHt(){let e=crypto.getRandomValues(new Uint8Array(MHt));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}o(LHt,"generate");var jHt=class{static{o(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(n$e);if(typeof e=="string"&&e.length>0)return e;let t=LHt();return await this.storage.put(n$e,t),t}},r$e="computer:container-launch-record";async function i$e(e){return{enableInternet:e.enableInternet,envDigest:await UHt(e.env)}}o(i$e,"launchRecordFor");function FHt(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}o(FHt,"sameLaunch");async function UHt(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(UHt,"digestEnv");var qHt=class{static{o(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(r$e)??null}async set(e){await this.storage.put(r$e,e)}},s$e=new WeakMap;function tre(e){let t=s$e.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},s$e.set(e,t)),t}o(tre,"getContainerLifecycle");function EO(e){return tre(e).exit}o(EO,"containerExitInfo");function a$e(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}o(a$e,"formatExitReason");function o$e(e,t,n){let r=tre(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>l$e(r,i,void 0,n),s=>l$e(r,i,s,n))}o(o$e,"installContainerMonitor");async function Qne(e,t){let n=tre(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}o(Qne,"destroyContainerExpectingExit");async function l$e(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=a$e(n),a=Date.now();e.exit={reason:s,exitedAt:a},i?console.info({message:"workspace.container.exited",reason:s,exitedAt:a,expected:!0}):console.warn({message:"workspace.container.exited",reason:s,exitedAt:a,expected:!1});try{await r?.()}catch(l){console.error({message:"workspace.container.exit_cleanup_failed",reason:a$e(l),exitedAt:Date.now()})}}o(l$e,"recordExit");var ere="computer:container-runtime-identity",BHt=class{static{o(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(ere)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(ere,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(ere)}},zHt=class extends SHt{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 BHt(e.storage),this.#n=new jHt(e.storage),this.#i=new qHt(e.storage)}async start(e){let t=EO(this.#t),n=await this.#n.ensure(),r=await i$e(e);if(t!==null){try{await Qne(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||!FHt(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 Qne(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return o$e(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await Qne(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await i$e(e),"launched")}async setInactivityTimeout(e){await this.#e.setInactivityTimeout(e)}async#s(e,t,n,r){let i=await this.#r.markStarted();try{this.#e.start({enableInternet:e.enableInternet,env:{...e.env,RPC_CLIENT_SECRET:t}})}catch(s){throw await this.#r.clear(i),s}return await this.#i.set(n),o$e(this.#t,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:EO(this.#t)}}async exitInfo(){return EO(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=EO(this.#t);if(r!==null)throw new Yo(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function c$e(e){class t extends e{static{o(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new zHt(this.ctx)}}return t}o(c$e,"withWorkspaceContainer");var WHt={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function d$e(e,t){let n=t.indexOf("."),r=t.indexOf("/"),i=n>=0?n:r;if(i<0)return;let s=t.slice(0,i),a=t.slice(i+1),l=WHt[s]??s,c=e[l];if(c===void 0)return;let u=c[a];return typeof u=="function"?u:void 0}o(d$e,"resolve");function HHt(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}o(HHt,"errorResponse");async function nre(e,t,n,r,i){let s=d$e(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}o(nre,"callEdgeApi");async function p$e(e,t){let r=new URL(t.url).pathname;if(t.method!=="POST"||!r.startsWith("/api/"))return new Response("not found",{status:404});if(r==="/api/respond")return Response.json({accepted:!1,reason:"not-pending"});let i=r.slice(5);if(d$e(e,i)===void 0)return new Response("not found",{status:404});let s;try{s=await t.json()}catch{return new Response("body is not JSON",{status:400})}let a=typeof s.rpcId=="string"?s.rpcId:"invalid-request",l=s.payload??{};try{let c=await nre(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 HHt(a,{code:"internal",message:String(c),details:{}})}}o(p$e,"dispatchEdgeApi");dr();ys();Mm();import{DurableObject as Btn}from"cloudflare:workers";var TO=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 VHt(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 VHt(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(VHt,"untilAborted");import{WorkerEntrypoint as CVn}from"cloudflare:workers";var _y=$l(f$e(),1);import{gunzipSync as gZt}from"node:zlib";var cE=class{static{o(this,"Diff")}diff(t,n,r={}){let i;typeof r=="function"?(i=r,r={}):"callback"in r&&(i=r.callback);let s=this.castInput(t,r),a=this.castInput(n,r),l=this.removeEmpty(this.tokenize(s,r)),c=this.removeEmpty(this.tokenize(a,r));return this.diffWithOptionsObj(l,c,r,i)}diffWithOptionsObj(t,n,r,i){var s;let a=o(S=>{if(S=this.postProcess(S,r),i){setTimeout(function(){i(S)},0);return}else return S},"done"),l=n.length,c=t.length,u=1,d=l+c;r.maxEditLength!=null&&(d=Math.min(d,r.maxEditLength));let p=(s=r.timeout)!==null&&s!==void 0?s:1/0,m=Date.now()+p,h=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(h[0],n,t,0,r);if(h[0].oldPos+1>=c&&g+1>=l)return a(this.buildValues(h[0].lastComponent,n,t));let y=-1/0,v=1/0,b=o(()=>{for(let S=Math.max(y,-u);S<=Math.min(v,u);S+=2){let k,x=h[S-1],E=h[S+1];x&&(h[S-1]=void 0);let T=!1;if(E){let U=E.oldPos-S;T=E&&0<=U&&U<l}let R=x&&x.oldPos+1<c;if(!T&&!R){h[S]=void 0;continue}if(!R||T&&x.oldPos<E.oldPos?k=this.addToPath(E,!0,!1,0,r):k=this.addToPath(x,!1,!0,1,r),g=this.extractCommon(k,n,t,S,r),k.oldPos+1>=c&&g+1>=l)return a(this.buildValues(k.lastComponent,n,t))||!0;h[S]=k,k.oldPos+1>=c&&(v=Math.min(v,S-1)),g+1>=l&&(y=Math.max(y,S+1))}u++},"execEditLength");if(i)o(function S(){setTimeout(function(){if(u>d||Date.now()>m)return i(void 0);b()||S()},0)},"exec")();else for(;u<=d&&Date.now()<=m;){let S=b();if(S)return S}}addToPath(t,n,r,i,s){let a=t.lastComponent;return a&&!s.oneChangePerToken&&a.added===n&&a.removed===r?{oldPos:t.oldPos+i,lastComponent:{count:a.count+1,added:n,removed:r,previousComponent:a.previousComponent}}:{oldPos:t.oldPos+i,lastComponent:{count:1,added:n,removed:r,previousComponent:a}}}extractCommon(t,n,r,i,s){let a=n.length,l=r.length,c=t.oldPos,u=c-i,d=0;for(;u+1<a&&c+1<l&&this.equals(r[c+1],n[u+1],s);)u++,c++,d++,s.oneChangePerToken&&(t.lastComponent={count:1,previousComponent:t.lastComponent,added:!1,removed:!1});return d&&!s.oneChangePerToken&&(t.lastComponent={count:d,previousComponent:t.lastComponent,added:!1,removed:!1}),t.oldPos=c,u}equals(t,n,r){return r.comparator?r.comparator(t,n):t===n||!!r.ignoreCase&&t.toLowerCase()===n.toLowerCase()}removeEmpty(t){let n=[];for(let r=0;r<t.length;r++)t[r]&&n.push(t[r]);return n}castInput(t,n){return t}tokenize(t,n){return Array.from(t)}join(t){return t.join("")}postProcess(t,n){return t}get useLongestToken(){return!1}buildValues(t,n,r){let i=[],s;for(;t;)i.push(t),s=t.previousComponent,delete t.previousComponent,t=s;i.reverse();let a=i.length,l=0,c=0,u=0;for(;l<a;l++){let d=i[l];if(d.removed)d.value=this.join(r.slice(u,u+d.count)),u+=d.count;else{if(!d.added&&this.useLongestToken){let p=n.slice(c,c+d.count);p=p.map(function(m,h){let g=r[u+h];return g.length>m.length?g:m}),d.value=this.join(p)}else d.value=this.join(n.slice(c,c+d.count));c+=d.count,d.added||(u+=d.count)}}return i}};var rre=class extends cE{static{o(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=ZHt}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
|
|
5930
|
+
`}o(e$e,"pageStyles");RS();var Vne="enabled",Gne=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")}),lE=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")}),Zne=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:o(e=>e.DSH_EDGE_CONTAINER_RUNTIME===Vne?"available":"needs-binding","probe")}),vHt=Object.freeze([Zne,lE,Gne]);function Kne(e,t=vHt){return t.filter(n=>n.probe(e)==="available")}o(Kne,"availableEdgeRuntimeProviders");function Jne(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(Jne,"resolveEdgeRuntimeSelection");function SO(e){let t=Kne(e),{bash:n,container:r}=Jne(t);return t.find(i=>i.id===(r??n)).shell}o(SO,"resolveEdgeRuntimeShell");function wHt(){return"dsh-edge@0.23.0/isolated"}o(wHt,"resolveEdgeDeploymentId");function ow(e){return{baseURL:QZ(e.DEEPSEEK_BASE_URL),maxTokens:nK(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:A0(e.DEEPSEEK_MODEL),reasoningEffort:eK(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:v4(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:tK(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:U1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}o(ow,"resolveEdgeDeploymentConfig");function bHt(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}o(bHt,"edgeDeploymentApiKeyConfigured");function xHt(e){let t=QZ(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}o(xHt,"projectedEdgeBaseURL");function Yne(e,t){return{shell:SO(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:wHt(),apiKeyConfigured:bHt(e),baseURL:xHt(e.DEEPSEEK_BASE_URL),maxTokens:nK(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:A0(e.DEEPSEEK_MODEL),reasoningEffort:eK(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:v4(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:tK(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:U1(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}o(Yne,"resolveEdgeDeploymentProfile");function kO(e){ow(e);let t=Yne(e);return{ok:!0,service:"dsh-edge",storage:t.storage,attachmentStorage:t.attachmentStorage,shell:t.shell,agent:"upstream-react-loop-agent",access:"single-owner-cookie",deploymentId:t.deploymentId,...e.CF_VERSION_METADATA===void 0?{}:{workerVersionId:e.CF_VERSION_METADATA.id},version:v0,upstreamVersion:Rve,status:"ready"}}o(kO,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as qtn}from"node:async_hooks";import{RpcTarget as SHt}from"cloudflare:workers";function kHt(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(kHt,"startHeartbeat");async function EHt(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(EHt,"probeComputerdHealth");var _Ht="computer.internal",THt="/health",Xne="/api",AHt=8080,IHt=3e4,CHt=2e4,RHt=1,OHt=2e3,NHt=250,$Ht=2e3;function PHt(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(PHt,"bearerMatches");var _O=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??_Ht,containerPort:e.containerPort??AHt,connectTimeoutMs:e.connectTimeoutMs??IHt,heartbeatIntervalMs:e.heartbeatIntervalMs??CHt,restartAttempts:e.restartAttempts??RHt,healthProbeTimeoutMs:e.healthProbeTimeoutMs??OHt,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??NHt,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??$Ht}}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 Yo(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 Yo(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=l$(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=kHt({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(Pw),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(t_),i.delete(Pw);let l=new Request(e,{headers:i});return this.#t.gateway.fetch(new Request(a,l))}if(new URL(e.url).pathname!==Xne)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${Xne} requires a websocket upgrade`,{status:400});if(!PHt(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 Yo(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 Yo(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 EHt(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 DHt(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=${t$e(t.lastError)}`}async#f(e,t){let n;try{let r=await e.fetchPort(this.#e.containerPort,"http://container/api",{signal:AbortSignal.timeout(Math.min(this.#e.healthProbeTimeoutMs,Math.max(50,t-Date.now())))});n=r.status,await r.text().catch(()=>"")}catch{return}if(n!==401)throw this.#o?.(new Error("container is not enforcing RPC_CLIENT_SECRET")),this.#a(),new Yo(`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:THt,api:Xne,healthTimeoutMs:r})})}catch(s){throw this.#o?.(s),this.#a(),new Yo(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${t$e(s)}`,{cause:s})}if(!i.ok){let s=await i.text().catch(()=>""),a=new Error(`/connect ${i.status}`);throw this.#o?.(a),this.#a(),new Yo(`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 Yo(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#a()}}};function DHt(e){return new Promise(t=>setTimeout(t,e))}o(DHt,"sleep");function t$e(e){return e instanceof Error?e.message:String(e)}o(t$e,"describeError");var n$e="computer:container-client-secret",MHt=16;function LHt(){let e=crypto.getRandomValues(new Uint8Array(MHt));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}o(LHt,"generate");var jHt=class{static{o(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(n$e);if(typeof e=="string"&&e.length>0)return e;let t=LHt();return await this.storage.put(n$e,t),t}},r$e="computer:container-launch-record";async function i$e(e){return{enableInternet:e.enableInternet,envDigest:await UHt(e.env)}}o(i$e,"launchRecordFor");function FHt(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}o(FHt,"sameLaunch");async function UHt(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(UHt,"digestEnv");var qHt=class{static{o(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(r$e)??null}async set(e){await this.storage.put(r$e,e)}},s$e=new WeakMap;function tre(e){let t=s$e.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},s$e.set(e,t)),t}o(tre,"getContainerLifecycle");function EO(e){return tre(e).exit}o(EO,"containerExitInfo");function a$e(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}o(a$e,"formatExitReason");function o$e(e,t,n){let r=tre(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>l$e(r,i,void 0,n),s=>l$e(r,i,s,n))}o(o$e,"installContainerMonitor");async function Qne(e,t){let n=tre(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}o(Qne,"destroyContainerExpectingExit");async function l$e(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=a$e(n),a=Date.now();e.exit={reason:s,exitedAt:a},i?console.info({message:"workspace.container.exited",reason:s,exitedAt:a,expected:!0}):console.warn({message:"workspace.container.exited",reason:s,exitedAt:a,expected:!1});try{await r?.()}catch(l){console.error({message:"workspace.container.exit_cleanup_failed",reason:a$e(l),exitedAt:Date.now()})}}o(l$e,"recordExit");var ere="computer:container-runtime-identity",BHt=class{static{o(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(ere)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(ere,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(ere)}},zHt=class extends SHt{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 BHt(e.storage),this.#n=new jHt(e.storage),this.#i=new qHt(e.storage)}async start(e){let t=EO(this.#t),n=await this.#n.ensure(),r=await i$e(e);if(t!==null){try{await Qne(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||!FHt(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 Qne(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return o$e(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await Qne(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await i$e(e),"launched")}async setInactivityTimeout(e){await this.#e.setInactivityTimeout(e)}async#s(e,t,n,r){let i=await this.#r.markStarted();try{this.#e.start({enableInternet:e.enableInternet,env:{...e.env,RPC_CLIENT_SECRET:t}})}catch(s){throw await this.#r.clear(i),s}return await this.#i.set(n),o$e(this.#t,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:EO(this.#t)}}async exitInfo(){return EO(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=EO(this.#t);if(r!==null)throw new Yo(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function c$e(e){class t extends e{static{o(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new zHt(this.ctx)}}return t}o(c$e,"withWorkspaceContainer");var WHt={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function d$e(e,t){let n=t.indexOf("."),r=t.indexOf("/"),i=n>=0?n:r;if(i<0)return;let s=t.slice(0,i),a=t.slice(i+1),l=WHt[s]??s,c=e[l];if(c===void 0)return;let u=c[a];return typeof u=="function"?u:void 0}o(d$e,"resolve");function HHt(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}o(HHt,"errorResponse");async function nre(e,t,n,r,i){let s=d$e(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}o(nre,"callEdgeApi");async function p$e(e,t){let r=new URL(t.url).pathname;if(t.method!=="POST"||!r.startsWith("/api/"))return new Response("not found",{status:404});if(r==="/api/respond")return Response.json({accepted:!1,reason:"not-pending"});let i=r.slice(5);if(d$e(e,i)===void 0)return new Response("not found",{status:404});let s;try{s=await t.json()}catch{return new Response("body is not JSON",{status:400})}let a=typeof s.rpcId=="string"?s.rpcId:"invalid-request",l=s.payload??{};try{let c=await nre(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 HHt(a,{code:"internal",message:String(c),details:{}})}}o(p$e,"dispatchEdgeApi");dr();ys();Mm();import{DurableObject as Btn}from"cloudflare:workers";var TO=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 VHt(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 VHt(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(VHt,"untilAborted");import{WorkerEntrypoint as CVn}from"cloudflare:workers";var _y=$l(f$e(),1);import{gunzipSync as gZt}from"node:zlib";var cE=class{static{o(this,"Diff")}diff(t,n,r={}){let i;typeof r=="function"?(i=r,r={}):"callback"in r&&(i=r.callback);let s=this.castInput(t,r),a=this.castInput(n,r),l=this.removeEmpty(this.tokenize(s,r)),c=this.removeEmpty(this.tokenize(a,r));return this.diffWithOptionsObj(l,c,r,i)}diffWithOptionsObj(t,n,r,i){var s;let a=o(S=>{if(S=this.postProcess(S,r),i){setTimeout(function(){i(S)},0);return}else return S},"done"),l=n.length,c=t.length,u=1,d=l+c;r.maxEditLength!=null&&(d=Math.min(d,r.maxEditLength));let p=(s=r.timeout)!==null&&s!==void 0?s:1/0,m=Date.now()+p,h=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(h[0],n,t,0,r);if(h[0].oldPos+1>=c&&g+1>=l)return a(this.buildValues(h[0].lastComponent,n,t));let y=-1/0,v=1/0,b=o(()=>{for(let S=Math.max(y,-u);S<=Math.min(v,u);S+=2){let k,x=h[S-1],E=h[S+1];x&&(h[S-1]=void 0);let T=!1;if(E){let U=E.oldPos-S;T=E&&0<=U&&U<l}let R=x&&x.oldPos+1<c;if(!T&&!R){h[S]=void 0;continue}if(!R||T&&x.oldPos<E.oldPos?k=this.addToPath(E,!0,!1,0,r):k=this.addToPath(x,!1,!0,1,r),g=this.extractCommon(k,n,t,S,r),k.oldPos+1>=c&&g+1>=l)return a(this.buildValues(k.lastComponent,n,t))||!0;h[S]=k,k.oldPos+1>=c&&(v=Math.min(v,S-1)),g+1>=l&&(y=Math.max(y,S+1))}u++},"execEditLength");if(i)o(function S(){setTimeout(function(){if(u>d||Date.now()>m)return i(void 0);b()||S()},0)},"exec")();else for(;u<=d&&Date.now()<=m;){let S=b();if(S)return S}}addToPath(t,n,r,i,s){let a=t.lastComponent;return a&&!s.oneChangePerToken&&a.added===n&&a.removed===r?{oldPos:t.oldPos+i,lastComponent:{count:a.count+1,added:n,removed:r,previousComponent:a.previousComponent}}:{oldPos:t.oldPos+i,lastComponent:{count:1,added:n,removed:r,previousComponent:a}}}extractCommon(t,n,r,i,s){let a=n.length,l=r.length,c=t.oldPos,u=c-i,d=0;for(;u+1<a&&c+1<l&&this.equals(r[c+1],n[u+1],s);)u++,c++,d++,s.oneChangePerToken&&(t.lastComponent={count:1,previousComponent:t.lastComponent,added:!1,removed:!1});return d&&!s.oneChangePerToken&&(t.lastComponent={count:d,previousComponent:t.lastComponent,added:!1,removed:!1}),t.oldPos=c,u}equals(t,n,r){return r.comparator?r.comparator(t,n):t===n||!!r.ignoreCase&&t.toLowerCase()===n.toLowerCase()}removeEmpty(t){let n=[];for(let r=0;r<t.length;r++)t[r]&&n.push(t[r]);return n}castInput(t,n){return t}tokenize(t,n){return Array.from(t)}join(t){return t.join("")}postProcess(t,n){return t}get useLongestToken(){return!1}buildValues(t,n,r){let i=[],s;for(;t;)i.push(t),s=t.previousComponent,delete t.previousComponent,t=s;i.reverse();let a=i.length,l=0,c=0,u=0;for(;l<a;l++){let d=i[l];if(d.removed)d.value=this.join(r.slice(u,u+d.count)),u+=d.count;else{if(!d.added&&this.useLongestToken){let p=n.slice(c,c+d.count);p=p.map(function(m,h){let g=r[u+h];return g.length>m.length?g:m}),d.value=this.join(p)}else d.value=this.join(n.slice(c,c+d.count));c+=d.count,d.added||(u+=d.count)}}return i}};var rre=class extends cE{static{o(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=ZHt}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
|
|
5931
5931
|
`))&&(t=t.trim()),(!r.newlineIsToken||!n.includes(`
|
|
5932
5932
|
`))&&(n=n.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
|
|
5933
5933
|
`)&&(t=t.slice(0,-1)),n.endsWith(`
|