dsh-edge 0.26.0-alpha.2 → 0.26.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(nt)}let Ct=`${l}/$ref`,mt=Jo(e,Ge,n,r,i,s,o,Ct,c);if(mt.valid||Re.push({instanceLocation:o,keyword:"$ref",keywordLocation:Ct,error:"A subschema had errors."},...mt.errors),n==="4"||n==="7")return{valid:Re.length===0,errors:Re}}if(Array.isArray(f)){let Ye=f.length,Ge=!1;for(let Ct=0;Ct<Ye;Ct++)if(d===f[Ct]||f[Ct]==="integer"&&d==="number"&&e%1===0&&e===e){Ge=!0;break}Ge||Re.push({instanceLocation:o,keyword:"type",keywordLocation:`${l}/type`,error:`Instance type "${d}" is invalid. Expected "${f.join('", "')}".`})}else f==="integer"?(d!=="number"||e%1||e!==e)&&Re.push({instanceLocation:o,keyword:"type",keywordLocation:`${l}/type`,error:`Instance type "${d}" is invalid. Expected "${f}".`}):f!==void 0&&d!==f&&Re.push({instanceLocation:o,keyword:"type",keywordLocation:`${l}/type`,error:`Instance type "${d}" is invalid. Expected "${f}".`});if(g!==void 0&&(d==="object"||d==="array"?TT(e,g)||Re.push({instanceLocation:o,keyword:"const",keywordLocation:`${l}/const`,error:`Instance does not match ${JSON.stringify(g)}.`}):e!==g&&Re.push({instanceLocation:o,keyword:"const",keywordLocation:`${l}/const`,error:`Instance does not match ${JSON.stringify(g)}.`})),v!==void 0&&(d==="object"||d==="array"?v.some(Ye=>TT(e,Ye))||Re.push({instanceLocation:o,keyword:"enum",keywordLocation:`${l}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`}):v.some(Ye=>e===Ye)||Re.push({instanceLocation:o,keyword:"enum",keywordLocation:`${l}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})),w!==void 0){let Ye=`${l}/not`;Jo(e,w,n,r,i,s,o,Ye).valid&&Re.push({instanceLocation:o,keyword:"not",keywordLocation:Ye,error:'Instance matched "not" schema.'})}let wt=[];if(b!==void 0){let Ye=`${l}/anyOf`,Ge=Re.length,Ct=!1;for(let mt=0;mt<b.length;mt++){let nt=b[mt],It=Object.create(c),Fe=Jo(e,nt,n,r,i,m===!0?s:null,o,`${Ye}/${mt}`,It);Re.push(...Fe.errors),Ct=Ct||Fe.valid,Fe.valid&&wt.push(It)}Ct?Re.length=Ge:Re.splice(Ge,0,{instanceLocation:o,keyword:"anyOf",keywordLocation:Ye,error:"Instance does not match any subschemas."})}if(k!==void 0){let Ye=`${l}/allOf`,Ge=Re.length,Ct=!0;for(let mt=0;mt<k.length;mt++){let nt=k[mt],It=Object.create(c),Fe=Jo(e,nt,n,r,i,m===!0?s:null,o,`${Ye}/${mt}`,It);Re.push(...Fe.errors),Ct=Ct&&Fe.valid,Fe.valid&&wt.push(It)}Ct?Re.length=Ge:Re.splice(Ge,0,{instanceLocation:o,keyword:"allOf",keywordLocation:Ye,error:"Instance does not match every subschema."})}if(E!==void 0){let Ye=`${l}/oneOf`,Ge=Re.length,Ct=E.filter((mt,nt)=>{let It=Object.create(c),Fe=Jo(e,mt,n,r,i,m===!0?s:null,o,`${Ye}/${nt}`,It);return Re.push(...Fe.errors),Fe.valid&&wt.push(It),Fe.valid}).length;Ct===1?Re.length=Ge:Re.splice(Ge,0,{instanceLocation:o,keyword:"oneOf",keywordLocation:Ye,error:`Instance does not match exactly one subschema (${Ct} matches).`})}if((d==="object"||d==="array")&&Object.assign(c,...wt),A!==void 0){let Ye=`${l}/if`;if(Jo(e,A,n,r,i,s,o,Ye,c).valid){if(I!==void 0){let Ct=Jo(e,I,n,r,i,s,o,`${l}/then`,c);Ct.valid||Re.push({instanceLocation:o,keyword:"if",keywordLocation:Ye,error:'Instance does not match "then" schema.'},...Ct.errors)}}else if(O!==void 0){let Ct=Jo(e,O,n,r,i,s,o,`${l}/else`,c);Ct.valid||Re.push({instanceLocation:o,keyword:"if",keywordLocation:Ye,error:'Instance does not match "else" schema.'},...Ct.errors)}}if(d==="object"){if(x!==void 0)for(let mt of x)mt in e||Re.push({instanceLocation:o,keyword:"required",keywordLocation:`${l}/required`,error:`Instance does not have required property "${mt}".`});let Ye=Object.keys(e);if(R!==void 0&&Ye.length<R&&Re.push({instanceLocation:o,keyword:"minProperties",keywordLocation:`${l}/minProperties`,error:`Instance does not have at least ${R} properties.`}),z!==void 0&&Ye.length>z&&Re.push({instanceLocation:o,keyword:"maxProperties",keywordLocation:`${l}/maxProperties`,error:`Instance does not have at least ${z} properties.`}),C!==void 0){let mt=`${l}/propertyNames`;for(let nt in e){let It=`${o}/${_p(nt)}`,Fe=Jo(nt,C,n,r,i,s,It,mt);Fe.valid||Re.push({instanceLocation:o,keyword:"propertyNames",keywordLocation:mt,error:`Property name "${nt}" does not match schema.`},...Fe.errors)}}if(M!==void 0){let mt=`${l}/dependantRequired`;for(let nt in M)if(nt in e){let It=M[nt];for(let Fe of It)Fe in e||Re.push({instanceLocation:o,keyword:"dependentRequired",keywordLocation:mt,error:`Instance has "${nt}" but does not have "${Fe}".`})}}if($!==void 0)for(let mt in $){let nt=`${l}/dependentSchemas`;if(mt in e){let It=Jo(e,$[mt],n,r,i,s,o,`${nt}/${_p(mt)}`,c);It.valid||Re.push({instanceLocation:o,keyword:"dependentSchemas",keywordLocation:nt,error:`Instance has "${mt}" but does not match dependant schema.`},...It.errors)}}if(F!==void 0){let mt=`${l}/dependencies`;for(let nt in F)if(nt in e){let It=F[nt];if(Array.isArray(It))for(let Fe of It)Fe in e||Re.push({instanceLocation:o,keyword:"dependencies",keywordLocation:mt,error:`Instance has "${nt}" but does not have "${Fe}".`});else{let Fe=Jo(e,It,n,r,i,s,o,`${mt}/${_p(nt)}`);Fe.valid||Re.push({instanceLocation:o,keyword:"dependencies",keywordLocation:mt,error:`Instance has "${nt}" but does not match dependant schema.`},...Fe.errors)}}}let Ge=Object.create(null),Ct=!1;if(L!==void 0){let mt=`${l}/properties`;for(let nt in L){if(!(nt in e))continue;let It=`${o}/${_p(nt)}`,Fe=Jo(e[nt],L[nt],n,r,i,s,It,`${mt}/${_p(nt)}`);if(Fe.valid)c[nt]=Ge[nt]=!0;else if(Ct=i,Re.push({instanceLocation:o,keyword:"properties",keywordLocation:mt,error:`Property "${nt}" does not match schema.`},...Fe.errors),Ct)break}}if(!Ct&&D!==void 0){let mt=`${l}/patternProperties`;for(let nt in D){let It=new RegExp(nt,"u"),Fe=D[nt];for(let Ft in e){if(!It.test(Ft))continue;let dn=`${o}/${_p(Ft)}`,_t=Jo(e[Ft],Fe,n,r,i,s,dn,`${mt}/${_p(nt)}`);_t.valid?c[Ft]=Ge[Ft]=!0:(Ct=i,Re.push({instanceLocation:o,keyword:"patternProperties",keywordLocation:mt,error:`Property "${Ft}" matches pattern "${nt}" but does not match associated schema.`},..._t.errors))}}}if(!Ct&&j!==void 0){let mt=`${l}/additionalProperties`;for(let nt in e){if(Ge[nt])continue;let It=`${o}/${_p(nt)}`,Fe=Jo(e[nt],j,n,r,i,s,It,mt);Fe.valid?c[nt]=!0:(Ct=i,Re.push({instanceLocation:o,keyword:"additionalProperties",keywordLocation:mt,error:`Property "${nt}" does not match additional properties schema.`},...Fe.errors))}}else if(!Ct&&Y!==void 0){let mt=`${l}/unevaluatedProperties`;for(let nt in e)if(!c[nt]){let It=`${o}/${_p(nt)}`,Fe=Jo(e[nt],Y,n,r,i,s,It,mt);Fe.valid?c[nt]=!0:Re.push({instanceLocation:o,keyword:"unevaluatedProperties",keywordLocation:mt,error:`Property "${nt}" does not match unevaluated properties schema.`},...Fe.errors)}}}else if(d==="array"){me!==void 0&&e.length>me&&Re.push({instanceLocation:o,keyword:"maxItems",keywordLocation:`${l}/maxItems`,error:`Array has too many items (${e.length} > ${me}).`}),Ee!==void 0&&e.length<Ee&&Re.push({instanceLocation:o,keyword:"minItems",keywordLocation:`${l}/minItems`,error:`Array has too few items (${e.length} < ${Ee}).`});let Ye=e.length,Ge=0,Ct=!1;if(U!==void 0){let mt=`${l}/prefixItems`,nt=Math.min(U.length,Ye);for(;Ge<nt;Ge++){let It=Jo(e[Ge],U[Ge],n,r,i,s,`${o}/${Ge}`,`${mt}/${Ge}`);if(c[Ge]=!0,!It.valid&&(Ct=i,Re.push({instanceLocation:o,keyword:"prefixItems",keywordLocation:mt,error:"Items did not match schema."},...It.errors),Ct))break}}if(Q!==void 0){let mt=`${l}/items`;if(Array.isArray(Q)){let nt=Math.min(Q.length,Ye);for(;Ge<nt;Ge++){let It=Jo(e[Ge],Q[Ge],n,r,i,s,`${o}/${Ge}`,`${mt}/${Ge}`);if(c[Ge]=!0,!It.valid&&(Ct=i,Re.push({instanceLocation:o,keyword:"items",keywordLocation:mt,error:"Items did not match schema."},...It.errors),Ct))break}}else for(;Ge<Ye;Ge++){let nt=Jo(e[Ge],Q,n,r,i,s,`${o}/${Ge}`,mt);if(c[Ge]=!0,!nt.valid&&(Ct=i,Re.push({instanceLocation:o,keyword:"items",keywordLocation:mt,error:"Items did not match schema."},...nt.errors),Ct))break}if(!Ct&&ee!==void 0){let nt=`${l}/additionalItems`;for(;Ge<Ye;Ge++){let It=Jo(e[Ge],ee,n,r,i,s,`${o}/${Ge}`,nt);c[Ge]=!0,It.valid||(Ct=i,Re.push({instanceLocation:o,keyword:"additionalItems",keywordLocation:nt,error:"Items did not match additional items schema."},...It.errors))}}}if(G!==void 0)if(Ye===0&&oe===void 0)Re.push({instanceLocation:o,keyword:"contains",keywordLocation:`${l}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(oe!==void 0&&Ye<oe)Re.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${l}/minContains`,error:`Array has less items (${Ye}) than minContains (${oe}).`});else{let mt=`${l}/contains`,nt=Re.length,It=0;for(let Fe=0;Fe<Ye;Fe++){let Ft=Jo(e[Fe],G,n,r,i,s,`${o}/${Fe}`,mt);Ft.valid?(c[Fe]=!0,It++):Re.push(...Ft.errors)}It>=(oe||0)&&(Re.length=nt),oe===void 0&&we===void 0&&It===0?Re.splice(nt,0,{instanceLocation:o,keyword:"contains",keywordLocation:mt,error:"Array does not contain item matching schema."}):oe!==void 0&&It<oe?Re.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${l}/minContains`,error:`Array must contain at least ${oe} items matching schema. Only ${It} items were found.`}):we!==void 0&&It>we&&Re.push({instanceLocation:o,keyword:"maxContains",keywordLocation:`${l}/maxContains`,error:`Array may contain at most ${we} items matching schema. ${It} items were found.`})}if(!Ct&&te!==void 0){let mt=`${l}/unevaluatedItems`;for(Ge;Ge<Ye;Ge++){if(c[Ge])continue;let nt=Jo(e[Ge],te,n,r,i,s,`${o}/${Ge}`,mt);c[Ge]=!0,nt.valid||Re.push({instanceLocation:o,keyword:"unevaluatedItems",keywordLocation:mt,error:"Items did not match unevaluated items schema."},...nt.errors)}}if(Ae)for(let mt=0;mt<Ye;mt++){let nt=e[mt],It=typeof nt=="object"&&nt!==null;for(let Fe=0;Fe<Ye;Fe++){if(mt===Fe)continue;let Ft=e[Fe];(nt===Ft||It&&(typeof Ft=="object"&&Ft!==null)&&TT(nt,Ft))&&(Re.push({instanceLocation:o,keyword:"uniqueItems",keywordLocation:`${l}/uniqueItems`,error:`Duplicate items at indexes ${mt} and ${Fe}.`}),mt=Number.MAX_SAFE_INTEGER,Fe=Number.MAX_SAFE_INTEGER)}}}else if(d==="number"){if(n==="4"?(Pe!==void 0&&(ge===!0&&e<=Pe||e<Pe)&&Re.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${l}/minimum`,error:`${e} is less than ${ge?"or equal to ":""} ${Pe}.`}),fe!==void 0&&(ft===!0&&e>=fe||e>fe)&&Re.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${l}/maximum`,error:`${e} is greater than ${ft?"or equal to ":""} ${fe}.`})):(Pe!==void 0&&e<Pe&&Re.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${l}/minimum`,error:`${e} is less than ${Pe}.`}),fe!==void 0&&e>fe&&Re.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${l}/maximum`,error:`${e} is greater than ${fe}.`}),ge!==void 0&&e<=ge&&Re.push({instanceLocation:o,keyword:"exclusiveMinimum",keywordLocation:`${l}/exclusiveMinimum`,error:`${e} is less than ${ge}.`}),ft!==void 0&&e>=ft&&Re.push({instanceLocation:o,keyword:"exclusiveMaximum",keywordLocation:`${l}/exclusiveMaximum`,error:`${e} is greater than or equal to ${ft}.`})),et!==void 0){let Ye=e%et;Math.abs(0-Ye)>=11920929e-14&&Math.abs(et-Ye)>=11920929e-14&&Re.push({instanceLocation:o,keyword:"multipleOf",keywordLocation:`${l}/multipleOf`,error:`${e} is not a multiple of ${et}.`})}}else if(d==="string"){let Ye=pt===void 0&&De===void 0?0:gqe(e);pt!==void 0&&Ye<pt&&Re.push({instanceLocation:o,keyword:"minLength",keywordLocation:`${l}/minLength`,error:`String is too short (${Ye} < ${pt}).`}),De!==void 0&&Ye>De&&Re.push({instanceLocation:o,keyword:"maxLength",keywordLocation:`${l}/maxLength`,error:`String is too long (${Ye} > ${De}).`}),Ie!==void 0&&!new RegExp(Ie,"u").test(e)&&Re.push({instanceLocation:o,keyword:"pattern",keywordLocation:`${l}/pattern`,error:"String does not match pattern."}),N!==void 0&&ude[N]&&!ude[N](e)&&Re.push({instanceLocation:o,keyword:"format",keywordLocation:`${l}/format`,error:`String does not match format "${N}".`})}return{valid:Re.length===0,errors:Re}}var hde=W(()=>{cde();OU();dde();MU();pde();a(Jo,"validate")});var NU,yqe=W(()=>{OU();hde();NU=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=U1(t)}validate(t){return Jo(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,n){n&&(t={...t,$id:n}),U1(t,this.lookup)}}});var vqe=W(()=>{cde();OU();dde();MU();fqe();pde();hde();yqe()});var $U,xqe=W(()=>{vqe();$U=class{static{a(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let n=new NU(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 Va,DU=W(()=>{"use strict";Va={probeTimeoutMs:3e4,callTimeoutMs:6e4,maxToolsPerServer:128,maxCatalogPages:10,maxCatalogBytes:131072,maxDescriptionLength:512,maxErrorMessageChars:300,maxPublicNameLength:64,maxInstructionsLength:1024,metaToolThreshold:20}});import{createHash as vKt}from"node:crypto";function wKt(e){let t=e.replace(/[.*+?^${}()|[\]\\]/gu,n=>n==="*"?"\0":`\\${n}`);return new RegExp(`^${t.replaceAll("\0",".*")}$`)}function wqe(e,t,n){let r=t??"read_only";return r==="allow_all"?"allow":r==="approve_all"?"ask":n===!0?"allow":n===!1?"ask":xKt.some(i=>wKt(i).test(e))?"allow":"ask"}function Wg(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,Va.maxErrorMessageChars)}function bqe(e,t){let n=`mcp__${e}__${t}`,r=n.replace(/[^A-Za-z0-9_-]/gu,"_");if(r===n&&r.length<=Va.maxPublicNameLength)return r;let i=bKt(e,t),s=Va.maxPublicNameLength-i.length-1;return`${r.slice(0,s)}_${i}`}function bKt(e,t){return vKt("sha256").update(`${e}\0${t}`).digest("hex").slice(0,12)}function kqe(e){if(!(e==null||typeof e!="object"))try{let t=JSON.parse(JSON.stringify(e));return Zb(t),t}catch{return}}function _Kt(e){return kKt.has(e)}function Sqe(e){return e.type!=="image"||e.data===void 0||e.mimeType===void 0||!_Kt(e.mimeType)||!SKt.test(e.data)?void 0:{data:Uint8Array.from(atob(e.data),n=>n.charCodeAt(0)),mediaType:e.mimeType}}function _qe(e){return e.some(t=>t.type==="image"&&t.data!==void 0)}function V8(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 xKt,kKt,SKt,LU=W(()=>{"use strict";Fo();DU();xKt=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a(wKt,"globToRegExp");a(wqe,"evaluateMcpToolPolicy");a(Wg,"scrubMcpErrorMessage");a(bqe,"publicToolName");a(bKt,"hashSuffix");a(kqe,"supportedOutputSchema");kKt=new Set(["image/png","image/jpeg"]),SKt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(_Kt,"isImageMediaType");a(Sqe,"decodeImageBlock");a(_qe,"containsImage");a(V8,"mapMcpResultToContentBlocks")});var mde,Eqe=W(()=>{mde={name:"dsh-edge",version:"0.26.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","check:startup":"node scripts/check-startup.mjs","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-pi-ai":"0.2.0-rc.2","@deepseek-ai/dsh-llm-retry":"0.2.0-rc.2","@deepseek-ai/dsh-message-feedback":"0.2.0-rc.2","@deepseek-ai/dsh-output-retention":"0.2.0-rc.2","@deepseek-ai/dsh-plan-mode":"0.2.0-rc.2","@deepseek-ai/dsh-ptc-runtime":"0.2.0-rc.2","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.0-rc.2","@deepseek-ai/dsh-sandbox":"0.2.0-rc.2","@deepseek-ai/dsh-schedule":"0.2.0-rc.2","@deepseek-ai/dsh-scope":"0.2.0-rc.2","@deepseek-ai/dsh-session":"0.2.0-rc.2","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.0-rc.2","@deepseek-ai/dsh-session-format":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-catalog":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.0-rc.2","@deepseek-ai/dsh-session-persistence":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection-cache":"0.2.0-rc.2","@deepseek-ai/dsh-session-stats":"0.2.0-rc.2","@deepseek-ai/dsh-session-query":"0.2.0-rc.2","@deepseek-ai/dsh-session-reference":"0.2.0-rc.2","@deepseek-ai/dsh-session-title":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-llm":"0.2.0-rc.2","@deepseek-ai/dsh-settings":"0.2.0-rc.2","@deepseek-ai/dsh-skill":"0.2.0-rc.2","@deepseek-ai/dsh-spill":"0.2.0-rc.2","@deepseek-ai/dsh-spill-policy":"0.2.0-rc.2","@deepseek-ai/dsh-storage":"0.2.0-rc.2","@deepseek-ai/dsh-storage-domain":"0.2.0-rc.2","@deepseek-ai/dsh-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-in-process-driver":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-fork-in-process":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-spawn-in-process":"0.2.0-rc.2","@deepseek-ai/dsh-system-prompt":"0.2.0-rc.2","@deepseek-ai/dsh-timeout":"0.2.0-rc.2","@deepseek-ai/dsh-token-meter":"0.2.0-rc.2","@deepseek-ai/dsh-tool-ask-user":"0.2.0-rc.2","@deepseek-ai/dsh-tool-call-timeout-policy":"0.2.0-rc.2","@deepseek-ai/dsh-tool-fs":"0.2.0-rc.2","@deepseek-ai/dsh-tool-fs-search":"0.2.0-rc.2","@deepseek-ai/dsh-tool-goal":"0.2.0-rc.2","@deepseek-ai/dsh-tool-jobs":"0.2.0-rc.2","@deepseek-ai/dsh-tool-skill":"0.2.0-rc.2","@deepseek-ai/dsh-tool-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-tool-subagent-control":"0.2.0-rc.2","@deepseek-ai/dsh-tool-present":"0.2.0-rc.2","@deepseek-ai/dsh-tool-todo":"0.2.0-rc.2","@deepseek-ai/dsh-tool-web":"0.2.0-rc.2","@deepseek-ai/dsh-tool-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-tools":"0.2.0-rc.2","@deepseek-ai/dsh-typert-protocol":"0.2.0-rc.2","@deepseek-ai/dsh-typert-registry":"0.2.0-rc.2","@deepseek-ai/dsh-user-approval":"0.2.0-rc.2","@deepseek-ai/dsh-user-questions":"0.2.0-rc.2","@deepseek-ai/dsh-util-values":"0.2.0-rc.2","@deepseek-ai/dsh-web":"0.2.0-rc.2","@deepseek-ai/dsh-web-fetch-http":"0.2.0-rc.2","@deepseek-ai/dsh-web-search-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-workspace":"0.2.0-rc.2","@deepseek-ai/schemastery":"3.18.4","@mixmark-io/domino":"2.2.0","@modelcontextprotocol/sdk":"1.30.0",acorn:"8.18.0","fast-png":"8.0.0","jpeg-js":"0.4.4","just-bash":"3.4.2",minimatch:"10.2.6",playwright:"^1.49.0",re2js:"1.3.3",sucrase:"3.35.1",typescript:"^6.0.3",vitest:"^4.1.8",ws:"^8.21.0"}}});var F2,Tqe,Aqe,K8=W(()=>{"use strict";Eqe();F2=mde.version,Tqe=mde.dshEdge.upstreamVersion,Aqe=`npx dsh-edge@${F2.includes("-")?"next":"latest"} upgrade`});function RKt(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 CKt(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function q1(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 TKt)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(CKt(i)){let s=RKt(i),o=s??i;for(let l of AKt)if(l.test(o))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`);if(s===void 0){for(let l of IKt)if(l.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function PKt(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function Iqe(e,t,n){q1(e);let r=new PU(new URL(e),{requestInit:{headers:PKt(t),signal:n},fetch:U2}),i=new RU({name:"dsh-edge",version:F2},{capabilities:{},jsonSchemaValidator:MKt});return await i.connect(r),{client:i,close:a(async()=>{await i.close().catch(()=>{})},"close")}}async function Rqe(e,t,n){let r=AbortSignal.timeout(Va.probeTimeoutMs),i;try{i=await Iqe(t,n,r)}catch(l){throw new Error(Wg(l instanceof Error?l.message:String(l)))}let{client:s,close:o}=i;try{let l=[],c=new Set,u=new Set,d;for(let m=0;m<Va.maxCatalogPages;m++){let f=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let g of f.tools){if(l.length>=Va.maxToolsPerServer)break;let v=bqe(e,g.name);if(c.has(v))throw new Error(`Server listed tool "${g.name}" more than once`);c.add(v);let x=g.annotations?.readOnlyHint,w=kqe(g.outputSchema);l.push({name:g.name,publicName:v,description:g.description??"",inputSchema:g.inputSchema??{type:"object"},...w!==void 0?{outputSchema:w}:{},...x!==void 0?{annotations:{readOnlyHint:x}}:{}})}if(l.length>=Va.maxToolsPerServer||(d=f.nextCursor??void 0,d===void 0))break;if(u.has(d))throw new Error("Server repeated a tools/list continuation cursor");u.add(d)}let p=s.getServerVersion?.(),h=s.getInstructions?.();return{tools:l,serverInfo:p?{name:p.name,version:p.version}:void 0,instructions:typeof h=="string"&&h.length>0?h.slice(0,Va.maxInstructionsLength):void 0}}finally{await o()}}async function FU(e,t,n,r,i,s){let o=s??Va.callTimeoutMs,l=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),c;try{c=await Iqe(e,r,l)}catch(u){throw new Error(Wg(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(Wg(u instanceof Error?u.message:String(u)))}finally{await c.close()}}var TKt,AKt,IKt,MKt,U2,Q8=W(()=>{"use strict";MUe();dqe();xqe();LU();DU();K8();TKt=[".internal",".local",".localhost"],AKt=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],IKt=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(RKt,"extractMappedIPv4");a(CKt,"isIpAddress");a(q1,"assertSafeUrl");a(PKt,"buildHeaders");MKt=new $U,U2=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(Iqe,"connectClient");a(Rqe,"probe");a(FU,"callTool")});import{Buffer as OKt}from"node:buffer";function LKt(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&DKt.has(e.code)}function Pqe(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&$Kt.has(e.code)}function Mqe(e,t,n){let r=OKt.from(e,"base64");if(e.length===0&&t==="reject"||r.toString("base64")!==e)throw new zr(n==="INVALID_IMAGE_BASE64"?"Image upload is not canonical base64.":"File upload is not canonical base64.",n);return new Uint8Array(r)}function FKt(e){return Mqe(e,"reject","INVALID_IMAGE_BASE64")}function UKt(e){return{data:FKt(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function J8(e,t){return e.saveImages(t.map(UKt))}async function qKt(e,t){return e.saveFile({data:Mqe(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function UU(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)),l=Math.max(1,Math.round(o*t/e));for(;o*l>n&&o>1;)o-=1,l=Math.max(1,Math.round(o*t/e));return{width:o,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 fde(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 Cqe,NKt,$Kt,DKt,zr,gde,jg=W(()=>{vr();Cqe=["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"],NKt=[...Cqe,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],$Kt=new Set(Cqe),DKt=new Set(NKt),zr=class extends Error{static{a(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};a(LKt,"isAttachmentError");a(Pqe,"isImageAdmissionError");a(Mqe,"decodeCanonicalBase64");a(FKt,"decodeBase64");a(UKt,"saveInput");a(J8,"admitEncodedImages");a(qKt,"admitEncodedFile");a(UU,"requestImageDimensions");a(fde,"longEdgeDimensions");gde=class extends $t{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 zr("Image batch exceeds the configured image-count limit.","TOO_MANY_IMAGES");if(e.reduce((i,s)=>i+s.data.byteLength,0)>n)throw new zr("Image batch exceeds the configured aggregate image-byte limit.","IMAGES_TOO_LARGE");for(let i of e)if(!r.includes(i.mediaType))throw new zr(`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 J8(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 qKt(this,e)}isAttachmentError(e){return LKt(e)}imageHostPath(e){}saveFile(e){return Promise.reject(new zr("The mounted attachment provider cannot store verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}saveFileStream(e){return Promise.reject(new zr("The mounted attachment provider cannot stream verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}async*readFileStream(e,t){t?.throwIfAborted(),await Promise.reject(new zr("The mounted attachment provider cannot read verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}fileHostPath(e){}readImageRequest(e,t,n){return n?.throwIfAborted(),Promise.reject(new zr("The mounted attachment provider cannot derive model-request images.","ATTACHMENT_PROJECTION_UNSUPPORTED"))}}});var WU={};tn(WU,{buildAuthorizationUrl:()=>QKt,discoverEndpoints:()=>VKt,exchangeCode:()=>JKt,isTokenExpired:()=>ZKt,refreshToken:()=>YKt,registerClient:()=>KKt});function Dqe(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 GKt(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 VKt(e){let t=AbortSignal.timeout(qU),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);q1(i.href);let s=await U2(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);q1(d.href);let p=await U2(d.href,{signal:t});if(!p.ok)throw new Error(`AS metadata failed: HTTP ${p.status}`);let h=await p.json();if(typeof h.authorization_endpoint!="string"||typeof h.token_endpoint!="string")throw new Error("Missing required endpoints in AS metadata");return{authorization:h.authorization_endpoint,token:h.token_endpoint,registration:h.registration_endpoint}}async function KKt(e,t,n){let r=AbortSignal.timeout(qU);q1(e);let i=await U2(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 QKt(e,t,n,r,i){let s=Dqe(32),o=Dqe(64),l=await GKt(o),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:o,redirectUri:n,serverName:r,serverUrl:i,stagedClient:t,createdAt:Date.now()}}}async function JKt(e,t,n,r,i,s){let o=AbortSignal.timeout(qU),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),q1(e);let c=await U2(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:l.toString(),signal:o});if(!c.ok)throw new Error(`Token exchange failed: HTTP ${c.status}`);return Lqe(await c.json())}async function YKt(e,t,n,r){let i=AbortSignal.timeout(qU),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),q1(e);let o=await U2(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 Lqe(await o.json())}function Lqe(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 ZKt(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var qU,jU=W(()=>{"use strict";Q8();qU=1e4;a(Dqe,"randomString");a(GKt,"sha256Base64Url");a(VKt,"discoverEndpoints");a(KKt,"registerClient");a(QKt,"buildAuthorizationUrl");a(JKt,"exchangeCode");a(YKt,"refreshToken");a(Lqe,"parseTokenResponse");a(ZKt,"isTokenExpired")});var hr,Hqe,AT=W(()=>{vr();Wr();hr=class extends Ei{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},Hqe=class extends $t{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new hr("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function t7(e){return XU.test(e)}function eq(e){return e.invocation.modelInvocable}function RT(e){return e.invocation.userInvocable}function $de(e){let t=DJt(e);return[`<skill_content name="${LJt(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 xKt,kKt,SKt,LU=W(()=>{"use strict";Fo();DU();xKt=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a(wKt,"globToRegExp");a(wqe,"evaluateMcpToolPolicy");a(Wg,"scrubMcpErrorMessage");a(bqe,"publicToolName");a(bKt,"hashSuffix");a(kqe,"supportedOutputSchema");kKt=new Set(["image/png","image/jpeg"]),SKt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(_Kt,"isImageMediaType");a(Sqe,"decodeImageBlock");a(_qe,"containsImage");a(V8,"mapMcpResultToContentBlocks")});var mde,Eqe=W(()=>{mde={name:"dsh-edge",version:"0.26.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","check:startup":"node scripts/check-startup.mjs","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-pi-ai":"0.2.0-rc.2","@deepseek-ai/dsh-llm-retry":"0.2.0-rc.2","@deepseek-ai/dsh-message-feedback":"0.2.0-rc.2","@deepseek-ai/dsh-output-retention":"0.2.0-rc.2","@deepseek-ai/dsh-plan-mode":"0.2.0-rc.2","@deepseek-ai/dsh-ptc-runtime":"0.2.0-rc.2","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.0-rc.2","@deepseek-ai/dsh-sandbox":"0.2.0-rc.2","@deepseek-ai/dsh-schedule":"0.2.0-rc.2","@deepseek-ai/dsh-scope":"0.2.0-rc.2","@deepseek-ai/dsh-session":"0.2.0-rc.2","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.0-rc.2","@deepseek-ai/dsh-session-format":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-catalog":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.0-rc.2","@deepseek-ai/dsh-session-persistence":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection-cache":"0.2.0-rc.2","@deepseek-ai/dsh-session-stats":"0.2.0-rc.2","@deepseek-ai/dsh-session-query":"0.2.0-rc.2","@deepseek-ai/dsh-session-reference":"0.2.0-rc.2","@deepseek-ai/dsh-session-title":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-llm":"0.2.0-rc.2","@deepseek-ai/dsh-settings":"0.2.0-rc.2","@deepseek-ai/dsh-skill":"0.2.0-rc.2","@deepseek-ai/dsh-spill":"0.2.0-rc.2","@deepseek-ai/dsh-spill-policy":"0.2.0-rc.2","@deepseek-ai/dsh-storage":"0.2.0-rc.2","@deepseek-ai/dsh-storage-domain":"0.2.0-rc.2","@deepseek-ai/dsh-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-in-process-driver":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-fork-in-process":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-spawn-in-process":"0.2.0-rc.2","@deepseek-ai/dsh-system-prompt":"0.2.0-rc.2","@deepseek-ai/dsh-timeout":"0.2.0-rc.2","@deepseek-ai/dsh-token-meter":"0.2.0-rc.2","@deepseek-ai/dsh-tool-ask-user":"0.2.0-rc.2","@deepseek-ai/dsh-tool-call-timeout-policy":"0.2.0-rc.2","@deepseek-ai/dsh-tool-fs":"0.2.0-rc.2","@deepseek-ai/dsh-tool-fs-search":"0.2.0-rc.2","@deepseek-ai/dsh-tool-goal":"0.2.0-rc.2","@deepseek-ai/dsh-tool-jobs":"0.2.0-rc.2","@deepseek-ai/dsh-tool-skill":"0.2.0-rc.2","@deepseek-ai/dsh-tool-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-tool-subagent-control":"0.2.0-rc.2","@deepseek-ai/dsh-tool-present":"0.2.0-rc.2","@deepseek-ai/dsh-tool-todo":"0.2.0-rc.2","@deepseek-ai/dsh-tool-web":"0.2.0-rc.2","@deepseek-ai/dsh-tool-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-tools":"0.2.0-rc.2","@deepseek-ai/dsh-typert-protocol":"0.2.0-rc.2","@deepseek-ai/dsh-typert-registry":"0.2.0-rc.2","@deepseek-ai/dsh-user-approval":"0.2.0-rc.2","@deepseek-ai/dsh-user-questions":"0.2.0-rc.2","@deepseek-ai/dsh-util-values":"0.2.0-rc.2","@deepseek-ai/dsh-web":"0.2.0-rc.2","@deepseek-ai/dsh-web-fetch-http":"0.2.0-rc.2","@deepseek-ai/dsh-web-search-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-workspace":"0.2.0-rc.2","@deepseek-ai/schemastery":"3.18.4","@mixmark-io/domino":"2.2.0","@modelcontextprotocol/sdk":"1.30.0",acorn:"8.18.0","fast-png":"8.0.0","jpeg-js":"0.4.4","just-bash":"3.4.2",minimatch:"10.2.6",playwright:"^1.49.0",re2js:"1.3.3",sucrase:"3.35.1",typescript:"^6.0.3",vitest:"^4.1.8",ws:"^8.21.0"}}});var F2,Tqe,Aqe,K8=W(()=>{"use strict";Eqe();F2=mde.version,Tqe=mde.dshEdge.upstreamVersion,Aqe=`npx dsh-edge@${F2.includes("-")?"next":"latest"} upgrade`});function RKt(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 CKt(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function q1(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 TKt)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(CKt(i)){let s=RKt(i),o=s??i;for(let l of AKt)if(l.test(o))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`);if(s===void 0){for(let l of IKt)if(l.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function PKt(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function Iqe(e,t,n){q1(e);let r=new PU(new URL(e),{requestInit:{headers:PKt(t),signal:n},fetch:U2}),i=new RU({name:"dsh-edge",version:F2},{capabilities:{},jsonSchemaValidator:MKt});return await i.connect(r),{client:i,close:a(async()=>{await i.close().catch(()=>{})},"close")}}async function Rqe(e,t,n){let r=AbortSignal.timeout(Va.probeTimeoutMs),i;try{i=await Iqe(t,n,r)}catch(l){throw new Error(Wg(l instanceof Error?l.message:String(l)))}let{client:s,close:o}=i;try{let l=[],c=new Set,u=new Set,d;for(let m=0;m<Va.maxCatalogPages;m++){let f=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let g of f.tools){if(l.length>=Va.maxToolsPerServer)break;let v=bqe(e,g.name);if(c.has(v))throw new Error(`Server listed tool "${g.name}" more than once`);c.add(v);let x=g.annotations?.readOnlyHint,w=kqe(g.outputSchema);l.push({name:g.name,publicName:v,description:g.description??"",inputSchema:g.inputSchema??{type:"object"},...w!==void 0?{outputSchema:w}:{},...x!==void 0?{annotations:{readOnlyHint:x}}:{}})}if(l.length>=Va.maxToolsPerServer||(d=f.nextCursor??void 0,d===void 0))break;if(u.has(d))throw new Error("Server repeated a tools/list continuation cursor");u.add(d)}let p=s.getServerVersion?.(),h=s.getInstructions?.();return{tools:l,serverInfo:p?{name:p.name,version:p.version}:void 0,instructions:typeof h=="string"&&h.length>0?h.slice(0,Va.maxInstructionsLength):void 0}}finally{await o()}}async function FU(e,t,n,r,i,s){let o=s??Va.callTimeoutMs,l=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),c;try{c=await Iqe(e,r,l)}catch(u){throw new Error(Wg(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(Wg(u instanceof Error?u.message:String(u)))}finally{await c.close()}}var TKt,AKt,IKt,MKt,U2,Q8=W(()=>{"use strict";MUe();dqe();xqe();LU();DU();K8();TKt=[".internal",".local",".localhost"],AKt=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],IKt=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(RKt,"extractMappedIPv4");a(CKt,"isIpAddress");a(q1,"assertSafeUrl");a(PKt,"buildHeaders");MKt=new $U,U2=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(Iqe,"connectClient");a(Rqe,"probe");a(FU,"callTool")});import{Buffer as OKt}from"node:buffer";function LKt(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&DKt.has(e.code)}function Pqe(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&$Kt.has(e.code)}function Mqe(e,t,n){let r=OKt.from(e,"base64");if(e.length===0&&t==="reject"||r.toString("base64")!==e)throw new zr(n==="INVALID_IMAGE_BASE64"?"Image upload is not canonical base64.":"File upload is not canonical base64.",n);return new Uint8Array(r)}function FKt(e){return Mqe(e,"reject","INVALID_IMAGE_BASE64")}function UKt(e){return{data:FKt(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function J8(e,t){return e.saveImages(t.map(UKt))}async function qKt(e,t){return e.saveFile({data:Mqe(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function UU(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)),l=Math.max(1,Math.round(o*t/e));for(;o*l>n&&o>1;)o-=1,l=Math.max(1,Math.round(o*t/e));return{width:o,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 fde(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 Cqe,NKt,$Kt,DKt,zr,gde,jg=W(()=>{vr();Cqe=["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"],NKt=[...Cqe,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],$Kt=new Set(Cqe),DKt=new Set(NKt),zr=class extends Error{static{a(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};a(LKt,"isAttachmentError");a(Pqe,"isImageAdmissionError");a(Mqe,"decodeCanonicalBase64");a(FKt,"decodeBase64");a(UKt,"saveInput");a(J8,"admitEncodedImages");a(qKt,"admitEncodedFile");a(UU,"requestImageDimensions");a(fde,"longEdgeDimensions");gde=class extends $t{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 zr("Image batch exceeds the configured image-count limit.","TOO_MANY_IMAGES");if(e.reduce((i,s)=>i+s.data.byteLength,0)>n)throw new zr("Image batch exceeds the configured aggregate image-byte limit.","IMAGES_TOO_LARGE");for(let i of e)if(!r.includes(i.mediaType))throw new zr(`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 J8(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 qKt(this,e)}isAttachmentError(e){return LKt(e)}imageHostPath(e){}saveFile(e){return Promise.reject(new zr("The mounted attachment provider cannot store verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}saveFileStream(e){return Promise.reject(new zr("The mounted attachment provider cannot stream verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}async*readFileStream(e,t){t?.throwIfAborted(),await Promise.reject(new zr("The mounted attachment provider cannot read verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}fileHostPath(e){}readImageRequest(e,t,n){return n?.throwIfAborted(),Promise.reject(new zr("The mounted attachment provider cannot derive model-request images.","ATTACHMENT_PROJECTION_UNSUPPORTED"))}}});var WU={};tn(WU,{buildAuthorizationUrl:()=>QKt,discoverEndpoints:()=>VKt,exchangeCode:()=>JKt,isTokenExpired:()=>ZKt,refreshToken:()=>YKt,registerClient:()=>KKt});function Dqe(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 GKt(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 VKt(e){let t=AbortSignal.timeout(qU),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);q1(i.href);let s=await U2(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);q1(d.href);let p=await U2(d.href,{signal:t});if(!p.ok)throw new Error(`AS metadata failed: HTTP ${p.status}`);let h=await p.json();if(typeof h.authorization_endpoint!="string"||typeof h.token_endpoint!="string")throw new Error("Missing required endpoints in AS metadata");return{authorization:h.authorization_endpoint,token:h.token_endpoint,registration:h.registration_endpoint}}async function KKt(e,t,n){let r=AbortSignal.timeout(qU);q1(e);let i=await U2(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 QKt(e,t,n,r,i){let s=Dqe(32),o=Dqe(64),l=await GKt(o),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:o,redirectUri:n,serverName:r,serverUrl:i,stagedClient:t,createdAt:Date.now()}}}async function JKt(e,t,n,r,i,s){let o=AbortSignal.timeout(qU),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),q1(e);let c=await U2(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:l.toString(),signal:o});if(!c.ok)throw new Error(`Token exchange failed: HTTP ${c.status}`);return Lqe(await c.json())}async function YKt(e,t,n,r){let i=AbortSignal.timeout(qU),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),q1(e);let o=await U2(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 Lqe(await o.json())}function Lqe(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 ZKt(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var qU,jU=W(()=>{"use strict";Q8();qU=1e4;a(Dqe,"randomString");a(GKt,"sha256Base64Url");a(VKt,"discoverEndpoints");a(KKt,"registerClient");a(QKt,"buildAuthorizationUrl");a(JKt,"exchangeCode");a(YKt,"refreshToken");a(Lqe,"parseTokenResponse");a(ZKt,"isTokenExpired")});var hr,Hqe,AT=W(()=>{vr();Wr();hr=class extends Ei{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},Hqe=class extends $t{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new hr("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function t7(e){return XU.test(e)}function eq(e){return e.invocation.modelInvocable}function RT(e){return e.invocation.userInvocable}function $de(e){let t=DJt(e);return[`<skill_content name="${LJt(e.name)}">`,"<skill_resources>",...t,"</skill_resources>","","<skill_instructions>",e.content,"</skill_instructions>","</skill_content>"].join(`
|
|
156
156
|
`)}function DJt(e){let t=e.resourceBase;if(t===void 0)return[`Resources for this skill are managed by provider "${IT(e.provider)}".`,"Load referenced resources only as needed."];switch(t.kind){case"directory":return[`Base directory for this skill: ${IT(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: ${IT(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: ${IT(t.description)}`,"Load referenced resources only as needed."];default:return Ni(t,"SkillResourceBase.kind")}}function LJt(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<")}function IT(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function UJt(e,t){if(Array.isArray(e))return{candidates:e,complete:!0};if(e===null||typeof e!="object")throw pWe(t);let n=e;if(!Array.isArray(n.candidates)||typeof n.complete!="boolean")throw pWe(t);return n}function pWe(e){return new TypeError(`skill provider "${e}" list() must return an array or { candidates, complete } observation`)}function WJt(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:$Jt,locator:e,...e.path!==void 0?{path:e.path}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}function jJt(e,t){if(typeof e.name!="string")throw new TypeError(`skill provider "${t}" returned a non-string skill name`);if(!XU.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(Dde(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 BJt(e){if(!XU.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`);Dde(e.invocation,`runtime skill "${e.name}"`)}function zJt(e){let t=e.name,n=e.description,r=e.whenToUse,i=e.invocation,s=e.source,o=e.provider,l=e.content,c=e.path;if(typeof t!="string")throw new TypeError("loaded skill name must be a string");if(!XU.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(Dde(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 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 HJt(e){let{name:t,description:n,whenToUse:r,invocation:i,source:s,provider:o,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:o,...l!==void 0?{resourceBase:l}:{}}}function Dde(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 GJt(e,t){return gWe(e.name,t.name)}function gWe(e,t){return e<t?-1:e>t?1:0}function VJt(e,t){return e.candidate.rank-t.candidate.rank||e.providerOrder-t.providerOrder||e.localOrder-t.localOrder}function KJt(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 hWe(e,t){return t===void 0?e:(e7(t),new Promise((n,r)=>{let i=a(()=>{t.removeEventListener("abort",s)},"cleanup"),s=a(()=>{i(),r(ZU(t.reason))},"onAbort");t.addEventListener("abort",s,{once:!0}),e.then(o=>{i(),n(o)},o=>{i(),r(ZU(o))})}))}function e7(e){if(e?.aborted===!0)throw ZU(e.reason)}function ZU(e){try{if(e instanceof Error)return e}catch{}return new Error(YU(e))}function YU(e){try{return String(e)}catch{return"[unrenderable thrown value]"}}var XU,dWe,NJt,JU,$Jt,mWe,FJt,fWe,qJt,W2=W(()=>{vr();xs();Kc();Pn();XU=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,dWe=128,NJt=2,JU="runtime",$Jt=250,mWe=600;a(t7,"isSkillName");a(eq,"isModelInvocable");a(RT,"isUserInvocable");a($de,"renderSkillContent");a(DJt,"renderResourceHint");a(LJt,"escapeAttr");a(IT,"escapeText");FJt=class{static{a(this,"SkillLayer")}providers;runtime=new Map;constructor(e){this.providers=new kg(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}},fWe=class extends $t{static{a(this,"SkillRegistry")}static Config=q.object({collectCacheMaxEntries:q.number().default(dWe)});collectCacheMaxEntries;layers=new Sg(e=>new FJt(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??dWe,KJt("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===JU)throw new Error(`"${JU}" is reserved for runtime skill registrations`);let o=this.nextProviderOrder;return this.nextProviderOrder+=1,this.layers.effect(this.ctx,l=>{let c=l.providers.insert(s,{provider:r,order:o});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){BJt(e);let t=pc(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??JU};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=>HJt(n.candidate)).sort(GJt),complete:t.cacheable}}async get(e,t={}){if(!t7(e))return;let n=await this.collect(t);e7(t.signal);let r=n.entries.get(e);if(r===void 0)return;let i=await hWe(r.provider.get(r.candidate,t),t.signal);if(i!==void 0){if(zJt(i),i.name!==r.candidate.name){this.invalidateEntry(r);return}return i}}async collect(e){e7(e.signal);let t=1;for(;;){let n=this.revision,r=this.collectCacheKey(e.cwd,SC(e.scope),n),i=this.collectCache.get(r);if(i!==void 0)return{entries:i,cacheable:!0};let s=await this.collectFresh(e);if(e7(e.signal),n!==this.revision){if(t<NJt){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(VJt);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){e7(t.signal);let n=[],r=!0,i=0;for(let s of[...e.runtime.values()].sort((o,l)=>gWe(o.name,l.name)))n.push({candidate:WJt(s),provider:qJt,providerOrder:-1,localOrder:i,layer:e}),i+=1;for(let{provider:s,order:o}of[...e.providers.values()]){let l=0,c;try{c=await hWe(s.list(t),t.signal)}catch(d){if(t.signal?.aborted===!0)throw ZU(t.signal.reason);r=!1,this.ctx.logger.warn(`skill provider "${s.name}" skipped: ${YU(d)}`)}if(c===void 0)continue;let u=UJt(c,s.name);u.complete||(r=!1);for(let d of u.candidates)jJt(d,s.name),n.push({candidate:d,provider:s,providerOrder:o,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: ${YU(n)}`)})}catch(t){this.ctx.logger.warn(`skills/change listener threw: ${YU(t)}`)}}};a(UJt,"normalizeProviderObservation");a(pWe,"invalidProviderObservation");qJt={name:JU,list(){return Promise.resolve([])},get(e){return Promise.resolve(e.locator)}};a(WJt,"runtimeCandidate");a(jJt,"validateCandidate");a(BJt,"validateRuntimeSkill");a(zJt,"validateDefinition");a(HJt,"toSummary");a(Dde,"validateInvocation");a(GJt,"compareSkillSummary");a(gWe,"compareCodePoints");a(VJt,"compareIndexedCandidates");a(KJt,"assertPositiveInteger");a(hWe,"waitWithAbort");a(e7,"throwIfAborted");a(ZU,"toError");a(YU,"errorMessage")});var Oh,MT=W(()=>{Oh=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 j1,Lje,kpe=W(()=>{vr();j1=class extends Error{static{a(this,"DirectoryPickerError")}code;path;constructor(e,t,n){super(n),this.code=e,this.path=t,this.name="DirectoryPickerError"}},Lje=class extends $t{static{a(this,"DirectoryPicker")}constructor(e){super(e,"directoryPicker")}}});function Knn(){return globalThis.process?.env}function Pze(){return{async env(e){let t=Knn()?.[e];return typeof t=="string"&&t.trim().length>0?t:void 0},async fileExists(e){try{let t=await Cze("node:fs/promises"),n=e;return n.startsWith("~")&&(n=(await Cze("node:os")).homedir()+n.slice(1)),await t.access(n),!0}catch{return!1}}}}var Vnn,Cze,Mze=W(()=>{Vnn=function(e,t){return typeof e=="string"&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(n,r,i,s,o){return r?t?".jsx":".js":i&&(!s||!o)?n:i+s+"."+o.toLowerCase()+"js"}):e},Cze=a(e=>import(Vnn(e)),"importNodeModule");a(Knn,"getProcessEnv");a(Pze,"defaultProviderAuthContext")});function Oze(e){if(e.reason!==void 0)return e.reason;let t=new Error("The operation was aborted");return t.name="AbortError",t}function hf(e){return e??new AbortController().signal}function mf(e,t){return t.aborted?(e.catch(()=>{}),Promise.reject(Oze(t))):new Promise((n,r)=>{let i=!1,s=a(()=>t.removeEventListener("abort",o),"cleanup"),o=a(()=>{i||(i=!0,s(),r(Oze(t)))},"onAbort");t.addEventListener("abort",o,{once:!0}),e.then(l=>{i||(i=!0,s(),n(l))},l=>{i||(i=!0,s(),r(l))}),t.aborted&&o()})}var cW=W(()=>{a(Oze,"abortReason");a(hf,"operationSignal");a(mf,"raceWithAbortSignal")});var uW,Nze=W(()=>{cW();uW=class{static{a(this,"InMemoryCredentialStore")}credentials=new Map;chains=new Map;enqueue(t,n,r){let i=hf(r?.signal),s=this.chains.get(t)??Promise.resolve(),o=(async()=>(await s.catch(()=>{}),i.throwIfAborted(),n()))(),l=o.catch(()=>{});return this.chains.set(t,l),l.then(()=>{this.chains.get(t)===l&&this.chains.delete(t)}),mf(o,i)}async read(t,n){return n?.signal?.throwIfAborted(),this.credentials.get(t)}async list(t){return t?.signal?.throwIfAborted(),[...this.credentials].map(([n,r])=>({providerId:n,type:r.type}))}modify(t,n,r){return this.enqueue(t,async()=>{let i=this.credentials.get(t),s=await n(i);return r?.signal?.throwIfAborted(),s!==void 0&&this.credentials.set(t,s),s??i},r)}delete(t,n){return this.enqueue(t,async()=>{this.credentials.delete(t)},n)}}});function K2(e){return e instanceof Error?e.message||e.name:typeof e=="string"?e:String(e)}function Qnn(e){if(!(e instanceof Error))return{name:"ThrownValue",message:K2(e)};let t=e.code;return{name:e.name||void 0,message:e.message||e.name,stack:e.stack,code:typeof t=="string"||typeof t=="number"?t:void 0}}function dW(e,t,n){return{type:e,timestamp:Date.now(),error:Qnn(t),details:n}}function Q2(e,t){e.diagnostics=[...e.diagnostics??[],t]}var O7=W(()=>{a(K2,"formatThrownValue");a(Qnn,"extractDiagnosticError");a(dW,"createAssistantMessageDiagnostic");a(Q2,"appendAssistantMessageDiagnostic")});function Jnn(e,t){if(t==null)return e;let n=K2(t).trim();return!n||e.includes(n)?e:`${e}: ${n}`}function The(e,t,n,r){let i=hf(r?.signal);return mf(Ynn(e,t,n,r,i),i)}async function Ynn(e,t,n,r,i){i.throwIfAborted();let s=r?.env?Znn(n,r.env):n;if(r?.apiKey!==void 0&&e.auth.apiKey)return Ehe(s,e.auth.apiKey,e.id,{type:"api_key",key:r.apiKey,env:r.env},i);let o=await nrn(t,e.id,i);if(o){if(o.type==="oauth"&&e.auth.oauth)return trn(t,e.id,e.auth.oauth,o,i,r?.minOAuthValidityMs);if(o.type==="api_key"&&e.auth.apiKey){let l=r?.env?{...o,env:{...o.env,...r.env}}:o;return Ehe(s,e.auth.apiKey,e.id,l,i)}return}return e.auth.apiKey?Ehe(s,e.auth.apiKey,e.id,void 0,i):void 0}function Znn(e,t){return{env:a(async n=>t[n]||await e.env(n),"env"),fileExists:a(n=>e.fileExists(n),"fileExists")}}async function trn(e,t,n,r,i,s){let o=Math.max(Xnn,s??0),l=a(u=>Date.now()+o>=u.expires,"expiresSoon"),c=r;if(l(c)){let u;try{u=await e.modify(t,async d=>{if(d?.type==="oauth"&&l(d))try{let p=AbortSignal.any([i,AbortSignal.timeout(ern)]);return await n.refresh(d,p)}catch(p){throw new Yo("oauth",`OAuth refresh failed for ${t}`,{cause:p})}},{signal:i})}catch(d){throw d instanceof Yo?d:new Yo("auth",`Credential store modify failed for ${t}`,{cause:d})}if(u?.type!=="oauth")return;if(c=u,s!==void 0&&l(c))throw new Yo("oauth",`OAuth refresh returned a token that expires too soon for ${t}`)}try{return{auth:await n.toAuth(c),source:"OAuth"}}catch(u){throw new Yo("oauth",`OAuth auth derivation failed for ${t}`,{cause:u})}}async function Ehe(e,t,n,r,i){try{return await t.resolve({ctx:e,credential:r,signal:i})}catch(s){throw new Yo("auth",`API key auth failed for provider ${n}`,{cause:s})}}async function nrn(e,t,n){try{return await e.read(t,{signal:n})}catch(r){throw new Yo("auth",`Credential store read failed for ${t}`,{cause:r})}}var Yo,Xnn,ern,$ze=W(()=>{cW();O7();Yo=class extends Error{static{a(this,"ModelsError")}code;constructor(t,n,r){super(Jnn(n,r?.cause),r),this.name="ModelsError",this.code=t}};a(Jnn,"withCauseDetail");a(The,"resolveProviderAuth");a(Ynn,"resolveProviderAuthWithSignal");a(Znn,"overlayEnvAuthContext");Xnn=300*1e3,ern=15e3;a(trn,"resolveStoredOAuth");a(Ehe,"resolveApiKey");a(nrn,"readCredential")});var XW,Ihe,Ea,ff=W(()=>{XW=class{static{a(this,"FifoQueue")}incoming=[];outgoing=[];get length(){return this.incoming.length+this.outgoing.length}enqueue(t){this.incoming.push(t)}dequeue(){if(this.outgoing.length===0)for(;this.incoming.length>0;)this.outgoing.push(this.incoming.pop());return this.outgoing.pop()}},Ihe=class{static{a(this,"EventStream")}queue=new XW;waiting=new XW;done=!1;finalResultPromise;resolveFinalResult;isComplete;extractResult;constructor(t,n){this.isComplete=t,this.extractResult=n,this.finalResultPromise=new Promise(r=>{this.resolveFinalResult=r})}push(t){if(this.done)return;this.isComplete(t)&&(this.done=!0,this.resolveFinalResult(this.extractResult(t)));let n=this.waiting.dequeue();n?n({value:t,done:!1}):this.queue.enqueue(t)}end(t){for(this.done=!0,t!==void 0&&this.resolveFinalResult(t);this.waiting.length>0;)this.waiting.dequeue()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.dequeue();else{if(this.done)return;{let t=await new Promise(n=>this.waiting.enqueue(n));if(t.done)return;yield t.value}}}result(){return this.finalResultPromise}},Ea=class extends Ihe{static{a(this,"AssistantMessageEventStream")}constructor(){super(t=>t.type==="done"||t.type==="error",t=>{if(t.type==="done")return t.message;if(t.type==="error")return t.error;throw new Error("Unexpected event type for final result")})}}});function zrn(e,t){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"error",errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}function Hrn(e){return typeof e.result=="function"}async function Grn(e,t){for await(let n of t)e.push(n);e.end(Hrn(t)?await t.result():void 0)}function Q1(e,t){let n=new Ea;return t().then(r=>Grn(n,r)).catch(r=>{let i=zrn(e,r);n.push({type:"error",reason:"error",error:i}),n.end(i)}),n}function hl(e,t){let n={stream:a((r,i,s)=>Q1(r,async()=>(await e()).stream(r,i,s)),"stream"),streamSimple:a((r,i,s)=>Q1(r,async()=>(await e()).streamSimple(r,i,s)),"streamSimple")};return t?.fetchDeferred&&(n.fetchDeferred=(r,i,s)=>Q1(r,async()=>{let o=await e();if(!o.fetchDeferred)throw new Error("API does not support deferred responses");return o.fetchDeferred(r,i,s)})),t?.cancelDeferred&&(n.cancelDeferred=async(r,i,s)=>{let o=await e();if(!o.cancelDeferred)throw new Error("API cannot cancel deferred responses");await o.cancelDeferred(r,i,s)}),n}var $h=W(()=>{ff();a(zrn,"createSetupErrorMessage");a(Hrn,"hasResult");a(Grn,"forwardStream");a(Q1,"lazyStream");a(hl,"lazyApi")});var ej,SHe=W(()=>{ej=class{static{a(this,"InMemoryModelsStore")}entries=new Map;async read(t,n){n?.signal?.throwIfAborted();let r=this.entries.get(t);return r?structuredClone(r):void 0}async write(t,n,r){r?.signal?.throwIfAborted(),this.entries.set(t,structuredClone(n))}async delete(t,n){n?.signal?.throwIfAborted(),this.entries.delete(t)}}});function tj(e,t=`
|
|
157
157
|
`){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join(t)}function bc(e){let t=[tj(e.content)];for(let n of Object.values(e.sections??{}))n!==null&&t.push(n);return t.filter(n=>n.length>0).join(`
|
|
158
158
|
|
|
@@ -6443,7 +6443,7 @@ The web search request used endpoint ${JSON.stringify(e)}. Search endpoint confi
|
|
|
6443
6443
|
.error { padding: .75rem; border-radius: .5rem; background: #461d2b; color: #ffd6df; }
|
|
6444
6444
|
.hint { margin: 1.5rem 0 0; font-size: .875rem; }
|
|
6445
6445
|
code { padding: .1rem .3rem; border-radius: .3rem; background: #0c1222; color: #edf2ff; }
|
|
6446
|
-
`}a(J1t,"pageStyles");K8();var cTe="enabled",uTe=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")}),hO=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")}),dTe=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===cTe?"available":"needs-binding","probe")}),TGn=Object.freeze([dTe,hO,uTe]);function pTe(e,t=TGn){return t.filter(n=>n.probe(e)==="available")}a(pTe,"availableEdgeRuntimeProviders");function hTe(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(hTe,"resolveEdgeRuntimeSelection");function rQ(e){let t=pTe(e),{bash:n,container:r}=hTe(t);return t.find(i=>i.id===(r??n)).shell}a(rQ,"resolveEdgeRuntimeShell");function AGn(){return"dsh-edge@0.26.0-alpha.2/direct"}a(AGn,"resolveEdgeDeploymentId");function LS(e){return{baseURL:fxe(e.DEEPSEEK_BASE_URL),maxTokens:vxe(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:eS(e.DEEPSEEK_MODEL),reasoningEffort:gxe(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:SM(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:yxe(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:eb(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(LS,"resolveEdgeDeploymentConfig");function IGn(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(IGn,"edgeDeploymentApiKeyConfigured");function RGn(e){let t=fxe(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(RGn,"projectedEdgeBaseURL");function mTe(e,t){return{shell:rQ(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:AGn(),apiKeyConfigured:IGn(e),baseURL:RGn(e.DEEPSEEK_BASE_URL),maxTokens:vxe(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:eS(e.DEEPSEEK_MODEL),reasoningEffort:gxe(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:SM(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:yxe(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:eb(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(mTe,"resolveEdgeDeploymentProfile");function iQ(e){LS(e);let t=mTe(e);return{ok:!0,service:"dsh-edge",storage:t.storage,attachmentStorage:t.attachmentStorage,shell:t.shell,agent:"upstream-react-loop-agent",access:"single-owner-cookie",deploymentId:t.deploymentId,...e.CF_VERSION_METADATA===void 0?{}:{workerVersionId:e.CF_VERSION_METADATA.id},version:F2,upstreamVersion:Tqe,status:"ready"}}a(iQ,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as Wcr}from"node:async_hooks";import{RpcTarget as CGn}from"cloudflare:workers";function PGn(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(PGn,"startHeartbeat");async function MGn(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(MGn,"probeComputerdHealth");var OGn="computer.internal",NGn="/health",fTe="/api",$Gn=8080,DGn=3e4,LGn=2e4,FGn=1,UGn=2e3,qGn=250,WGn=2e3;function jGn(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(jGn,"bearerMatches");var oQ=class{static{a(this,"CloudflareContainerBackend")}type="cloudflare-container";id;#e;#t;#r;#n;#i;#s;#a;#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??OGn,containerPort:e.containerPort??$Gn,connectTimeoutMs:e.connectTimeoutMs??DGn,heartbeatIntervalMs:e.heartbeatIntervalMs??LGn,restartAttempts:e.restartAttempts??FGn,healthProbeTimeoutMs:e.healthProbeTimeoutMs??UGn,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??qGn,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??WGn}}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 Eu(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 Eu(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.#h(t,e),await this.#v(t,e,s);let o=await this.#m(e),l=OY(o),c,u=new Promise(p=>{let h=!1,m=a(()=>{h||(h=!0,c?.(),p(),this.#l=void 0)},"onClose");o.addEventListener("close",m,{once:!0}),o.addEventListener("error",m,{once:!0}),l.onRpcBroken(m)});this.#e.heartbeatIntervalMs>0&&(c=PGn({intervalMs:this.#e.heartbeatIntervalMs,ping:a(()=>l.sync.watermarks(),"ping"),onFailure:a(()=>{try{o.close()}catch{}},"onFailure")}));let d={rpc:l,runtimeId:i,closed:u,close:a(async()=>{c?.();try{l[Symbol.dispose]?.()}catch{}try{o.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(JR),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(EN),i.delete(JR);let l=new Request(e,{headers:i});return this.#t.gateway.fetch(new Request(o,l))}if(new URL(e.url).pathname!==fTe)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${fTe} requires a websocket upgrade`,{status:400});if(!jGn(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()),l=Math.max(250,Math.floor(o/s)),c=0,u=0,d,p=i;for(;c<s;){c++;let h=Math.min(n,Date.now()+l);if(await this.#f(e,h).then(()=>!0,m=>(d=m,!1)))return p;if(c<s)try{({runtimeId:p}=await e.restart({env:t,enableInternet:this.#t.mode==="direct"})),u++}catch(m){throw this.#a?.(m),this.#o(),new Eu(this.#d("restart",{attempt:c,maxAttempts:s,restarts:u,lastError:m}),{cause:m})}}throw this.#a?.(new Error("computerd never became healthy")),this.#o(),new Eu(this.#d("health",{attempt:c,maxAttempts:s,restarts:u,lastError:d,priorExit:r}),d instanceof Error?{cause:d}:void 0)}async#f(e,t){let n=this.#e.healthRetryInitialDelayMs,r;for(;Date.now()<t;)try{await MGn(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 BGn(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=${Y1t(t.lastError)}`}async#h(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 Eu(`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:NGn,api:fTe,healthTimeoutMs:r})})}catch(s){throw this.#a?.(s),this.#o(),new Eu(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${Y1t(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 Eu(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect returned ${i.status}: ${s}`,{cause:o})}}async#m(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 Eu(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#o()}}};function BGn(e){return new Promise(t=>setTimeout(t,e))}a(BGn,"sleep");function Y1t(e){return e instanceof Error?e.message:String(e)}a(Y1t,"describeError");var Z1t="computer:container-client-secret",zGn=16;function HGn(){let e=crypto.getRandomValues(new Uint8Array(zGn));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(HGn,"generate");var GGn=class{static{a(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(Z1t);if(typeof e=="string"&&e.length>0)return e;let t=HGn();return await this.storage.put(Z1t,t),t}},X1t="computer:container-launch-record";async function eyt(e){return{enableInternet:e.enableInternet,envDigest:await KGn(e.env)}}a(eyt,"launchRecordFor");function VGn(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}a(VGn,"sameLaunch");async function KGn(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(KGn,"digestEnv");var QGn=class{static{a(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(X1t)??null}async set(e){await this.storage.put(X1t,e)}},tyt=new WeakMap;function vTe(e){let t=tyt.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},tyt.set(e,t)),t}a(vTe,"getContainerLifecycle");function sQ(e){return vTe(e).exit}a(sQ,"containerExitInfo");function nyt(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}a(nyt,"formatExitReason");function ryt(e,t,n){let r=vTe(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>iyt(r,i,void 0,n),s=>iyt(r,i,s,n))}a(ryt,"installContainerMonitor");async function gTe(e,t){let n=vTe(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}a(gTe,"destroyContainerExpectingExit");async function iyt(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=nyt(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(l){console.error({message:"workspace.container.exit_cleanup_failed",reason:nyt(l),exitedAt:Date.now()})}}a(iyt,"recordExit");var yTe="computer:container-runtime-identity",JGn=class{static{a(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(yTe)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(yTe,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(yTe)}},YGn=class extends CGn{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 JGn(e.storage),this.#n=new GGn(e.storage),this.#i=new QGn(e.storage)}async start(e){let t=sQ(this.#t),n=await this.#n.ensure(),r=await eyt(e);if(t!==null){try{await gTe(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||!VGn(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 gTe(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return ryt(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await gTe(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await eyt(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),ryt(this.#t,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:sQ(this.#t)}}async exitInfo(){return sQ(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=sQ(this.#t);if(r!==null)throw new Eu(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function syt(e){class t extends e{static{a(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new YGn(this.ctx)}}return t}a(syt,"withWorkspaceContainer");var ZGn={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function ayt(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),l=ZGn[s]??s,c=e[l];if(c===void 0)return;let u=c[o];return typeof u=="function"?u:void 0}a(ayt,"resolve");function XGn(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}a(XGn,"errorResponse");async function xTe(e,t,n,r,i){let s=ayt(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}a(xTe,"callEdgeApi");async function lyt(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(ayt(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",l=s.payload??{};try{let c=await xTe(e,i,o,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 XGn(o,{code:"internal",message:String(c),details:{}})}}a(lyt,"dispatchEdgeApi");Wr();Lo();Xv();import{DurableObject as jcr}from"cloudflare:workers";var aQ=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 eVn(this.stopping,t);continue}await new Promise((r,i)=>{let s=a(()=>{t?.removeEventListener("abort",o),r()},"wake"),o=a(()=>{let l=this.waiters.indexOf(s);l!==-1&&this.waiters.splice(l,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 eVn(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(eVn,"untilAborted");import{WorkerEntrypoint as d7i}from"cloudflare:workers";var m_=sc(cyt());import{gunzipSync as sQn}from"node:zlib";var mO=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),l=this.removeEmpty(this.tokenize(s,r)),c=this.removeEmpty(this.tokenize(o,r));return this.diffWithOptionsObj(l,c,r,i)}diffWithOptionsObj(t,n,r,i){var s;let o=a(w=>{if(w=this.postProcess(w,r),i){setTimeout(function(){i(w)},0);return}else return w},"done"),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,h=Date.now()+p,m=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(m[0],n,t,0,r);if(m[0].oldPos+1>=c&&f+1>=l)return o(this.buildValues(m[0].lastComponent,n,t));let g=-1/0,v=1/0,x=a(()=>{for(let w=Math.max(g,-u);w<=Math.min(v,u);w+=2){let b,k=m[w-1],E=m[w+1];k&&(m[w-1]=void 0);let A=!1;if(E){let O=E.oldPos-w;A=E&&0<=O&&O<l}let I=k&&k.oldPos+1<c;if(!A&&!I){m[w]=void 0;continue}if(!I||A&&k.oldPos<E.oldPos?b=this.addToPath(E,!0,!1,0,r):b=this.addToPath(k,!1,!0,1,r),f=this.extractCommon(b,n,t,w,r),b.oldPos+1>=c&&f+1>=l)return o(this.buildValues(b.lastComponent,n,t))||!0;m[w]=b,b.oldPos+1>=c&&(v=Math.min(v,w-1)),f+1>=l&&(g=Math.max(g,w+1))}u++},"execEditLength");if(i)a(function w(){setTimeout(function(){if(u>d||Date.now()>h)return i(void 0);x()||w()},0)},"exec")();else for(;u<=d&&Date.now()<=h;){let w=x();if(w)return w}}addToPath(t,n,r,i,s){let o=t.lastComponent;return o&&!s.oneChangePerToken&&o.added===n&&o.removed===r?{oldPos:t.oldPos+i,lastComponent:{count:o.count+1,added:n,removed:r,previousComponent:o.previousComponent}}:{oldPos:t.oldPos+i,lastComponent:{count:1,added:n,removed:r,previousComponent:o}}}extractCommon(t,n,r,i,s){let o=n.length,l=r.length,c=t.oldPos,u=c-i,d=0;for(;u+1<o&&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 o=i.length,l=0,c=0,u=0;for(;l<o;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(h,m){let f=r[u+m];return f.length>h.length?f:h}),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 wTe=class extends mO{static{a(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=nVn}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
|
|
6446
|
+
`}a(J1t,"pageStyles");K8();var cTe="enabled",uTe=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")}),hO=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")}),dTe=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===cTe?"available":"needs-binding","probe")}),TGn=Object.freeze([dTe,hO,uTe]);function pTe(e,t=TGn){return t.filter(n=>n.probe(e)==="available")}a(pTe,"availableEdgeRuntimeProviders");function hTe(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(hTe,"resolveEdgeRuntimeSelection");function rQ(e){let t=pTe(e),{bash:n,container:r}=hTe(t);return t.find(i=>i.id===(r??n)).shell}a(rQ,"resolveEdgeRuntimeShell");function AGn(){return"dsh-edge@0.26.0/direct"}a(AGn,"resolveEdgeDeploymentId");function LS(e){return{baseURL:fxe(e.DEEPSEEK_BASE_URL),maxTokens:vxe(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:eS(e.DEEPSEEK_MODEL),reasoningEffort:gxe(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:SM(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:yxe(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:eb(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(LS,"resolveEdgeDeploymentConfig");function IGn(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(IGn,"edgeDeploymentApiKeyConfigured");function RGn(e){let t=fxe(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(RGn,"projectedEdgeBaseURL");function mTe(e,t){return{shell:rQ(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:AGn(),apiKeyConfigured:IGn(e),baseURL:RGn(e.DEEPSEEK_BASE_URL),maxTokens:vxe(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:eS(e.DEEPSEEK_MODEL),reasoningEffort:gxe(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:SM(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:yxe(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:eb(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(mTe,"resolveEdgeDeploymentProfile");function iQ(e){LS(e);let t=mTe(e);return{ok:!0,service:"dsh-edge",storage:t.storage,attachmentStorage:t.attachmentStorage,shell:t.shell,agent:"upstream-react-loop-agent",access:"single-owner-cookie",deploymentId:t.deploymentId,...e.CF_VERSION_METADATA===void 0?{}:{workerVersionId:e.CF_VERSION_METADATA.id},version:F2,upstreamVersion:Tqe,status:"ready"}}a(iQ,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as Wcr}from"node:async_hooks";import{RpcTarget as CGn}from"cloudflare:workers";function PGn(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(PGn,"startHeartbeat");async function MGn(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(MGn,"probeComputerdHealth");var OGn="computer.internal",NGn="/health",fTe="/api",$Gn=8080,DGn=3e4,LGn=2e4,FGn=1,UGn=2e3,qGn=250,WGn=2e3;function jGn(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(jGn,"bearerMatches");var oQ=class{static{a(this,"CloudflareContainerBackend")}type="cloudflare-container";id;#e;#t;#r;#n;#i;#s;#a;#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??OGn,containerPort:e.containerPort??$Gn,connectTimeoutMs:e.connectTimeoutMs??DGn,heartbeatIntervalMs:e.heartbeatIntervalMs??LGn,restartAttempts:e.restartAttempts??FGn,healthProbeTimeoutMs:e.healthProbeTimeoutMs??UGn,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??qGn,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??WGn}}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 Eu(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 Eu(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.#h(t,e),await this.#v(t,e,s);let o=await this.#m(e),l=OY(o),c,u=new Promise(p=>{let h=!1,m=a(()=>{h||(h=!0,c?.(),p(),this.#l=void 0)},"onClose");o.addEventListener("close",m,{once:!0}),o.addEventListener("error",m,{once:!0}),l.onRpcBroken(m)});this.#e.heartbeatIntervalMs>0&&(c=PGn({intervalMs:this.#e.heartbeatIntervalMs,ping:a(()=>l.sync.watermarks(),"ping"),onFailure:a(()=>{try{o.close()}catch{}},"onFailure")}));let d={rpc:l,runtimeId:i,closed:u,close:a(async()=>{c?.();try{l[Symbol.dispose]?.()}catch{}try{o.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(JR),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(EN),i.delete(JR);let l=new Request(e,{headers:i});return this.#t.gateway.fetch(new Request(o,l))}if(new URL(e.url).pathname!==fTe)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${fTe} requires a websocket upgrade`,{status:400});if(!jGn(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()),l=Math.max(250,Math.floor(o/s)),c=0,u=0,d,p=i;for(;c<s;){c++;let h=Math.min(n,Date.now()+l);if(await this.#f(e,h).then(()=>!0,m=>(d=m,!1)))return p;if(c<s)try{({runtimeId:p}=await e.restart({env:t,enableInternet:this.#t.mode==="direct"})),u++}catch(m){throw this.#a?.(m),this.#o(),new Eu(this.#d("restart",{attempt:c,maxAttempts:s,restarts:u,lastError:m}),{cause:m})}}throw this.#a?.(new Error("computerd never became healthy")),this.#o(),new Eu(this.#d("health",{attempt:c,maxAttempts:s,restarts:u,lastError:d,priorExit:r}),d instanceof Error?{cause:d}:void 0)}async#f(e,t){let n=this.#e.healthRetryInitialDelayMs,r;for(;Date.now()<t;)try{await MGn(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 BGn(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=${Y1t(t.lastError)}`}async#h(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 Eu(`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:NGn,api:fTe,healthTimeoutMs:r})})}catch(s){throw this.#a?.(s),this.#o(),new Eu(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${Y1t(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 Eu(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect returned ${i.status}: ${s}`,{cause:o})}}async#m(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 Eu(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#o()}}};function BGn(e){return new Promise(t=>setTimeout(t,e))}a(BGn,"sleep");function Y1t(e){return e instanceof Error?e.message:String(e)}a(Y1t,"describeError");var Z1t="computer:container-client-secret",zGn=16;function HGn(){let e=crypto.getRandomValues(new Uint8Array(zGn));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(HGn,"generate");var GGn=class{static{a(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(Z1t);if(typeof e=="string"&&e.length>0)return e;let t=HGn();return await this.storage.put(Z1t,t),t}},X1t="computer:container-launch-record";async function eyt(e){return{enableInternet:e.enableInternet,envDigest:await KGn(e.env)}}a(eyt,"launchRecordFor");function VGn(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}a(VGn,"sameLaunch");async function KGn(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(KGn,"digestEnv");var QGn=class{static{a(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(X1t)??null}async set(e){await this.storage.put(X1t,e)}},tyt=new WeakMap;function vTe(e){let t=tyt.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},tyt.set(e,t)),t}a(vTe,"getContainerLifecycle");function sQ(e){return vTe(e).exit}a(sQ,"containerExitInfo");function nyt(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}a(nyt,"formatExitReason");function ryt(e,t,n){let r=vTe(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>iyt(r,i,void 0,n),s=>iyt(r,i,s,n))}a(ryt,"installContainerMonitor");async function gTe(e,t){let n=vTe(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}a(gTe,"destroyContainerExpectingExit");async function iyt(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=nyt(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(l){console.error({message:"workspace.container.exit_cleanup_failed",reason:nyt(l),exitedAt:Date.now()})}}a(iyt,"recordExit");var yTe="computer:container-runtime-identity",JGn=class{static{a(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(yTe)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(yTe,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(yTe)}},YGn=class extends CGn{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 JGn(e.storage),this.#n=new GGn(e.storage),this.#i=new QGn(e.storage)}async start(e){let t=sQ(this.#t),n=await this.#n.ensure(),r=await eyt(e);if(t!==null){try{await gTe(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||!VGn(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 gTe(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return ryt(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await gTe(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await eyt(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),ryt(this.#t,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:sQ(this.#t)}}async exitInfo(){return sQ(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=sQ(this.#t);if(r!==null)throw new Eu(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function syt(e){class t extends e{static{a(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new YGn(this.ctx)}}return t}a(syt,"withWorkspaceContainer");var ZGn={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function ayt(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),l=ZGn[s]??s,c=e[l];if(c===void 0)return;let u=c[o];return typeof u=="function"?u:void 0}a(ayt,"resolve");function XGn(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}a(XGn,"errorResponse");async function xTe(e,t,n,r,i){let s=ayt(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}a(xTe,"callEdgeApi");async function lyt(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(ayt(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",l=s.payload??{};try{let c=await xTe(e,i,o,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 XGn(o,{code:"internal",message:String(c),details:{}})}}a(lyt,"dispatchEdgeApi");Wr();Lo();Xv();import{DurableObject as jcr}from"cloudflare:workers";var aQ=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 eVn(this.stopping,t);continue}await new Promise((r,i)=>{let s=a(()=>{t?.removeEventListener("abort",o),r()},"wake"),o=a(()=>{let l=this.waiters.indexOf(s);l!==-1&&this.waiters.splice(l,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 eVn(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(eVn,"untilAborted");import{WorkerEntrypoint as d7i}from"cloudflare:workers";var m_=sc(cyt());import{gunzipSync as sQn}from"node:zlib";var mO=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),l=this.removeEmpty(this.tokenize(s,r)),c=this.removeEmpty(this.tokenize(o,r));return this.diffWithOptionsObj(l,c,r,i)}diffWithOptionsObj(t,n,r,i){var s;let o=a(w=>{if(w=this.postProcess(w,r),i){setTimeout(function(){i(w)},0);return}else return w},"done"),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,h=Date.now()+p,m=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(m[0],n,t,0,r);if(m[0].oldPos+1>=c&&f+1>=l)return o(this.buildValues(m[0].lastComponent,n,t));let g=-1/0,v=1/0,x=a(()=>{for(let w=Math.max(g,-u);w<=Math.min(v,u);w+=2){let b,k=m[w-1],E=m[w+1];k&&(m[w-1]=void 0);let A=!1;if(E){let O=E.oldPos-w;A=E&&0<=O&&O<l}let I=k&&k.oldPos+1<c;if(!A&&!I){m[w]=void 0;continue}if(!I||A&&k.oldPos<E.oldPos?b=this.addToPath(E,!0,!1,0,r):b=this.addToPath(k,!1,!0,1,r),f=this.extractCommon(b,n,t,w,r),b.oldPos+1>=c&&f+1>=l)return o(this.buildValues(b.lastComponent,n,t))||!0;m[w]=b,b.oldPos+1>=c&&(v=Math.min(v,w-1)),f+1>=l&&(g=Math.max(g,w+1))}u++},"execEditLength");if(i)a(function w(){setTimeout(function(){if(u>d||Date.now()>h)return i(void 0);x()||w()},0)},"exec")();else for(;u<=d&&Date.now()<=h;){let w=x();if(w)return w}}addToPath(t,n,r,i,s){let o=t.lastComponent;return o&&!s.oneChangePerToken&&o.added===n&&o.removed===r?{oldPos:t.oldPos+i,lastComponent:{count:o.count+1,added:n,removed:r,previousComponent:o.previousComponent}}:{oldPos:t.oldPos+i,lastComponent:{count:1,added:n,removed:r,previousComponent:o}}}extractCommon(t,n,r,i,s){let o=n.length,l=r.length,c=t.oldPos,u=c-i,d=0;for(;u+1<o&&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 o=i.length,l=0,c=0,u=0;for(;l<o;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(h,m){let f=r[u+m];return f.length>h.length?f:h}),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 wTe=class extends mO{static{a(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=nVn}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
|
|
6447
6447
|
`))&&(t=t.trim()),(!r.newlineIsToken||!n.includes(`
|
|
6448
6448
|
`))&&(n=n.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
|
|
6449
6449
|
`)&&(t=t.slice(0,-1)),n.endsWith(`
|
package/worker/isolated/index.js
CHANGED
|
@@ -152,7 +152,7 @@ Known schemas:
|
|
|
152
152
|
- `)}`,new Error(tt)}let It=`${l}/$ref`,ht=Ro(e,He,n,r,i,s,o,It,c);if(ht.valid||Ie.push({instanceLocation:o,keyword:"$ref",keywordLocation:It,error:"A subschema had errors."},...ht.errors),n==="4"||n==="7")return{valid:Ie.length===0,errors:Ie}}if(Array.isArray(m)){let Je=m.length,He=!1;for(let It=0;It<Je;It++)if(d===m[It]||m[It]==="integer"&&d==="number"&&e%1===0&&e===e){He=!0;break}He||Ie.push({instanceLocation:o,keyword:"type",keywordLocation:`${l}/type`,error:`Instance type "${d}" is invalid. Expected "${m.join('", "')}".`})}else m==="integer"?(d!=="number"||e%1||e!==e)&&Ie.push({instanceLocation:o,keyword:"type",keywordLocation:`${l}/type`,error:`Instance type "${d}" is invalid. Expected "${m}".`}):m!==void 0&&d!==m&&Ie.push({instanceLocation:o,keyword:"type",keywordLocation:`${l}/type`,error:`Instance type "${d}" is invalid. Expected "${m}".`});if(y!==void 0&&(d==="object"||d==="array"?BS(e,y)||Ie.push({instanceLocation:o,keyword:"const",keywordLocation:`${l}/const`,error:`Instance does not match ${JSON.stringify(y)}.`}):e!==y&&Ie.push({instanceLocation:o,keyword:"const",keywordLocation:`${l}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})),x!==void 0&&(d==="object"||d==="array"?x.some(Je=>BS(e,Je))||Ie.push({instanceLocation:o,keyword:"enum",keywordLocation:`${l}/enum`,error:`Instance does not match any of ${JSON.stringify(x)}.`}):x.some(Je=>e===Je)||Ie.push({instanceLocation:o,keyword:"enum",keywordLocation:`${l}/enum`,error:`Instance does not match any of ${JSON.stringify(x)}.`})),w!==void 0){let Je=`${l}/not`;Ro(e,w,n,r,i,s,o,Je).valid&&Ie.push({instanceLocation:o,keyword:"not",keywordLocation:Je,error:'Instance matched "not" schema.'})}let xt=[];if(_!==void 0){let Je=`${l}/anyOf`,He=Ie.length,It=!1;for(let ht=0;ht<_.length;ht++){let tt=_[ht],Tt=Object.create(c),Le=Ro(e,tt,n,r,i,f===!0?s:null,o,`${Je}/${ht}`,Tt);Ie.push(...Le.errors),It=It||Le.valid,Le.valid&&xt.push(Tt)}It?Ie.length=He:Ie.splice(He,0,{instanceLocation:o,keyword:"anyOf",keywordLocation:Je,error:"Instance does not match any subschemas."})}if(S!==void 0){let Je=`${l}/allOf`,He=Ie.length,It=!0;for(let ht=0;ht<S.length;ht++){let tt=S[ht],Tt=Object.create(c),Le=Ro(e,tt,n,r,i,f===!0?s:null,o,`${Je}/${ht}`,Tt);Ie.push(...Le.errors),It=It&&Le.valid,Le.valid&&xt.push(Tt)}It?Ie.length=He:Ie.splice(He,0,{instanceLocation:o,keyword:"allOf",keywordLocation:Je,error:"Instance does not match every subschema."})}if(T!==void 0){let Je=`${l}/oneOf`,He=Ie.length,It=T.filter((ht,tt)=>{let Tt=Object.create(c),Le=Ro(e,ht,n,r,i,f===!0?s:null,o,`${Je}/${tt}`,Tt);return Ie.push(...Le.errors),Le.valid&&xt.push(Tt),Le.valid}).length;It===1?Ie.length=He:Ie.splice(He,0,{instanceLocation:o,keyword:"oneOf",keywordLocation:Je,error:`Instance does not match exactly one subschema (${It} matches).`})}if((d==="object"||d==="array")&&Object.assign(c,...xt),A!==void 0){let Je=`${l}/if`;if(Ro(e,A,n,r,i,s,o,Je,c).valid){if(O!==void 0){let It=Ro(e,O,n,r,i,s,o,`${l}/then`,c);It.valid||Ie.push({instanceLocation:o,keyword:"if",keywordLocation:Je,error:'Instance does not match "then" schema.'},...It.errors)}}else if(N!==void 0){let It=Ro(e,N,n,r,i,s,o,`${l}/else`,c);It.valid||Ie.push({instanceLocation:o,keyword:"if",keywordLocation:Je,error:'Instance does not match "else" schema.'},...It.errors)}}if(d==="object"){if(v!==void 0)for(let ht of v)ht in e||Ie.push({instanceLocation:o,keyword:"required",keywordLocation:`${l}/required`,error:`Instance does not have required property "${ht}".`});let Je=Object.keys(e);if(I!==void 0&&Je.length<I&&Ie.push({instanceLocation:o,keyword:"minProperties",keywordLocation:`${l}/minProperties`,error:`Instance does not have at least ${I} properties.`}),H!==void 0&&Je.length>H&&Ie.push({instanceLocation:o,keyword:"maxProperties",keywordLocation:`${l}/maxProperties`,error:`Instance does not have at least ${H} properties.`}),C!==void 0){let ht=`${l}/propertyNames`;for(let tt in e){let Tt=`${o}/${Ld(tt)}`,Le=Ro(tt,C,n,r,i,s,Tt,ht);Le.valid||Ie.push({instanceLocation:o,keyword:"propertyNames",keywordLocation:ht,error:`Property name "${tt}" does not match schema.`},...Le.errors)}}if(P!==void 0){let ht=`${l}/dependantRequired`;for(let tt in P)if(tt in e){let Tt=P[tt];for(let Le of Tt)Le in e||Ie.push({instanceLocation:o,keyword:"dependentRequired",keywordLocation:ht,error:`Instance has "${tt}" but does not have "${Le}".`})}}if($!==void 0)for(let ht in $){let tt=`${l}/dependentSchemas`;if(ht in e){let Tt=Ro(e,$[ht],n,r,i,s,o,`${tt}/${Ld(ht)}`,c);Tt.valid||Ie.push({instanceLocation:o,keyword:"dependentSchemas",keywordLocation:tt,error:`Instance has "${ht}" but does not match dependant schema.`},...Tt.errors)}}if(U!==void 0){let ht=`${l}/dependencies`;for(let tt in U)if(tt in e){let Tt=U[tt];if(Array.isArray(Tt))for(let Le of Tt)Le in e||Ie.push({instanceLocation:o,keyword:"dependencies",keywordLocation:ht,error:`Instance has "${tt}" but does not have "${Le}".`});else{let Le=Ro(e,Tt,n,r,i,s,o,`${ht}/${Ld(tt)}`);Le.valid||Ie.push({instanceLocation:o,keyword:"dependencies",keywordLocation:ht,error:`Instance has "${tt}" but does not match dependant schema.`},...Le.errors)}}}let He=Object.create(null),It=!1;if(L!==void 0){let ht=`${l}/properties`;for(let tt in L){if(!(tt in e))continue;let Tt=`${o}/${Ld(tt)}`,Le=Ro(e[tt],L[tt],n,r,i,s,Tt,`${ht}/${Ld(tt)}`);if(Le.valid)c[tt]=He[tt]=!0;else if(It=i,Ie.push({instanceLocation:o,keyword:"properties",keywordLocation:ht,error:`Property "${tt}" does not match schema.`},...Le.errors),It)break}}if(!It&&D!==void 0){let ht=`${l}/patternProperties`;for(let tt in D){let Tt=new RegExp(tt,"u"),Le=D[tt];for(let Dt in e){if(!Tt.test(Dt))continue;let an=`${o}/${Ld(Dt)}`,kt=Ro(e[Dt],Le,n,r,i,s,an,`${ht}/${Ld(tt)}`);kt.valid?c[Dt]=He[Dt]=!0:(It=i,Ie.push({instanceLocation:o,keyword:"patternProperties",keywordLocation:ht,error:`Property "${Dt}" matches pattern "${tt}" but does not match associated schema.`},...kt.errors))}}}if(!It&&z!==void 0){let ht=`${l}/additionalProperties`;for(let tt in e){if(He[tt])continue;let Tt=`${o}/${Ld(tt)}`,Le=Ro(e[tt],z,n,r,i,s,Tt,ht);Le.valid?c[tt]=!0:(It=i,Ie.push({instanceLocation:o,keyword:"additionalProperties",keywordLocation:ht,error:`Property "${tt}" does not match additional properties schema.`},...Le.errors))}}else if(!It&&Z!==void 0){let ht=`${l}/unevaluatedProperties`;for(let tt in e)if(!c[tt]){let Tt=`${o}/${Ld(tt)}`,Le=Ro(e[tt],Z,n,r,i,s,Tt,ht);Le.valid?c[tt]=!0:Ie.push({instanceLocation:o,keyword:"unevaluatedProperties",keywordLocation:ht,error:`Property "${tt}" does not match unevaluated properties schema.`},...Le.errors)}}}else if(d==="array"){he!==void 0&&e.length>he&&Ie.push({instanceLocation:o,keyword:"maxItems",keywordLocation:`${l}/maxItems`,error:`Array has too many items (${e.length} > ${he}).`}),_e!==void 0&&e.length<_e&&Ie.push({instanceLocation:o,keyword:"minItems",keywordLocation:`${l}/minItems`,error:`Array has too few items (${e.length} < ${_e}).`});let Je=e.length,He=0,It=!1;if(j!==void 0){let ht=`${l}/prefixItems`,tt=Math.min(j.length,Je);for(;He<tt;He++){let Tt=Ro(e[He],j[He],n,r,i,s,`${o}/${He}`,`${ht}/${He}`);if(c[He]=!0,!Tt.valid&&(It=i,Ie.push({instanceLocation:o,keyword:"prefixItems",keywordLocation:ht,error:"Items did not match schema."},...Tt.errors),It))break}}if(Q!==void 0){let ht=`${l}/items`;if(Array.isArray(Q)){let tt=Math.min(Q.length,Je);for(;He<tt;He++){let Tt=Ro(e[He],Q[He],n,r,i,s,`${o}/${He}`,`${ht}/${He}`);if(c[He]=!0,!Tt.valid&&(It=i,Ie.push({instanceLocation:o,keyword:"items",keywordLocation:ht,error:"Items did not match schema."},...Tt.errors),It))break}}else for(;He<Je;He++){let tt=Ro(e[He],Q,n,r,i,s,`${o}/${He}`,ht);if(c[He]=!0,!tt.valid&&(It=i,Ie.push({instanceLocation:o,keyword:"items",keywordLocation:ht,error:"Items did not match schema."},...tt.errors),It))break}if(!It&&ee!==void 0){let tt=`${l}/additionalItems`;for(;He<Je;He++){let Tt=Ro(e[He],ee,n,r,i,s,`${o}/${He}`,tt);c[He]=!0,Tt.valid||(It=i,Ie.push({instanceLocation:o,keyword:"additionalItems",keywordLocation:tt,error:"Items did not match additional items schema."},...Tt.errors))}}}if(V!==void 0)if(Je===0&&ie===void 0)Ie.push({instanceLocation:o,keyword:"contains",keywordLocation:`${l}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(ie!==void 0&&Je<ie)Ie.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${l}/minContains`,error:`Array has less items (${Je}) than minContains (${ie}).`});else{let ht=`${l}/contains`,tt=Ie.length,Tt=0;for(let Le=0;Le<Je;Le++){let Dt=Ro(e[Le],V,n,r,i,s,`${o}/${Le}`,ht);Dt.valid?(c[Le]=!0,Tt++):Ie.push(...Dt.errors)}Tt>=(ie||0)&&(Ie.length=tt),ie===void 0&&be===void 0&&Tt===0?Ie.splice(tt,0,{instanceLocation:o,keyword:"contains",keywordLocation:ht,error:"Array does not contain item matching schema."}):ie!==void 0&&Tt<ie?Ie.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${l}/minContains`,error:`Array must contain at least ${ie} items matching schema. Only ${Tt} items were found.`}):be!==void 0&&Tt>be&&Ie.push({instanceLocation:o,keyword:"maxContains",keywordLocation:`${l}/maxContains`,error:`Array may contain at most ${be} items matching schema. ${Tt} items were found.`})}if(!It&&X!==void 0){let ht=`${l}/unevaluatedItems`;for(He;He<Je;He++){if(c[He])continue;let tt=Ro(e[He],X,n,r,i,s,`${o}/${He}`,ht);c[He]=!0,tt.valid||Ie.push({instanceLocation:o,keyword:"unevaluatedItems",keywordLocation:ht,error:"Items did not match unevaluated items schema."},...tt.errors)}}if(Te)for(let ht=0;ht<Je;ht++){let tt=e[ht],Tt=typeof tt=="object"&&tt!==null;for(let Le=0;Le<Je;Le++){if(ht===Le)continue;let Dt=e[Le];(tt===Dt||Tt&&(typeof Dt=="object"&&Dt!==null)&&BS(tt,Dt))&&(Ie.push({instanceLocation:o,keyword:"uniqueItems",keywordLocation:`${l}/uniqueItems`,error:`Duplicate items at indexes ${ht} and ${Le}.`}),ht=Number.MAX_SAFE_INTEGER,Le=Number.MAX_SAFE_INTEGER)}}}else if(d==="number"){if(n==="4"?(Ce!==void 0&&(me===!0&&e<=Ce||e<Ce)&&Ie.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${l}/minimum`,error:`${e} is less than ${me?"or equal to ":""} ${Ce}.`}),fe!==void 0&&(ft===!0&&e>=fe||e>fe)&&Ie.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${l}/maximum`,error:`${e} is greater than ${ft?"or equal to ":""} ${fe}.`})):(Ce!==void 0&&e<Ce&&Ie.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${l}/minimum`,error:`${e} is less than ${Ce}.`}),fe!==void 0&&e>fe&&Ie.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${l}/maximum`,error:`${e} is greater than ${fe}.`}),me!==void 0&&e<=me&&Ie.push({instanceLocation:o,keyword:"exclusiveMinimum",keywordLocation:`${l}/exclusiveMinimum`,error:`${e} is less than ${me}.`}),ft!==void 0&&e>=ft&&Ie.push({instanceLocation:o,keyword:"exclusiveMaximum",keywordLocation:`${l}/exclusiveMaximum`,error:`${e} is greater than or equal to ${ft}.`})),Xe!==void 0){let Je=e%Xe;Math.abs(0-Je)>=11920929e-14&&Math.abs(Xe-Je)>=11920929e-14&&Ie.push({instanceLocation:o,keyword:"multipleOf",keywordLocation:`${l}/multipleOf`,error:`${e} is not a multiple of ${Xe}.`})}}else if(d==="string"){let Je=dt===void 0&&$e===void 0?0:h$e(e);dt!==void 0&&Je<dt&&Ie.push({instanceLocation:o,keyword:"minLength",keywordLocation:`${l}/minLength`,error:`String is too short (${Je} < ${dt}).`}),$e!==void 0&&Je>$e&&Ie.push({instanceLocation:o,keyword:"maxLength",keywordLocation:`${l}/maxLength`,error:`String is too long (${Je} > ${$e}).`}),Ae!==void 0&&!new RegExp(Ae,"u").test(e)&&Ie.push({instanceLocation:o,keyword:"pattern",keywordLocation:`${l}/pattern`,error:"String does not match pattern."}),B!==void 0&&Hae[B]&&!Hae[B](e)&&Ie.push({instanceLocation:o,keyword:"format",keywordLocation:`${l}/format`,error:`String does not match format "${B}".`})}return{valid:Ie.length===0,errors:Ie}}var Kae=F(()=>{zae();sL();Gae();iL();Vae();a(Ro,"validate")});var oL,f$e=F(()=>{sL();Kae();oL=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=C0(t)}validate(t){return Ro(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,n){n&&(t={...t,$id:n}),C0(t,this.lookup)}}});var m$e=F(()=>{zae();sL();Gae();iL();p$e();Vae();Kae();f$e()});var aL,g$e=F(()=>{m$e();aL=class{static{a(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let n=new oL(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 ka,lL=F(()=>{"use strict";ka={probeTimeoutMs:3e4,callTimeoutMs:6e4,maxToolsPerServer:128,maxCatalogPages:10,maxCatalogBytes:131072,maxDescriptionLength:512,maxErrorMessageChars:300,maxPublicNameLength:64,maxInstructionsLength:1024,metaToolThreshold:20}});import{createHash as HFt}from"node:crypto";function VFt(e){let t=e.replace(/[.*+?^${}()|[\]\\]/gu,n=>n==="*"?"\0":`\\${n}`);return new RegExp(`^${t.replaceAll("\0",".*")}$`)}function y$e(e,t,n){let r=t??"read_only";return r==="allow_all"?"allow":r==="approve_all"?"ask":n===!0?"allow":n===!1?"ask":GFt.some(i=>VFt(i).test(e))?"allow":"ask"}function Um(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,ka.maxErrorMessageChars)}function x$e(e,t){let n=`mcp__${e}__${t}`,r=n.replace(/[^A-Za-z0-9_-]/gu,"_");if(r===n&&r.length<=ka.maxPublicNameLength)return r;let i=KFt(e,t),s=ka.maxPublicNameLength-i.length-1;return`${r.slice(0,s)}_${i}`}function KFt(e,t){return HFt("sha256").update(`${e}\0${t}`).digest("hex").slice(0,12)}function v$e(e){if(!(e==null||typeof e!="object"))try{let t=JSON.parse(JSON.stringify(e));return Iv(t),t}catch{return}}function ZFt(e){return QFt.has(e)}function w$e(e){return e.type!=="image"||e.data===void 0||e.mimeType===void 0||!ZFt(e.mimeType)||!JFt.test(e.data)?void 0:{data:Uint8Array.from(atob(e.data),n=>n.charCodeAt(0)),mediaType:e.mimeType}}function b$e(e){return e.some(t=>t.type==="image"&&t.data!==void 0)}function F8(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 GFt,QFt,JFt,cL=F(()=>{"use strict";xo();lL();GFt=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a(VFt,"globToRegExp");a(y$e,"evaluateMcpToolPolicy");a(Um,"scrubMcpErrorMessage");a(x$e,"publicToolName");a(KFt,"hashSuffix");a(v$e,"supportedOutputSchema");QFt=new Set(["image/png","image/jpeg"]),JFt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(ZFt,"isImageMediaType");a(w$e,"decodeImageBlock");a(b$e,"containsImage");a(F8,"mapMcpResultToContentBlocks")});var Qae,k$e=F(()=>{Qae={name:"dsh-edge",version:"0.26.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","check:startup":"node scripts/check-startup.mjs","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-pi-ai":"0.2.0-rc.2","@deepseek-ai/dsh-llm-retry":"0.2.0-rc.2","@deepseek-ai/dsh-message-feedback":"0.2.0-rc.2","@deepseek-ai/dsh-output-retention":"0.2.0-rc.2","@deepseek-ai/dsh-plan-mode":"0.2.0-rc.2","@deepseek-ai/dsh-ptc-runtime":"0.2.0-rc.2","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.0-rc.2","@deepseek-ai/dsh-sandbox":"0.2.0-rc.2","@deepseek-ai/dsh-schedule":"0.2.0-rc.2","@deepseek-ai/dsh-scope":"0.2.0-rc.2","@deepseek-ai/dsh-session":"0.2.0-rc.2","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.0-rc.2","@deepseek-ai/dsh-session-format":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-catalog":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.0-rc.2","@deepseek-ai/dsh-session-persistence":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection-cache":"0.2.0-rc.2","@deepseek-ai/dsh-session-stats":"0.2.0-rc.2","@deepseek-ai/dsh-session-query":"0.2.0-rc.2","@deepseek-ai/dsh-session-reference":"0.2.0-rc.2","@deepseek-ai/dsh-session-title":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-llm":"0.2.0-rc.2","@deepseek-ai/dsh-settings":"0.2.0-rc.2","@deepseek-ai/dsh-skill":"0.2.0-rc.2","@deepseek-ai/dsh-spill":"0.2.0-rc.2","@deepseek-ai/dsh-spill-policy":"0.2.0-rc.2","@deepseek-ai/dsh-storage":"0.2.0-rc.2","@deepseek-ai/dsh-storage-domain":"0.2.0-rc.2","@deepseek-ai/dsh-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-in-process-driver":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-fork-in-process":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-spawn-in-process":"0.2.0-rc.2","@deepseek-ai/dsh-system-prompt":"0.2.0-rc.2","@deepseek-ai/dsh-timeout":"0.2.0-rc.2","@deepseek-ai/dsh-token-meter":"0.2.0-rc.2","@deepseek-ai/dsh-tool-ask-user":"0.2.0-rc.2","@deepseek-ai/dsh-tool-call-timeout-policy":"0.2.0-rc.2","@deepseek-ai/dsh-tool-fs":"0.2.0-rc.2","@deepseek-ai/dsh-tool-fs-search":"0.2.0-rc.2","@deepseek-ai/dsh-tool-goal":"0.2.0-rc.2","@deepseek-ai/dsh-tool-jobs":"0.2.0-rc.2","@deepseek-ai/dsh-tool-skill":"0.2.0-rc.2","@deepseek-ai/dsh-tool-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-tool-subagent-control":"0.2.0-rc.2","@deepseek-ai/dsh-tool-present":"0.2.0-rc.2","@deepseek-ai/dsh-tool-todo":"0.2.0-rc.2","@deepseek-ai/dsh-tool-web":"0.2.0-rc.2","@deepseek-ai/dsh-tool-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-tools":"0.2.0-rc.2","@deepseek-ai/dsh-typert-protocol":"0.2.0-rc.2","@deepseek-ai/dsh-typert-registry":"0.2.0-rc.2","@deepseek-ai/dsh-user-approval":"0.2.0-rc.2","@deepseek-ai/dsh-user-questions":"0.2.0-rc.2","@deepseek-ai/dsh-util-values":"0.2.0-rc.2","@deepseek-ai/dsh-web":"0.2.0-rc.2","@deepseek-ai/dsh-web-fetch-http":"0.2.0-rc.2","@deepseek-ai/dsh-web-search-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-workspace":"0.2.0-rc.2","@deepseek-ai/schemastery":"3.18.4","@mixmark-io/domino":"2.2.0","@modelcontextprotocol/sdk":"1.30.0",acorn:"8.18.0","fast-png":"8.0.0","jpeg-js":"0.4.4","just-bash":"3.4.2",minimatch:"10.2.6",playwright:"^1.49.0",re2js:"1.3.3",sucrase:"3.35.1",typescript:"^6.0.3",vitest:"^4.1.8",ws:"^8.21.0"}}});var fw,S$e,_$e,U8=F(()=>{"use strict";k$e();fw=Qae.version,S$e=Qae.dshEdge.upstreamVersion,_$e=`npx dsh-edge@${fw.includes("-")?"next":"latest"} upgrade`});function nUt(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 rUt(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function P0(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 XFt)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(rUt(i)){let s=nUt(i),o=s??i;for(let l of eUt)if(l.test(o))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`);if(s===void 0){for(let l of tUt)if(l.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function iUt(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function E$e(e,t,n){P0(e);let r=new rL(new URL(e),{requestInit:{headers:iUt(t),signal:n},fetch:mw}),i=new tL({name:"dsh-edge",version:fw},{capabilities:{},jsonSchemaValidator:sUt});return await i.connect(r),{client:i,close:a(async()=>{await i.close().catch(()=>{})},"close")}}async function T$e(e,t,n){let r=AbortSignal.timeout(ka.probeTimeoutMs),i;try{i=await E$e(t,n,r)}catch(l){throw new Error(Um(l instanceof Error?l.message:String(l)))}let{client:s,close:o}=i;try{let l=[],c=new Set,u=new Set,d;for(let f=0;f<ka.maxCatalogPages;f++){let m=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let y of m.tools){if(l.length>=ka.maxToolsPerServer)break;let x=x$e(e,y.name);if(c.has(x))throw new Error(`Server listed tool "${y.name}" more than once`);c.add(x);let v=y.annotations?.readOnlyHint,w=v$e(y.outputSchema);l.push({name:y.name,publicName:x,description:y.description??"",inputSchema:y.inputSchema??{type:"object"},...w!==void 0?{outputSchema:w}:{},...v!==void 0?{annotations:{readOnlyHint:v}}:{}})}if(l.length>=ka.maxToolsPerServer||(d=m.nextCursor??void 0,d===void 0))break;if(u.has(d))throw new Error("Server repeated a tools/list continuation cursor");u.add(d)}let p=s.getServerVersion?.(),h=s.getInstructions?.();return{tools:l,serverInfo:p?{name:p.name,version:p.version}:void 0,instructions:typeof h=="string"&&h.length>0?h.slice(0,ka.maxInstructionsLength):void 0}}finally{await o()}}async function uL(e,t,n,r,i,s){let o=s??ka.callTimeoutMs,l=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),c;try{c=await E$e(e,r,l)}catch(u){throw new Error(Um(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(Um(u instanceof Error?u.message:String(u)))}finally{await c.close()}}var XFt,eUt,tUt,sUt,mw,j8=F(()=>{"use strict";RMe();l$e();g$e();cL();lL();U8();XFt=[".internal",".local",".localhost"],eUt=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],tUt=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(nUt,"extractMappedIPv4");a(rUt,"isIpAddress");a(P0,"assertSafeUrl");a(iUt,"buildHeaders");sUt=new aL,mw=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(E$e,"connectClient");a(T$e,"probe");a(uL,"callTool")});import{Buffer as oUt}from"node:buffer";function uUt(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&cUt.has(e.code)}function I$e(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&lUt.has(e.code)}function R$e(e,t,n){let r=oUt.from(e,"base64");if(e.length===0&&t==="reject"||r.toString("base64")!==e)throw new jr(n==="INVALID_IMAGE_BASE64"?"Image upload is not canonical base64.":"File upload is not canonical base64.",n);return new Uint8Array(r)}function dUt(e){return R$e(e,"reject","INVALID_IMAGE_BASE64")}function pUt(e){return{data:dUt(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function W8(e,t){return e.saveImages(t.map(pUt))}async function hUt(e,t){return e.saveFile({data:R$e(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function dL(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)),l=Math.max(1,Math.round(o*t/e));for(;o*l>n&&o>1;)o-=1,l=Math.max(1,Math.round(o*t/e));return{width:o,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 Jae(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 A$e,aUt,lUt,cUt,jr,Zae,jm=F(()=>{fr();A$e=["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"],aUt=[...A$e,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],lUt=new Set(A$e),cUt=new Set(aUt),jr=class extends Error{static{a(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};a(uUt,"isAttachmentError");a(I$e,"isImageAdmissionError");a(R$e,"decodeCanonicalBase64");a(dUt,"decodeBase64");a(pUt,"saveInput");a(W8,"admitEncodedImages");a(hUt,"admitEncodedFile");a(dL,"requestImageDimensions");a(Jae,"longEdgeDimensions");Zae=class extends Nt{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 jr("Image batch exceeds the configured image-count limit.","TOO_MANY_IMAGES");if(e.reduce((i,s)=>i+s.data.byteLength,0)>n)throw new jr("Image batch exceeds the configured aggregate image-byte limit.","IMAGES_TOO_LARGE");for(let i of e)if(!r.includes(i.mediaType))throw new jr(`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 W8(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 hUt(this,e)}isAttachmentError(e){return uUt(e)}imageHostPath(e){}saveFile(e){return Promise.reject(new jr("The mounted attachment provider cannot store verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}saveFileStream(e){return Promise.reject(new jr("The mounted attachment provider cannot stream verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}async*readFileStream(e,t){t?.throwIfAborted(),await Promise.reject(new jr("The mounted attachment provider cannot read verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}fileHostPath(e){}readImageRequest(e,t,n){return n?.throwIfAborted(),Promise.reject(new jr("The mounted attachment provider cannot derive model-request images.","ATTACHMENT_PROJECTION_UNSUPPORTED"))}}});var hL={};Yt(hL,{buildAuthorizationUrl:()=>kUt,discoverEndpoints:()=>wUt,exchangeCode:()=>SUt,isTokenExpired:()=>EUt,refreshToken:()=>_Ut,registerClient:()=>bUt});function N$e(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 vUt(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 wUt(e){let t=AbortSignal.timeout(pL),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);P0(i.href);let s=await mw(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);P0(d.href);let p=await mw(d.href,{signal:t});if(!p.ok)throw new Error(`AS metadata failed: HTTP ${p.status}`);let h=await p.json();if(typeof h.authorization_endpoint!="string"||typeof h.token_endpoint!="string")throw new Error("Missing required endpoints in AS metadata");return{authorization:h.authorization_endpoint,token:h.token_endpoint,registration:h.registration_endpoint}}async function bUt(e,t,n){let r=AbortSignal.timeout(pL);P0(e);let i=await mw(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 kUt(e,t,n,r,i){let s=N$e(32),o=N$e(64),l=await vUt(o),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:o,redirectUri:n,serverName:r,serverUrl:i,stagedClient:t,createdAt:Date.now()}}}async function SUt(e,t,n,r,i,s){let o=AbortSignal.timeout(pL),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),P0(e);let c=await mw(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:l.toString(),signal:o});if(!c.ok)throw new Error(`Token exchange failed: HTTP ${c.status}`);return M$e(await c.json())}async function _Ut(e,t,n,r){let i=AbortSignal.timeout(pL),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),P0(e);let o=await mw(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 M$e(await o.json())}function M$e(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 EUt(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var pL,fL=F(()=>{"use strict";j8();pL=1e4;a(N$e,"randomString");a(vUt,"sha256Base64Url");a(wUt,"discoverEndpoints");a(bUt,"registerClient");a(kUt,"buildAuthorizationUrl");a(SUt,"exchangeCode");a(_Ut,"refreshToken");a(M$e,"parseTokenResponse");a(EUt,"isTokenExpired")});var cr,B$e,qS=F(()=>{fr();Lr();cr=class extends vi{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},B$e=class extends Nt{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new cr("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function G8(e){return EL.test(e)}function TL(e){return e.invocation.modelInvocable}function HS(e){return e.invocation.userInvocable}function gle(e){let t=cWt(e);return[`<skill_content name="${uWt(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 GFt,QFt,JFt,cL=F(()=>{"use strict";xo();lL();GFt=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a(VFt,"globToRegExp");a(y$e,"evaluateMcpToolPolicy");a(Um,"scrubMcpErrorMessage");a(x$e,"publicToolName");a(KFt,"hashSuffix");a(v$e,"supportedOutputSchema");QFt=new Set(["image/png","image/jpeg"]),JFt=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(ZFt,"isImageMediaType");a(w$e,"decodeImageBlock");a(b$e,"containsImage");a(F8,"mapMcpResultToContentBlocks")});var Qae,k$e=F(()=>{Qae={name:"dsh-edge",version:"0.26.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","check:startup":"node scripts/check-startup.mjs","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-pi-ai":"0.2.0-rc.2","@deepseek-ai/dsh-llm-retry":"0.2.0-rc.2","@deepseek-ai/dsh-message-feedback":"0.2.0-rc.2","@deepseek-ai/dsh-output-retention":"0.2.0-rc.2","@deepseek-ai/dsh-plan-mode":"0.2.0-rc.2","@deepseek-ai/dsh-ptc-runtime":"0.2.0-rc.2","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.0-rc.2","@deepseek-ai/dsh-sandbox":"0.2.0-rc.2","@deepseek-ai/dsh-schedule":"0.2.0-rc.2","@deepseek-ai/dsh-scope":"0.2.0-rc.2","@deepseek-ai/dsh-session":"0.2.0-rc.2","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.0-rc.2","@deepseek-ai/dsh-session-format":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-catalog":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.0-rc.2","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.0-rc.2","@deepseek-ai/dsh-session-persistence":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection":"0.2.0-rc.2","@deepseek-ai/dsh-session-projection-cache":"0.2.0-rc.2","@deepseek-ai/dsh-session-stats":"0.2.0-rc.2","@deepseek-ai/dsh-session-query":"0.2.0-rc.2","@deepseek-ai/dsh-session-reference":"0.2.0-rc.2","@deepseek-ai/dsh-session-title":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.0-rc.2","@deepseek-ai/dsh-session-title-llm":"0.2.0-rc.2","@deepseek-ai/dsh-settings":"0.2.0-rc.2","@deepseek-ai/dsh-skill":"0.2.0-rc.2","@deepseek-ai/dsh-spill":"0.2.0-rc.2","@deepseek-ai/dsh-spill-policy":"0.2.0-rc.2","@deepseek-ai/dsh-storage":"0.2.0-rc.2","@deepseek-ai/dsh-storage-domain":"0.2.0-rc.2","@deepseek-ai/dsh-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-in-process-driver":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-fork-in-process":"0.2.0-rc.2","@deepseek-ai/dsh-subagent-spawn-in-process":"0.2.0-rc.2","@deepseek-ai/dsh-system-prompt":"0.2.0-rc.2","@deepseek-ai/dsh-timeout":"0.2.0-rc.2","@deepseek-ai/dsh-token-meter":"0.2.0-rc.2","@deepseek-ai/dsh-tool-ask-user":"0.2.0-rc.2","@deepseek-ai/dsh-tool-call-timeout-policy":"0.2.0-rc.2","@deepseek-ai/dsh-tool-fs":"0.2.0-rc.2","@deepseek-ai/dsh-tool-fs-search":"0.2.0-rc.2","@deepseek-ai/dsh-tool-goal":"0.2.0-rc.2","@deepseek-ai/dsh-tool-jobs":"0.2.0-rc.2","@deepseek-ai/dsh-tool-skill":"0.2.0-rc.2","@deepseek-ai/dsh-tool-subagent":"0.2.0-rc.2","@deepseek-ai/dsh-tool-subagent-control":"0.2.0-rc.2","@deepseek-ai/dsh-tool-present":"0.2.0-rc.2","@deepseek-ai/dsh-tool-todo":"0.2.0-rc.2","@deepseek-ai/dsh-tool-web":"0.2.0-rc.2","@deepseek-ai/dsh-tool-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-tools":"0.2.0-rc.2","@deepseek-ai/dsh-typert-protocol":"0.2.0-rc.2","@deepseek-ai/dsh-typert-registry":"0.2.0-rc.2","@deepseek-ai/dsh-user-approval":"0.2.0-rc.2","@deepseek-ai/dsh-user-questions":"0.2.0-rc.2","@deepseek-ai/dsh-util-values":"0.2.0-rc.2","@deepseek-ai/dsh-web":"0.2.0-rc.2","@deepseek-ai/dsh-web-fetch-http":"0.2.0-rc.2","@deepseek-ai/dsh-web-search-deepseek":"0.2.0-rc.2","@deepseek-ai/dsh-workflow":"0.2.0-rc.2","@deepseek-ai/dsh-workspace":"0.2.0-rc.2","@deepseek-ai/schemastery":"3.18.4","@mixmark-io/domino":"2.2.0","@modelcontextprotocol/sdk":"1.30.0",acorn:"8.18.0","fast-png":"8.0.0","jpeg-js":"0.4.4","just-bash":"3.4.2",minimatch:"10.2.6",playwright:"^1.49.0",re2js:"1.3.3",sucrase:"3.35.1",typescript:"^6.0.3",vitest:"^4.1.8",ws:"^8.21.0"}}});var fw,S$e,_$e,U8=F(()=>{"use strict";k$e();fw=Qae.version,S$e=Qae.dshEdge.upstreamVersion,_$e=`npx dsh-edge@${fw.includes("-")?"next":"latest"} upgrade`});function nUt(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 rUt(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function P0(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 XFt)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(rUt(i)){let s=nUt(i),o=s??i;for(let l of eUt)if(l.test(o))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`);if(s===void 0){for(let l of tUt)if(l.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function iUt(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}async function E$e(e,t,n){P0(e);let r=new rL(new URL(e),{requestInit:{headers:iUt(t),signal:n},fetch:mw}),i=new tL({name:"dsh-edge",version:fw},{capabilities:{},jsonSchemaValidator:sUt});return await i.connect(r),{client:i,close:a(async()=>{await i.close().catch(()=>{})},"close")}}async function T$e(e,t,n){let r=AbortSignal.timeout(ka.probeTimeoutMs),i;try{i=await E$e(t,n,r)}catch(l){throw new Error(Um(l instanceof Error?l.message:String(l)))}let{client:s,close:o}=i;try{let l=[],c=new Set,u=new Set,d;for(let f=0;f<ka.maxCatalogPages;f++){let m=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let y of m.tools){if(l.length>=ka.maxToolsPerServer)break;let x=x$e(e,y.name);if(c.has(x))throw new Error(`Server listed tool "${y.name}" more than once`);c.add(x);let v=y.annotations?.readOnlyHint,w=v$e(y.outputSchema);l.push({name:y.name,publicName:x,description:y.description??"",inputSchema:y.inputSchema??{type:"object"},...w!==void 0?{outputSchema:w}:{},...v!==void 0?{annotations:{readOnlyHint:v}}:{}})}if(l.length>=ka.maxToolsPerServer||(d=m.nextCursor??void 0,d===void 0))break;if(u.has(d))throw new Error("Server repeated a tools/list continuation cursor");u.add(d)}let p=s.getServerVersion?.(),h=s.getInstructions?.();return{tools:l,serverInfo:p?{name:p.name,version:p.version}:void 0,instructions:typeof h=="string"&&h.length>0?h.slice(0,ka.maxInstructionsLength):void 0}}finally{await o()}}async function uL(e,t,n,r,i,s){let o=s??ka.callTimeoutMs,l=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),c;try{c=await E$e(e,r,l)}catch(u){throw new Error(Um(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(Um(u instanceof Error?u.message:String(u)))}finally{await c.close()}}var XFt,eUt,tUt,sUt,mw,j8=F(()=>{"use strict";RMe();l$e();g$e();cL();lL();U8();XFt=[".internal",".local",".localhost"],eUt=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],tUt=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(nUt,"extractMappedIPv4");a(rUt,"isIpAddress");a(P0,"assertSafeUrl");a(iUt,"buildHeaders");sUt=new aL,mw=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(E$e,"connectClient");a(T$e,"probe");a(uL,"callTool")});import{Buffer as oUt}from"node:buffer";function uUt(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&cUt.has(e.code)}function I$e(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&lUt.has(e.code)}function R$e(e,t,n){let r=oUt.from(e,"base64");if(e.length===0&&t==="reject"||r.toString("base64")!==e)throw new jr(n==="INVALID_IMAGE_BASE64"?"Image upload is not canonical base64.":"File upload is not canonical base64.",n);return new Uint8Array(r)}function dUt(e){return R$e(e,"reject","INVALID_IMAGE_BASE64")}function pUt(e){return{data:dUt(e.data),mediaType:e.mediaType,...e.name===void 0?{}:{name:e.name}}}async function W8(e,t){return e.saveImages(t.map(pUt))}async function hUt(e,t){return e.saveFile({data:R$e(t.data,"accept","INVALID_FILE_BASE64"),...t.name===void 0?{}:{name:t.name}})}function dL(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)),l=Math.max(1,Math.round(o*t/e));for(;o*l>n&&o>1;)o-=1,l=Math.max(1,Math.round(o*t/e));return{width:o,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 Jae(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 A$e,aUt,lUt,cUt,jr,Zae,jm=F(()=>{fr();A$e=["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"],aUt=[...A$e,"INVALID_FILE_BASE64","INVALID_ATTACHMENT_REF","ATTACHMENT_CORRUPT","ATTACHMENT_WRITE_FAILED","ATTACHMENT_NOT_FOUND","ATTACHMENT_READ_FAILED","ATTACHMENT_PROJECTION_UNSUPPORTED","ATTACHMENT_FILES_UNSUPPORTED"],lUt=new Set(A$e),cUt=new Set(aUt),jr=class extends Error{static{a(this,"AttachmentError")}code;constructor(e,t,n){super(e,n),this.name="AttachmentError",this.code=t}};a(uUt,"isAttachmentError");a(I$e,"isImageAdmissionError");a(R$e,"decodeCanonicalBase64");a(dUt,"decodeBase64");a(pUt,"saveInput");a(W8,"admitEncodedImages");a(hUt,"admitEncodedFile");a(dL,"requestImageDimensions");a(Jae,"longEdgeDimensions");Zae=class extends Nt{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 jr("Image batch exceeds the configured image-count limit.","TOO_MANY_IMAGES");if(e.reduce((i,s)=>i+s.data.byteLength,0)>n)throw new jr("Image batch exceeds the configured aggregate image-byte limit.","IMAGES_TOO_LARGE");for(let i of e)if(!r.includes(i.mediaType))throw new jr(`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 W8(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 hUt(this,e)}isAttachmentError(e){return uUt(e)}imageHostPath(e){}saveFile(e){return Promise.reject(new jr("The mounted attachment provider cannot store verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}saveFileStream(e){return Promise.reject(new jr("The mounted attachment provider cannot stream verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}async*readFileStream(e,t){t?.throwIfAborted(),await Promise.reject(new jr("The mounted attachment provider cannot read verbatim files.","ATTACHMENT_FILES_UNSUPPORTED"))}fileHostPath(e){}readImageRequest(e,t,n){return n?.throwIfAborted(),Promise.reject(new jr("The mounted attachment provider cannot derive model-request images.","ATTACHMENT_PROJECTION_UNSUPPORTED"))}}});var hL={};Yt(hL,{buildAuthorizationUrl:()=>kUt,discoverEndpoints:()=>wUt,exchangeCode:()=>SUt,isTokenExpired:()=>EUt,refreshToken:()=>_Ut,registerClient:()=>bUt});function N$e(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 vUt(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 wUt(e){let t=AbortSignal.timeout(pL),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);P0(i.href);let s=await mw(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);P0(d.href);let p=await mw(d.href,{signal:t});if(!p.ok)throw new Error(`AS metadata failed: HTTP ${p.status}`);let h=await p.json();if(typeof h.authorization_endpoint!="string"||typeof h.token_endpoint!="string")throw new Error("Missing required endpoints in AS metadata");return{authorization:h.authorization_endpoint,token:h.token_endpoint,registration:h.registration_endpoint}}async function bUt(e,t,n){let r=AbortSignal.timeout(pL);P0(e);let i=await mw(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 kUt(e,t,n,r,i){let s=N$e(32),o=N$e(64),l=await vUt(o),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:o,redirectUri:n,serverName:r,serverUrl:i,stagedClient:t,createdAt:Date.now()}}}async function SUt(e,t,n,r,i,s){let o=AbortSignal.timeout(pL),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),P0(e);let c=await mw(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:l.toString(),signal:o});if(!c.ok)throw new Error(`Token exchange failed: HTTP ${c.status}`);return M$e(await c.json())}async function _Ut(e,t,n,r){let i=AbortSignal.timeout(pL),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),P0(e);let o=await mw(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 M$e(await o.json())}function M$e(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 EUt(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var pL,fL=F(()=>{"use strict";j8();pL=1e4;a(N$e,"randomString");a(vUt,"sha256Base64Url");a(wUt,"discoverEndpoints");a(bUt,"registerClient");a(kUt,"buildAuthorizationUrl");a(SUt,"exchangeCode");a(_Ut,"refreshToken");a(M$e,"parseTokenResponse");a(EUt,"isTokenExpired")});var cr,B$e,qS=F(()=>{fr();Lr();cr=class extends vi{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},B$e=class extends Nt{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new cr("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function G8(e){return EL.test(e)}function TL(e){return e.invocation.modelInvocable}function HS(e){return e.invocation.userInvocable}function gle(e){let t=cWt(e);return[`<skill_content name="${uWt(e.name)}">`,"<skill_resources>",...t,"</skill_resources>","","<skill_instructions>",e.content,"</skill_instructions>","</skill_content>"].join(`
|
|
156
156
|
`)}function cWt(e){let t=e.resourceBase;if(t===void 0)return[`Resources for this skill are managed by provider "${zS(e.provider)}".`,"Load referenced resources only as needed."];switch(t.kind){case"directory":return[`Base directory for this skill: ${zS(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: ${zS(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: ${zS(t.description)}`,"Load referenced resources only as needed."];default:return Ti(t,"SkillResourceBase.kind")}}function uWt(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<")}function zS(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function pWt(e,t){if(Array.isArray(e))return{candidates:e,complete:!0};if(e===null||typeof e!="object")throw cDe(t);let n=e;if(!Array.isArray(n.candidates)||typeof n.complete!="boolean")throw cDe(t);return n}function cDe(e){return new TypeError(`skill provider "${e}" list() must return an array or { candidates, complete } observation`)}function fWt(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:lWt,locator:e,...e.path!==void 0?{path:e.path}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}function mWt(e,t){if(typeof e.name!="string")throw new TypeError(`skill provider "${t}" returned a non-string skill name`);if(!EL.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(yle(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 gWt(e){if(!EL.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`);yle(e.invocation,`runtime skill "${e.name}"`)}function yWt(e){let t=e.name,n=e.description,r=e.whenToUse,i=e.invocation,s=e.source,o=e.provider,l=e.content,c=e.path;if(typeof t!="string")throw new TypeError("loaded skill name must be a string");if(!EL.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(yle(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 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 xWt(e){let{name:t,description:n,whenToUse:r,invocation:i,source:s,provider:o,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:o,...l!==void 0?{resourceBase:l}:{}}}function yle(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 vWt(e,t){return hDe(e.name,t.name)}function hDe(e,t){return e<t?-1:e>t?1:0}function wWt(e,t){return e.candidate.rank-t.candidate.rank||e.providerOrder-t.providerOrder||e.localOrder-t.localOrder}function bWt(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 uDe(e,t){return t===void 0?e:(H8(t),new Promise((n,r)=>{let i=a(()=>{t.removeEventListener("abort",s)},"cleanup"),s=a(()=>{i(),r(_L(t.reason))},"onAbort");t.addEventListener("abort",s,{once:!0}),e.then(o=>{i(),n(o)},o=>{i(),r(_L(o))})}))}function H8(e){if(e?.aborted===!0)throw _L(e.reason)}function _L(e){try{if(e instanceof Error)return e}catch{}return new Error(SL(e))}function SL(e){try{return String(e)}catch{return"[unrenderable thrown value]"}}var EL,lDe,aWt,kL,lWt,dDe,dWt,pDe,hWt,yw=F(()=>{fr();us();mc();In();EL=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,lDe=128,aWt=2,kL="runtime",lWt=250,dDe=600;a(G8,"isSkillName");a(TL,"isModelInvocable");a(HS,"isUserInvocable");a(gle,"renderSkillContent");a(cWt,"renderResourceHint");a(uWt,"escapeAttr");a(zS,"escapeText");dWt=class{static{a(this,"SkillLayer")}providers;runtime=new Map;constructor(e){this.providers=new wm(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}},pDe=class extends Nt{static{a(this,"SkillRegistry")}static Config=M.object({collectCacheMaxEntries:M.number().default(lDe)});collectCacheMaxEntries;layers=new bm(e=>new dWt(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??lDe,bWt("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===kL)throw new Error(`"${kL}" is reserved for runtime skill registrations`);let o=this.nextProviderOrder;return this.nextProviderOrder+=1,this.layers.effect(this.ctx,l=>{let c=l.providers.insert(s,{provider:r,order:o});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){gWt(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??kL};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=>xWt(n.candidate)).sort(vWt),complete:t.cacheable}}async get(e,t={}){if(!G8(e))return;let n=await this.collect(t);H8(t.signal);let r=n.entries.get(e);if(r===void 0)return;let i=await uDe(r.provider.get(r.candidate,t),t.signal);if(i!==void 0){if(yWt(i),i.name!==r.candidate.name){this.invalidateEntry(r);return}return i}}async collect(e){H8(e.signal);let t=1;for(;;){let n=this.revision,r=this.collectCacheKey(e.cwd,fA(e.scope),n),i=this.collectCache.get(r);if(i!==void 0)return{entries:i,cacheable:!0};let s=await this.collectFresh(e);if(H8(e.signal),n!==this.revision){if(t<aWt){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(wWt);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){H8(t.signal);let n=[],r=!0,i=0;for(let s of[...e.runtime.values()].sort((o,l)=>hDe(o.name,l.name)))n.push({candidate:fWt(s),provider:hWt,providerOrder:-1,localOrder:i,layer:e}),i+=1;for(let{provider:s,order:o}of[...e.providers.values()]){let l=0,c;try{c=await uDe(s.list(t),t.signal)}catch(d){if(t.signal?.aborted===!0)throw _L(t.signal.reason);r=!1,this.ctx.logger.warn(`skill provider "${s.name}" skipped: ${SL(d)}`)}if(c===void 0)continue;let u=pWt(c,s.name);u.complete||(r=!1);for(let d of u.candidates)mWt(d,s.name),n.push({candidate:d,provider:s,providerOrder:o,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: ${SL(n)}`)})}catch(t){this.ctx.logger.warn(`skills/change listener threw: ${SL(t)}`)}}};a(pWt,"normalizeProviderObservation");a(cDe,"invalidProviderObservation");hWt={name:kL,list(){return Promise.resolve([])},get(e){return Promise.resolve(e.locator)}};a(fWt,"runtimeCandidate");a(mWt,"validateCandidate");a(gWt,"validateRuntimeSkill");a(yWt,"validateDefinition");a(xWt,"toSummary");a(yle,"validateInvocation");a(vWt,"compareSkillSummary");a(hDe,"compareCodePoints");a(wWt,"compareIndexedCandidates");a(bWt,"assertPositiveInteger");a(uDe,"waitWithAbort");a(H8,"throwIfAborted");a(_L,"toError");a(SL,"errorMessage")});var Bp,KS=F(()=>{Bp=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 N0,MLe,rce=F(()=>{fr();N0=class extends Error{static{a(this,"DirectoryPickerError")}code;path;constructor(e,t,n){super(n),this.code=e,this.path=t,this.name="DirectoryPickerError"}},MLe=class extends Nt{static{a(this,"DirectoryPicker")}constructor(e){super(e,"directoryPicker")}}});function bVt(){return globalThis.process?.env}function RUe(){return{async env(e){let t=bVt()?.[e];return typeof t=="string"&&t.trim().length>0?t:void 0},async fileExists(e){try{let t=await IUe("node:fs/promises"),n=e;return n.startsWith("~")&&(n=(await IUe("node:os")).homedir()+n.slice(1)),await t.access(n),!0}catch{return!1}}}}var wVt,IUe,CUe=F(()=>{wVt=function(e,t){return typeof e=="string"&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(n,r,i,s,o){return r?t?".jsx":".js":i&&(!s||!o)?n:i+s+"."+o.toLowerCase()+"js"}):e},IUe=a(e=>import(wVt(e)),"importNodeModule");a(bVt,"getProcessEnv");a(RUe,"defaultProviderAuthContext")});function PUe(e){if(e.reason!==void 0)return e.reason;let t=new Error("The operation was aborted");return t.name="AbortError",t}function gf(e){return e??new AbortController().signal}function yf(e,t){return t.aborted?(e.catch(()=>{}),Promise.reject(PUe(t))):new Promise((n,r)=>{let i=!1,s=a(()=>t.removeEventListener("abort",o),"cleanup"),o=a(()=>{i||(i=!0,s(),r(PUe(t)))},"onAbort");t.addEventListener("abort",o,{once:!0}),e.then(l=>{i||(i=!0,s(),n(l))},l=>{i||(i=!0,s(),r(l))}),t.aborted&&o()})}var MF=F(()=>{a(PUe,"abortReason");a(gf,"operationSignal");a(yf,"raceWithAbortSignal")});var $F,OUe=F(()=>{MF();$F=class{static{a(this,"InMemoryCredentialStore")}credentials=new Map;chains=new Map;enqueue(t,n,r){let i=gf(r?.signal),s=this.chains.get(t)??Promise.resolve(),o=(async()=>(await s.catch(()=>{}),i.throwIfAborted(),n()))(),l=o.catch(()=>{});return this.chains.set(t,l),l.then(()=>{this.chains.get(t)===l&&this.chains.delete(t)}),yf(o,i)}async read(t,n){return n?.signal?.throwIfAborted(),this.credentials.get(t)}async list(t){return t?.signal?.throwIfAborted(),[...this.credentials].map(([n,r])=>({providerId:n,type:r.type}))}modify(t,n,r){return this.enqueue(t,async()=>{let i=this.credentials.get(t),s=await n(i);return r?.signal?.throwIfAborted(),s!==void 0&&this.credentials.set(t,s),s??i},r)}delete(t,n){return this.enqueue(t,async()=>{this.credentials.delete(t)},n)}}});function Sw(e){return e instanceof Error?e.message||e.name:typeof e=="string"?e:String(e)}function kVt(e){if(!(e instanceof Error))return{name:"ThrownValue",message:Sw(e)};let t=e.code;return{name:e.name||void 0,message:e.message||e.name,stack:e.stack,code:typeof t=="string"||typeof t=="number"?t:void 0}}function DF(e,t,n){return{type:e,timestamp:Date.now(),error:kVt(t),details:n}}function _w(e,t){e.diagnostics=[...e.diagnostics??[],t]}var _I=F(()=>{a(Sw,"formatThrownValue");a(kVt,"extractDiagnosticError");a(DF,"createAssistantMessageDiagnostic");a(_w,"appendAssistantMessageDiagnostic")});function SVt(e,t){if(t==null)return e;let n=Sw(t).trim();return!n||e.includes(n)?e:`${e}: ${n}`}function lue(e,t,n,r){let i=gf(r?.signal);return yf(_Vt(e,t,n,r,i),i)}async function _Vt(e,t,n,r,i){i.throwIfAborted();let s=r?.env?EVt(n,r.env):n;if(r?.apiKey!==void 0&&e.auth.apiKey)return aue(s,e.auth.apiKey,e.id,{type:"api_key",key:r.apiKey,env:r.env},i);let o=await RVt(t,e.id,i);if(o){if(o.type==="oauth"&&e.auth.oauth)return IVt(t,e.id,e.auth.oauth,o,i,r?.minOAuthValidityMs);if(o.type==="api_key"&&e.auth.apiKey){let l=r?.env?{...o,env:{...o.env,...r.env}}:o;return aue(s,e.auth.apiKey,e.id,l,i)}return}return e.auth.apiKey?aue(s,e.auth.apiKey,e.id,void 0,i):void 0}function EVt(e,t){return{env:a(async n=>t[n]||await e.env(n),"env"),fileExists:a(n=>e.fileExists(n),"fileExists")}}async function IVt(e,t,n,r,i,s){let o=Math.max(TVt,s??0),l=a(u=>Date.now()+o>=u.expires,"expiresSoon"),c=r;if(l(c)){let u;try{u=await e.modify(t,async d=>{if(d?.type==="oauth"&&l(d))try{let p=AbortSignal.any([i,AbortSignal.timeout(AVt)]);return await n.refresh(d,p)}catch(p){throw new Co("oauth",`OAuth refresh failed for ${t}`,{cause:p})}},{signal:i})}catch(d){throw d instanceof Co?d:new Co("auth",`Credential store modify failed for ${t}`,{cause:d})}if(u?.type!=="oauth")return;if(c=u,s!==void 0&&l(c))throw new Co("oauth",`OAuth refresh returned a token that expires too soon for ${t}`)}try{return{auth:await n.toAuth(c),source:"OAuth"}}catch(u){throw new Co("oauth",`OAuth auth derivation failed for ${t}`,{cause:u})}}async function aue(e,t,n,r,i){try{return await t.resolve({ctx:e,credential:r,signal:i})}catch(s){throw new Co("auth",`API key auth failed for provider ${n}`,{cause:s})}}async function RVt(e,t,n){try{return await e.read(t,{signal:n})}catch(r){throw new Co("auth",`Credential store read failed for ${t}`,{cause:r})}}var Co,TVt,AVt,NUe=F(()=>{MF();_I();Co=class extends Error{static{a(this,"ModelsError")}code;constructor(t,n,r){super(SVt(n,r?.cause),r),this.name="ModelsError",this.code=t}};a(SVt,"withCauseDetail");a(lue,"resolveProviderAuth");a(_Vt,"resolveProviderAuthWithSignal");a(EVt,"overlayEnvAuthContext");TVt=300*1e3,AVt=15e3;a(IVt,"resolveStoredOAuth");a(aue,"resolveApiKey");a(RVt,"readCredential")});var _U,uue,ta,xf=F(()=>{_U=class{static{a(this,"FifoQueue")}incoming=[];outgoing=[];get length(){return this.incoming.length+this.outgoing.length}enqueue(t){this.incoming.push(t)}dequeue(){if(this.outgoing.length===0)for(;this.incoming.length>0;)this.outgoing.push(this.incoming.pop());return this.outgoing.pop()}},uue=class{static{a(this,"EventStream")}queue=new _U;waiting=new _U;done=!1;finalResultPromise;resolveFinalResult;isComplete;extractResult;constructor(t,n){this.isComplete=t,this.extractResult=n,this.finalResultPromise=new Promise(r=>{this.resolveFinalResult=r})}push(t){if(this.done)return;this.isComplete(t)&&(this.done=!0,this.resolveFinalResult(this.extractResult(t)));let n=this.waiting.dequeue();n?n({value:t,done:!1}):this.queue.enqueue(t)}end(t){for(this.done=!0,t!==void 0&&this.resolveFinalResult(t);this.waiting.length>0;)this.waiting.dequeue()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.dequeue();else{if(this.done)return;{let t=await new Promise(n=>this.waiting.enqueue(n));if(t.done)return;yield t.value}}}result(){return this.finalResultPromise}},ta=class extends uue{static{a(this,"AssistantMessageEventStream")}constructor(){super(t=>t.type==="done"||t.type==="error",t=>{if(t.type==="done")return t.message;if(t.type==="error")return t.error;throw new Error("Unexpected event type for final result")})}}});function yKt(e,t){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"error",errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}function xKt(e){return typeof e.result=="function"}async function vKt(e,t){for await(let n of t)e.push(n);e.end(xKt(t)?await t.result():void 0)}function j0(e,t){let n=new ta;return t().then(r=>vKt(n,r)).catch(r=>{let i=yKt(e,r);n.push({type:"error",reason:"error",error:i}),n.end(i)}),n}function Ua(e,t){let n={stream:a((r,i,s)=>j0(r,async()=>(await e()).stream(r,i,s)),"stream"),streamSimple:a((r,i,s)=>j0(r,async()=>(await e()).streamSimple(r,i,s)),"streamSimple")};return t?.fetchDeferred&&(n.fetchDeferred=(r,i,s)=>j0(r,async()=>{let o=await e();if(!o.fetchDeferred)throw new Error("API does not support deferred responses");return o.fetchDeferred(r,i,s)})),t?.cancelDeferred&&(n.cancelDeferred=async(r,i,s)=>{let o=await e();if(!o.cancelDeferred)throw new Error("API cannot cancel deferred responses");await o.cancelDeferred(r,i,s)}),n}var zp=F(()=>{xf();a(yKt,"createSetupErrorMessage");a(xKt,"hasResult");a(vKt,"forwardStream");a(j0,"lazyStream");a(Ua,"lazyApi")});var EU,bje=F(()=>{EU=class{static{a(this,"InMemoryModelsStore")}entries=new Map;async read(t,n){n?.signal?.throwIfAborted();let r=this.entries.get(t);return r?structuredClone(r):void 0}async write(t,n,r){r?.signal?.throwIfAborted(),this.entries.set(t,structuredClone(n))}async delete(t,n){n?.signal?.throwIfAborted(),this.entries.delete(t)}}});function TU(e,t=`
|
|
157
157
|
`){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join(t)}function ql(e){let t=[TU(e.content)];for(let n of Object.values(e.sections??{}))n!==null&&t.push(n);return t.filter(n=>n.length>0).join(`
|
|
158
158
|
|
|
@@ -6443,7 +6443,7 @@ The web search request used endpoint ${JSON.stringify(e)}. Search endpoint confi
|
|
|
6443
6443
|
.error { padding: .75rem; border-radius: .5rem; background: #461d2b; color: #ffd6df; }
|
|
6444
6444
|
.hint { margin: 1.5rem 0 0; font-size: .875rem; }
|
|
6445
6445
|
code { padding: .1rem .3rem; border-radius: .3rem; background: #0c1222; color: #edf2ff; }
|
|
6446
|
-
`}a(Kht,"pageStyles");U8();var H3e="enabled",G3e=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")}),iP=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")}),V3e=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===H3e?"available":"needs-binding","probe")}),XDn=Object.freeze([V3e,iP,G3e]);function K3e(e,t=XDn){return t.filter(n=>n.probe(e)==="available")}a(K3e,"availableEdgeRuntimeProviders");function Q3e(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(Q3e,"resolveEdgeRuntimeSelection");function IG(e){let t=K3e(e),{bash:n,container:r}=Q3e(t);return t.find(i=>i.id===(r??n)).shell}a(IG,"resolveEdgeRuntimeShell");function eLn(){return"dsh-edge@0.26.0-alpha.2/isolated"}a(eLn,"resolveEdgeDeploymentId");function p3(e){return{baseURL:Z0e(e.DEEPSEEK_BASE_URL),maxTokens:e1e(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Rb(e.DEEPSEEK_MODEL),reasoningEffort:Y0e(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:f9(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:X0e(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:$x(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(p3,"resolveEdgeDeploymentConfig");function tLn(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(tLn,"edgeDeploymentApiKeyConfigured");function nLn(e){let t=Z0e(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(nLn,"projectedEdgeBaseURL");function J3e(e,t){return{shell:IG(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:eLn(),apiKeyConfigured:tLn(e),baseURL:nLn(e.DEEPSEEK_BASE_URL),maxTokens:e1e(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Rb(e.DEEPSEEK_MODEL),reasoningEffort:Y0e(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:f9(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:X0e(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:$x(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(J3e,"resolveEdgeDeploymentProfile");function RG(e){p3(e);let t=J3e(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:fw,upstreamVersion:S$e,status:"ready"}}a(RG,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as kVn}from"node:async_hooks";import{RpcTarget as rLn}from"cloudflare:workers";function iLn(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(iLn,"startHeartbeat");async function sLn(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(sLn,"probeComputerdHealth");var oLn="computer.internal",aLn="/health",Z3e="/api",lLn=8080,cLn=3e4,uLn=2e4,dLn=1,pLn=2e3,hLn=250,fLn=2e3;function mLn(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(mLn,"bearerMatches");var PG=class{static{a(this,"CloudflareContainerBackend")}type="cloudflare-container";id;#e;#t;#r;#n;#i;#s;#a;#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??oLn,containerPort:e.containerPort??lLn,connectTimeoutMs:e.connectTimeoutMs??cLn,heartbeatIntervalMs:e.heartbeatIntervalMs??uLn,restartAttempts:e.restartAttempts??dLn,healthProbeTimeoutMs:e.healthProbeTimeoutMs??pLn,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??hLn,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??fLn}}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 Hc(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 Hc(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.#h(t,e),await this.#x(t,e,s);let o=await this.#f(e),l=fK(o),c,u=new Promise(p=>{let h=!1,f=a(()=>{h||(h=!0,c?.(),p(),this.#l=void 0)},"onClose");o.addEventListener("close",f,{once:!0}),o.addEventListener("error",f,{once:!0}),l.onRpcBroken(f)});this.#e.heartbeatIntervalMs>0&&(c=iLn({intervalMs:this.#e.heartbeatIntervalMs,ping:a(()=>l.sync.watermarks(),"ping"),onFailure:a(()=>{try{o.close()}catch{}},"onFailure")}));let d={rpc:l,runtimeId:i,closed:u,close:a(async()=>{c?.();try{l[Symbol.dispose]?.()}catch{}try{o.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(WT),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(ZP),i.delete(WT);let l=new Request(e,{headers:i});return this.#t.gateway.fetch(new Request(o,l))}if(new URL(e.url).pathname!==Z3e)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${Z3e} requires a websocket upgrade`,{status:400});if(!mLn(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()),l=Math.max(250,Math.floor(o/s)),c=0,u=0,d,p=i;for(;c<s;){c++;let h=Math.min(n,Date.now()+l);if(await this.#m(e,h).then(()=>!0,f=>(d=f,!1)))return p;if(c<s)try{({runtimeId:p}=await e.restart({env:t,enableInternet:this.#t.mode==="direct"})),u++}catch(f){throw this.#a?.(f),this.#o(),new Hc(this.#d("restart",{attempt:c,maxAttempts:s,restarts:u,lastError:f}),{cause:f})}}throw this.#a?.(new Error("computerd never became healthy")),this.#o(),new Hc(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 sLn(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 gLn(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=${Qht(t.lastError)}`}async#h(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 Hc(`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#x(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:aLn,api:Z3e,healthTimeoutMs:r})})}catch(s){throw this.#a?.(s),this.#o(),new Hc(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${Qht(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 Hc(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect returned ${i.status}: ${s}`,{cause:o})}}async#f(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 Hc(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#o()}}};function gLn(e){return new Promise(t=>setTimeout(t,e))}a(gLn,"sleep");function Qht(e){return e instanceof Error?e.message:String(e)}a(Qht,"describeError");var Jht="computer:container-client-secret",yLn=16;function xLn(){let e=crypto.getRandomValues(new Uint8Array(yLn));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(xLn,"generate");var vLn=class{static{a(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(Jht);if(typeof e=="string"&&e.length>0)return e;let t=xLn();return await this.storage.put(Jht,t),t}},Zht="computer:container-launch-record";async function Yht(e){return{enableInternet:e.enableInternet,envDigest:await bLn(e.env)}}a(Yht,"launchRecordFor");function wLn(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}a(wLn,"sameLaunch");async function bLn(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(bLn,"digestEnv");var kLn=class{static{a(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(Zht)??null}async set(e){await this.storage.put(Zht,e)}},Xht=new WeakMap;function eke(e){let t=Xht.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},Xht.set(e,t)),t}a(eke,"getContainerLifecycle");function CG(e){return eke(e).exit}a(CG,"containerExitInfo");function eft(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}a(eft,"formatExitReason");function tft(e,t,n){let r=eke(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>nft(r,i,void 0,n),s=>nft(r,i,s,n))}a(tft,"installContainerMonitor");async function Y3e(e,t){let n=eke(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}a(Y3e,"destroyContainerExpectingExit");async function nft(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=eft(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(l){console.error({message:"workspace.container.exit_cleanup_failed",reason:eft(l),exitedAt:Date.now()})}}a(nft,"recordExit");var X3e="computer:container-runtime-identity",SLn=class{static{a(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(X3e)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(X3e,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(X3e)}},_Ln=class extends rLn{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 SLn(e.storage),this.#n=new vLn(e.storage),this.#i=new kLn(e.storage)}async start(e){let t=CG(this.#t),n=await this.#n.ensure(),r=await Yht(e);if(t!==null){try{await Y3e(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||!wLn(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 Y3e(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return tft(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await Y3e(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await Yht(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),tft(this.#t,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:CG(this.#t)}}async exitInfo(){return CG(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=CG(this.#t);if(r!==null)throw new Hc(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function rft(e){class t extends e{static{a(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new _Ln(this.ctx)}}return t}a(rft,"withWorkspaceContainer");var ELn={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function sft(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),l=ELn[s]??s,c=e[l];if(c===void 0)return;let u=c[o];return typeof u=="function"?u:void 0}a(sft,"resolve");function TLn(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}a(TLn,"errorResponse");async function tke(e,t,n,r,i){let s=sft(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}a(tke,"callEdgeApi");async function oft(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(sft(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",l=s.payload??{};try{let c=await tke(e,i,o,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 TLn(o,{code:"internal",message:String(c),details:{}})}}a(oft,"dispatchEdgeApi");Lr();yo();My();import{DurableObject as SVn}from"cloudflare:workers";var OG=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 ALn(this.stopping,t);continue}await new Promise((r,i)=>{let s=a(()=>{t?.removeEventListener("abort",o),r()},"wake"),o=a(()=>{let l=this.waiters.indexOf(s);l!==-1&&this.waiters.splice(l,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 ALn(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(ALn,"untilAborted");import{WorkerEntrypoint as pbi}from"cloudflare:workers";var R3=Al(aft(),1);import{gunzipSync as ZUn}from"node:zlib";var sP=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),l=this.removeEmpty(this.tokenize(s,r)),c=this.removeEmpty(this.tokenize(o,r));return this.diffWithOptionsObj(l,c,r,i)}diffWithOptionsObj(t,n,r,i){var s;let o=a(w=>{if(w=this.postProcess(w,r),i){setTimeout(function(){i(w)},0);return}else return w},"done"),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,h=Date.now()+p,f=[{oldPos:-1,lastComponent:void 0}],m=this.extractCommon(f[0],n,t,0,r);if(f[0].oldPos+1>=c&&m+1>=l)return o(this.buildValues(f[0].lastComponent,n,t));let y=-1/0,x=1/0,v=a(()=>{for(let w=Math.max(y,-u);w<=Math.min(x,u);w+=2){let _,S=f[w-1],T=f[w+1];S&&(f[w-1]=void 0);let A=!1;if(T){let N=T.oldPos-w;A=T&&0<=N&&N<l}let O=S&&S.oldPos+1<c;if(!A&&!O){f[w]=void 0;continue}if(!O||A&&S.oldPos<T.oldPos?_=this.addToPath(T,!0,!1,0,r):_=this.addToPath(S,!1,!0,1,r),m=this.extractCommon(_,n,t,w,r),_.oldPos+1>=c&&m+1>=l)return o(this.buildValues(_.lastComponent,n,t))||!0;f[w]=_,_.oldPos+1>=c&&(x=Math.min(x,w-1)),m+1>=l&&(y=Math.max(y,w+1))}u++},"execEditLength");if(i)a(function w(){setTimeout(function(){if(u>d||Date.now()>h)return i(void 0);v()||w()},0)},"exec")();else for(;u<=d&&Date.now()<=h;){let w=v();if(w)return w}}addToPath(t,n,r,i,s){let o=t.lastComponent;return o&&!s.oneChangePerToken&&o.added===n&&o.removed===r?{oldPos:t.oldPos+i,lastComponent:{count:o.count+1,added:n,removed:r,previousComponent:o.previousComponent}}:{oldPos:t.oldPos+i,lastComponent:{count:1,added:n,removed:r,previousComponent:o}}}extractCommon(t,n,r,i,s){let o=n.length,l=r.length,c=t.oldPos,u=c-i,d=0;for(;u+1<o&&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 o=i.length,l=0,c=0,u=0;for(;l<o;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(h,f){let m=r[u+f];return m.length>h.length?m:h}),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 nke=class extends sP{static{a(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=RLn}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
|
|
6446
|
+
`}a(Kht,"pageStyles");U8();var H3e="enabled",G3e=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")}),iP=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")}),V3e=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===H3e?"available":"needs-binding","probe")}),XDn=Object.freeze([V3e,iP,G3e]);function K3e(e,t=XDn){return t.filter(n=>n.probe(e)==="available")}a(K3e,"availableEdgeRuntimeProviders");function Q3e(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(Q3e,"resolveEdgeRuntimeSelection");function IG(e){let t=K3e(e),{bash:n,container:r}=Q3e(t);return t.find(i=>i.id===(r??n)).shell}a(IG,"resolveEdgeRuntimeShell");function eLn(){return"dsh-edge@0.26.0/isolated"}a(eLn,"resolveEdgeDeploymentId");function p3(e){return{baseURL:Z0e(e.DEEPSEEK_BASE_URL),maxTokens:e1e(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Rb(e.DEEPSEEK_MODEL),reasoningEffort:Y0e(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:f9(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:X0e(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:$x(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(p3,"resolveEdgeDeploymentConfig");function tLn(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(tLn,"edgeDeploymentApiKeyConfigured");function nLn(e){let t=Z0e(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(nLn,"projectedEdgeBaseURL");function J3e(e,t){return{shell:IG(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:eLn(),apiKeyConfigured:tLn(e),baseURL:nLn(e.DEEPSEEK_BASE_URL),maxTokens:e1e(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Rb(e.DEEPSEEK_MODEL),reasoningEffort:Y0e(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:f9(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:X0e(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:$x(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(J3e,"resolveEdgeDeploymentProfile");function RG(e){p3(e);let t=J3e(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:fw,upstreamVersion:S$e,status:"ready"}}a(RG,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as kVn}from"node:async_hooks";import{RpcTarget as rLn}from"cloudflare:workers";function iLn(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(iLn,"startHeartbeat");async function sLn(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(sLn,"probeComputerdHealth");var oLn="computer.internal",aLn="/health",Z3e="/api",lLn=8080,cLn=3e4,uLn=2e4,dLn=1,pLn=2e3,hLn=250,fLn=2e3;function mLn(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(mLn,"bearerMatches");var PG=class{static{a(this,"CloudflareContainerBackend")}type="cloudflare-container";id;#e;#t;#r;#n;#i;#s;#a;#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??oLn,containerPort:e.containerPort??lLn,connectTimeoutMs:e.connectTimeoutMs??cLn,heartbeatIntervalMs:e.heartbeatIntervalMs??uLn,restartAttempts:e.restartAttempts??dLn,healthProbeTimeoutMs:e.healthProbeTimeoutMs??pLn,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??hLn,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??fLn}}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 Hc(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 Hc(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.#h(t,e),await this.#x(t,e,s);let o=await this.#f(e),l=fK(o),c,u=new Promise(p=>{let h=!1,f=a(()=>{h||(h=!0,c?.(),p(),this.#l=void 0)},"onClose");o.addEventListener("close",f,{once:!0}),o.addEventListener("error",f,{once:!0}),l.onRpcBroken(f)});this.#e.heartbeatIntervalMs>0&&(c=iLn({intervalMs:this.#e.heartbeatIntervalMs,ping:a(()=>l.sync.watermarks(),"ping"),onFailure:a(()=>{try{o.close()}catch{}},"onFailure")}));let d={rpc:l,runtimeId:i,closed:u,close:a(async()=>{c?.();try{l[Symbol.dispose]?.()}catch{}try{o.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(WT),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(ZP),i.delete(WT);let l=new Request(e,{headers:i});return this.#t.gateway.fetch(new Request(o,l))}if(new URL(e.url).pathname!==Z3e)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${Z3e} requires a websocket upgrade`,{status:400});if(!mLn(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()),l=Math.max(250,Math.floor(o/s)),c=0,u=0,d,p=i;for(;c<s;){c++;let h=Math.min(n,Date.now()+l);if(await this.#m(e,h).then(()=>!0,f=>(d=f,!1)))return p;if(c<s)try{({runtimeId:p}=await e.restart({env:t,enableInternet:this.#t.mode==="direct"})),u++}catch(f){throw this.#a?.(f),this.#o(),new Hc(this.#d("restart",{attempt:c,maxAttempts:s,restarts:u,lastError:f}),{cause:f})}}throw this.#a?.(new Error("computerd never became healthy")),this.#o(),new Hc(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 sLn(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 gLn(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=${Qht(t.lastError)}`}async#h(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 Hc(`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#x(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:aLn,api:Z3e,healthTimeoutMs:r})})}catch(s){throw this.#a?.(s),this.#o(),new Hc(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${Qht(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 Hc(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect returned ${i.status}: ${s}`,{cause:o})}}async#f(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 Hc(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#o()}}};function gLn(e){return new Promise(t=>setTimeout(t,e))}a(gLn,"sleep");function Qht(e){return e instanceof Error?e.message:String(e)}a(Qht,"describeError");var Jht="computer:container-client-secret",yLn=16;function xLn(){let e=crypto.getRandomValues(new Uint8Array(yLn));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(xLn,"generate");var vLn=class{static{a(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(Jht);if(typeof e=="string"&&e.length>0)return e;let t=xLn();return await this.storage.put(Jht,t),t}},Zht="computer:container-launch-record";async function Yht(e){return{enableInternet:e.enableInternet,envDigest:await bLn(e.env)}}a(Yht,"launchRecordFor");function wLn(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}a(wLn,"sameLaunch");async function bLn(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(bLn,"digestEnv");var kLn=class{static{a(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(Zht)??null}async set(e){await this.storage.put(Zht,e)}},Xht=new WeakMap;function eke(e){let t=Xht.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},Xht.set(e,t)),t}a(eke,"getContainerLifecycle");function CG(e){return eke(e).exit}a(CG,"containerExitInfo");function eft(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}a(eft,"formatExitReason");function tft(e,t,n){let r=eke(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>nft(r,i,void 0,n),s=>nft(r,i,s,n))}a(tft,"installContainerMonitor");async function Y3e(e,t){let n=eke(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}a(Y3e,"destroyContainerExpectingExit");async function nft(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=eft(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(l){console.error({message:"workspace.container.exit_cleanup_failed",reason:eft(l),exitedAt:Date.now()})}}a(nft,"recordExit");var X3e="computer:container-runtime-identity",SLn=class{static{a(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(X3e)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(X3e,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(X3e)}},_Ln=class extends rLn{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 SLn(e.storage),this.#n=new vLn(e.storage),this.#i=new kLn(e.storage)}async start(e){let t=CG(this.#t),n=await this.#n.ensure(),r=await Yht(e);if(t!==null){try{await Y3e(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||!wLn(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 Y3e(this.#t,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return tft(this.#t,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await Y3e(this.#t,this.#e)}catch{}let t=await this.#n.ensure();return this.#s(e,t,await Yht(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),tft(this.#t,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:CG(this.#t)}}async exitInfo(){return CG(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=CG(this.#t);if(r!==null)throw new Hc(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function rft(e){class t extends e{static{a(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new _Ln(this.ctx)}}return t}a(rft,"withWorkspaceContainer");var ELn={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function sft(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),l=ELn[s]??s,c=e[l];if(c===void 0)return;let u=c[o];return typeof u=="function"?u:void 0}a(sft,"resolve");function TLn(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}a(TLn,"errorResponse");async function tke(e,t,n,r,i){let s=sft(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}a(tke,"callEdgeApi");async function oft(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(sft(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",l=s.payload??{};try{let c=await tke(e,i,o,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 TLn(o,{code:"internal",message:String(c),details:{}})}}a(oft,"dispatchEdgeApi");Lr();yo();My();import{DurableObject as SVn}from"cloudflare:workers";var OG=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 ALn(this.stopping,t);continue}await new Promise((r,i)=>{let s=a(()=>{t?.removeEventListener("abort",o),r()},"wake"),o=a(()=>{let l=this.waiters.indexOf(s);l!==-1&&this.waiters.splice(l,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 ALn(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(ALn,"untilAborted");import{WorkerEntrypoint as pbi}from"cloudflare:workers";var R3=Al(aft(),1);import{gunzipSync as ZUn}from"node:zlib";var sP=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),l=this.removeEmpty(this.tokenize(s,r)),c=this.removeEmpty(this.tokenize(o,r));return this.diffWithOptionsObj(l,c,r,i)}diffWithOptionsObj(t,n,r,i){var s;let o=a(w=>{if(w=this.postProcess(w,r),i){setTimeout(function(){i(w)},0);return}else return w},"done"),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,h=Date.now()+p,f=[{oldPos:-1,lastComponent:void 0}],m=this.extractCommon(f[0],n,t,0,r);if(f[0].oldPos+1>=c&&m+1>=l)return o(this.buildValues(f[0].lastComponent,n,t));let y=-1/0,x=1/0,v=a(()=>{for(let w=Math.max(y,-u);w<=Math.min(x,u);w+=2){let _,S=f[w-1],T=f[w+1];S&&(f[w-1]=void 0);let A=!1;if(T){let N=T.oldPos-w;A=T&&0<=N&&N<l}let O=S&&S.oldPos+1<c;if(!A&&!O){f[w]=void 0;continue}if(!O||A&&S.oldPos<T.oldPos?_=this.addToPath(T,!0,!1,0,r):_=this.addToPath(S,!1,!0,1,r),m=this.extractCommon(_,n,t,w,r),_.oldPos+1>=c&&m+1>=l)return o(this.buildValues(_.lastComponent,n,t))||!0;f[w]=_,_.oldPos+1>=c&&(x=Math.min(x,w-1)),m+1>=l&&(y=Math.max(y,w+1))}u++},"execEditLength");if(i)a(function w(){setTimeout(function(){if(u>d||Date.now()>h)return i(void 0);v()||w()},0)},"exec")();else for(;u<=d&&Date.now()<=h;){let w=v();if(w)return w}}addToPath(t,n,r,i,s){let o=t.lastComponent;return o&&!s.oneChangePerToken&&o.added===n&&o.removed===r?{oldPos:t.oldPos+i,lastComponent:{count:o.count+1,added:n,removed:r,previousComponent:o.previousComponent}}:{oldPos:t.oldPos+i,lastComponent:{count:1,added:n,removed:r,previousComponent:o}}}extractCommon(t,n,r,i,s){let o=n.length,l=r.length,c=t.oldPos,u=c-i,d=0;for(;u+1<o&&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 o=i.length,l=0,c=0,u=0;for(;l<o;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(h,f){let m=r[u+f];return m.length>h.length?m:h}),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 nke=class extends sP{static{a(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=RLn}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
|
|
6447
6447
|
`))&&(t=t.trim()),(!r.newlineIsToken||!n.includes(`
|
|
6448
6448
|
`))&&(n=n.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
|
|
6449
6449
|
`)&&(t=t.slice(0,-1)),n.endsWith(`
|