dsh-edge 0.29.0-alpha.1 → 0.29.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/README.i18n.yaml +2 -2
- package/README.md +1 -1
- package/README.zh.md +1 -1
- package/package.json +1 -1
- package/worker/direct/index.js +2 -2
- package/worker/isolated/index.js +2 -2
package/README.i18n.yaml
CHANGED
|
@@ -2,5 +2,5 @@
|
|
|
2
2
|
# last confirmed-consistent state. Both languages carry equal authority.
|
|
3
3
|
# After editing either side, update both and re-record every pair with:
|
|
4
4
|
# pnpm run doc-pairs -- --write
|
|
5
|
-
README.md:
|
|
6
|
-
README.zh.md:
|
|
5
|
+
README.md: f662c22b412ed1f739084f912caf6032d044dfc6
|
|
6
|
+
README.zh.md: 62907f39478ad05696ce5f579c4257caafb32671
|
package/README.md
CHANGED
|
@@ -378,7 +378,7 @@ SQLite `DELETE` operations consume the daily row-write allowance too. During for
|
|
|
378
378
|
- Request bodies are consumed incrementally. Once a route limit is crossed, later chunks are drained without being retained and the route returns 413. File uploads also reject malformed UTF-8.
|
|
379
379
|
- File reads check VFS metadata, then collect the opened byte stream through the same 1 MiB cap. This closes the growth race between `stat()` and `readFile()` without retaining an unbounded value.
|
|
380
380
|
- Image admission fully decodes the declared raster format before writing.
|
|
381
|
-
- As upstream `bash-local`, a command keeps running past the output cap: each stream keeps its last 64,000 bytes inline by default (the Shell card's output cap, 1 KiB to 1 MiB), and the whole stream is saved to `/workspace/.spill/bash-<execution>.<stream>.txt` (deleted with the other spills after 30 days), up to 16 MiB per stream (upstream allows 64 MiB; each 512 KiB costs about five Durable Object rows written, and the workspace storage does not free deleted bytes, #358), past which the file keeps its start and the result says so. Memory stays at the tail plus a 1 MiB write queue per stream: reading the command's output waits while the spill is written. Output under the cap writes nothing. The lightweight shell (just-bash) returns a command's output whole instead of streaming it, so it still stops a command whose output passes 8 MiB (exit 126, reported as `[stopped: …]`); that buffer lives in its isolate, the Durable Object in Direct mode. The bash tool renders upstream's layout: stdout, a `[stderr]` section, `[output truncated; full output: <path>]` per stream, `[timed out after Nms]`, and `[exit code: N]` last, and its terminal card shows the working directory. A `timeoutMs` above the deployment ceiling is lowered to it, as upstream clamps it; the HTTP exec route still refuses one. `cancelled` reflects an adapter-requested interruption; `timedOut` independently records deadline expiry.
|
|
381
|
+
- As upstream `bash-local`, a command keeps running past the output cap: each stream keeps its last 64,000 bytes inline by default (the Shell card's output cap, 1 KiB to 1 MiB), and the whole stream is saved to `/workspace/.spill/bash-<execution>.<stream>.txt` (deleted with the other spills after 30 days), up to 16 MiB per stream (upstream allows 64 MiB; each 512 KiB costs about five Durable Object rows written, and the workspace storage does not free deleted bytes, #358), past which the file keeps its start and the result says so. Memory stays at the tail plus a 1 MiB write queue per stream: reading the command's output waits while the spill is written. Output under the cap writes nothing. The lightweight shell (just-bash) returns a command's output whole instead of streaming it, so it still stops a command whose output passes 8 MiB (exit 126, reported as `[stopped: …]`); that buffer lives in its isolate, the Durable Object in Direct mode. The bash tool renders upstream's layout: stdout, a `[stderr]` section, `[output truncated; full output: <path>]` per stream, `[timed out after Nms]`, and `[exit code: N]` last, and its terminal card shows the working directory. In the Linux Container, output that reaches computerd after its command has exited stops the container: computerd 0.3.1 throws on it and exits, so on Cloudflare a command that prints a few hundred KB faster than the Durable Object reads it usually fails with an internal error, and the container restarts. The fix waits for the Computer release that carries cloudflare/computer#260 (#373). A `timeoutMs` above the deployment ceiling is lowered to it, as upstream clamps it; the HTTP exec route still refuses one. `cancelled` reflects an adapter-requested interruption; `timedOut` independently records deadline expiry.
|
|
382
382
|
|
|
383
383
|
### Durability and concurrency
|
|
384
384
|
|
package/README.zh.md
CHANGED
|
@@ -378,7 +378,7 @@ SQLite 的 `DELETE` 操作也会消耗每日行写入额度。迁移格式时,
|
|
|
378
378
|
- Request body 会增量消费。一旦越过路由上限,后续 chunk 只会排空而不会保留,路由返回 413。文件上传也会拒绝非法 UTF-8。
|
|
379
379
|
- 读取文件时先检查 VFS metadata,再通过相同的 1 MiB 上限收集已打开的 byte stream,从而关闭 `stat()` 与 `readFile()` 之间的增长竞态,且不保留无界值。
|
|
380
380
|
- 写入前,图片准入会完整解码声明的 raster 格式。
|
|
381
|
-
- 与上游 `bash-local` 一致,输出超过上限后命令会继续运行:每个流内联保留最后 64,000 字节(默认值,即 Shell 卡片的输出上限,可设为 1 KiB 到 1 MiB),整个流保存到 `/workspace/.spill/bash-<execution>.<stream>.txt`(与其他 spill 一样 30 天后删除),每个流最多 16 MiB(上游允许 64 MiB;每 512 KiB 约写 5 行 Durable Object 数据,且工作区存储不会释放已删除的字节,#358),超过后文件只保留开头部分,结果中会注明。内存只占尾部加每个流 1 MiB 的写入队列:写 spill 时会暂停读取命令输出。未超过上限的输出不写任何文件。轻量 shell(just-bash)一次性返回命令的完整输出而不是流式输出,所以输出超过 8 MiB 时仍会停止命令(exit 126,显示为 `[stopped: …]`);这块缓冲位于它所在的 isolate 中,Direct 模式下就是 Durable Object。bash 工具按上游格式呈现结果:stdout、`[stderr]` 段、每个流的 `[output truncated; full output: <path>]`、`[timed out after Nms]`,最后是 `[exit code: N]
|
|
381
|
+
- 与上游 `bash-local` 一致,输出超过上限后命令会继续运行:每个流内联保留最后 64,000 字节(默认值,即 Shell 卡片的输出上限,可设为 1 KiB 到 1 MiB),整个流保存到 `/workspace/.spill/bash-<execution>.<stream>.txt`(与其他 spill 一样 30 天后删除),每个流最多 16 MiB(上游允许 64 MiB;每 512 KiB 约写 5 行 Durable Object 数据,且工作区存储不会释放已删除的字节,#358),超过后文件只保留开头部分,结果中会注明。内存只占尾部加每个流 1 MiB 的写入队列:写 spill 时会暂停读取命令输出。未超过上限的输出不写任何文件。轻量 shell(just-bash)一次性返回命令的完整输出而不是流式输出,所以输出超过 8 MiB 时仍会停止命令(exit 126,显示为 `[stopped: …]`);这块缓冲位于它所在的 isolate 中,Direct 模式下就是 Durable Object。bash 工具按上游格式呈现结果:stdout、`[stderr]` 段、每个流的 `[output truncated; full output: <path>]`、`[timed out after Nms]`,最后是 `[exit code: N]`;终端卡片会显示工作目录。在 Linux Container 中,命令退出后才到达 computerd 的输出会让容器停止:computerd 0.3.1 遇到这种输出会抛出异常并退出,所以在 Cloudflare 上,一条输出几百 KB、且输出速度快于 Durable Object 读取速度的命令通常会以内部错误失败,容器随后重启。修复要等包含 cloudflare/computer#260 的 Computer 版本(#373)。超过部署上限的 `timeoutMs` 会像上游一样被降到上限;HTTP exec 路由仍会拒绝它。`cancelled` 反映 adapter 请求的中断;`timedOut` 独立记录 deadline expiry。
|
|
382
382
|
|
|
383
383
|
### 持久性与并发
|
|
384
384
|
|
package/package.json
CHANGED
package/worker/direct/index.js
CHANGED
|
@@ -164,7 +164,7 @@ Known schemas:
|
|
|
164
164
|
- `)}`,new Error(at)}let Nt=`${c}/$ref`,vt=fa(e,Ke,n,r,i,s,o,Nt,l);if(vt.valid||Me.push({instanceLocation:o,keyword:"$ref",keywordLocation:Nt,error:"A subschema had errors."},...vt.errors),n==="4"||n==="7")return{valid:Me.length===0,errors:Me}}if(Array.isArray(f)){let tt=f.length,Ke=!1;for(let Nt=0;Nt<tt;Nt++)if(d===f[Nt]||f[Nt]==="integer"&&d==="number"&&e%1===0&&e===e){Ke=!0;break}Ke||Me.push({instanceLocation:o,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${d}" is invalid. Expected "${f.join('", "')}".`})}else f==="integer"?(d!=="number"||e%1||e!==e)&&Me.push({instanceLocation:o,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${d}" is invalid. Expected "${f}".`}):f!==void 0&&d!==f&&Me.push({instanceLocation:o,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${d}" is invalid. Expected "${f}".`});if(g!==void 0&&(d==="object"||d==="array"?PI(e,g)||Me.push({instanceLocation:o,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(g)}.`}):e!==g&&Me.push({instanceLocation:o,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(g)}.`})),v!==void 0&&(d==="object"||d==="array"?v.some(tt=>PI(e,tt))||Me.push({instanceLocation:o,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`}):v.some(tt=>e===tt)||Me.push({instanceLocation:o,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})),b!==void 0){let tt=`${c}/not`;fa(e,b,n,r,i,s,o,tt).valid&&Me.push({instanceLocation:o,keyword:"not",keywordLocation:tt,error:'Instance matched "not" schema.'})}let _t=[];if(w!==void 0){let tt=`${c}/anyOf`,Ke=Me.length,Nt=!1;for(let vt=0;vt<w.length;vt++){let at=w[vt],Ot=Object.create(l),qe=fa(e,at,n,r,i,m===!0?s:null,o,`${tt}/${vt}`,Ot);Me.push(...qe.errors),Nt=Nt||qe.valid,qe.valid&&_t.push(Ot)}Nt?Me.length=Ke:Me.splice(Ke,0,{instanceLocation:o,keyword:"anyOf",keywordLocation:tt,error:"Instance does not match any subschemas."})}if(k!==void 0){let tt=`${c}/allOf`,Ke=Me.length,Nt=!0;for(let vt=0;vt<k.length;vt++){let at=k[vt],Ot=Object.create(l),qe=fa(e,at,n,r,i,m===!0?s:null,o,`${tt}/${vt}`,Ot);Me.push(...qe.errors),Nt=Nt&&qe.valid,qe.valid&&_t.push(Ot)}Nt?Me.length=Ke:Me.splice(Ke,0,{instanceLocation:o,keyword:"allOf",keywordLocation:tt,error:"Instance does not match every subschema."})}if(E!==void 0){let tt=`${c}/oneOf`,Ke=Me.length,Nt=E.filter((vt,at)=>{let Ot=Object.create(l),qe=fa(e,vt,n,r,i,m===!0?s:null,o,`${tt}/${at}`,Ot);return Me.push(...qe.errors),qe.valid&&_t.push(Ot),qe.valid}).length;Nt===1?Me.length=Ke:Me.splice(Ke,0,{instanceLocation:o,keyword:"oneOf",keywordLocation:tt,error:`Instance does not match exactly one subschema (${Nt} matches).`})}if((d==="object"||d==="array")&&Object.assign(l,..._t),A!==void 0){let tt=`${c}/if`;if(fa(e,A,n,r,i,s,o,tt,l).valid){if(I!==void 0){let Nt=fa(e,I,n,r,i,s,o,`${c}/then`,l);Nt.valid||Me.push({instanceLocation:o,keyword:"if",keywordLocation:tt,error:'Instance does not match "then" schema.'},...Nt.errors)}}else if(O!==void 0){let Nt=fa(e,O,n,r,i,s,o,`${c}/else`,l);Nt.valid||Me.push({instanceLocation:o,keyword:"if",keywordLocation:tt,error:'Instance does not match "else" schema.'},...Nt.errors)}}if(d==="object"){if(x!==void 0)for(let vt of x)vt in e||Me.push({instanceLocation:o,keyword:"required",keywordLocation:`${c}/required`,error:`Instance does not have required property "${vt}".`});let tt=Object.keys(e);if(R!==void 0&&tt.length<R&&Me.push({instanceLocation:o,keyword:"minProperties",keywordLocation:`${c}/minProperties`,error:`Instance does not have at least ${R} properties.`}),B!==void 0&&tt.length>B&&Me.push({instanceLocation:o,keyword:"maxProperties",keywordLocation:`${c}/maxProperties`,error:`Instance does not have at least ${B} properties.`}),C!==void 0){let vt=`${c}/propertyNames`;for(let at in e){let Ot=`${o}/${yh(at)}`,qe=fa(at,C,n,r,i,s,Ot,vt);qe.valid||Me.push({instanceLocation:o,keyword:"propertyNames",keywordLocation:vt,error:`Property name "${at}" does not match schema.`},...qe.errors)}}if(N!==void 0){let vt=`${c}/dependantRequired`;for(let at in N)if(at in e){let Ot=N[at];for(let qe of Ot)qe in e||Me.push({instanceLocation:o,keyword:"dependentRequired",keywordLocation:vt,error:`Instance has "${at}" but does not have "${qe}".`})}}if(U!==void 0)for(let vt in U){let at=`${c}/dependentSchemas`;if(vt in e){let Ot=fa(e,U[vt],n,r,i,s,o,`${at}/${yh(vt)}`,l);Ot.valid||Me.push({instanceLocation:o,keyword:"dependentSchemas",keywordLocation:at,error:`Instance has "${vt}" but does not match dependant schema.`},...Ot.errors)}}if(L!==void 0){let vt=`${c}/dependencies`;for(let at in L)if(at in e){let Ot=L[at];if(Array.isArray(Ot))for(let qe of Ot)qe in e||Me.push({instanceLocation:o,keyword:"dependencies",keywordLocation:vt,error:`Instance has "${at}" but does not have "${qe}".`});else{let qe=fa(e,Ot,n,r,i,s,o,`${vt}/${yh(at)}`);qe.valid||Me.push({instanceLocation:o,keyword:"dependencies",keywordLocation:vt,error:`Instance has "${at}" but does not match dependant schema.`},...qe.errors)}}}let Ke=Object.create(null),Nt=!1;if($!==void 0){let vt=`${c}/properties`;for(let at in $){if(!(at in e))continue;let Ot=`${o}/${yh(at)}`,qe=fa(e[at],$[at],n,r,i,s,Ot,`${vt}/${yh(at)}`);if(qe.valid)l[at]=Ke[at]=!0;else if(Nt=i,Me.push({instanceLocation:o,keyword:"properties",keywordLocation:vt,error:`Property "${at}" does not match schema.`},...qe.errors),Nt)break}}if(!Nt&&D!==void 0){let vt=`${c}/patternProperties`;for(let at in D){let Ot=new RegExp(at,"u"),qe=D[at];for(let Bt in e){if(!Ot.test(Bt))continue;let yn=`${o}/${yh(Bt)}`,It=fa(e[Bt],qe,n,r,i,s,yn,`${vt}/${yh(at)}`);It.valid?l[Bt]=Ke[Bt]=!0:(Nt=i,Me.push({instanceLocation:o,keyword:"patternProperties",keywordLocation:vt,error:`Property "${Bt}" matches pattern "${at}" but does not match associated schema.`},...It.errors))}}}if(!Nt&&W!==void 0){let vt=`${c}/additionalProperties`;for(let at in e){if(Ke[at])continue;let Ot=`${o}/${yh(at)}`,qe=fa(e[at],W,n,r,i,s,Ot,vt);qe.valid?l[at]=!0:(Nt=i,Me.push({instanceLocation:o,keyword:"additionalProperties",keywordLocation:vt,error:`Property "${at}" does not match additional properties schema.`},...qe.errors))}}else if(!Nt&&ee!==void 0){let vt=`${c}/unevaluatedProperties`;for(let at in e)if(!l[at]){let Ot=`${o}/${yh(at)}`,qe=fa(e[at],ee,n,r,i,s,Ot,vt);qe.valid?l[at]=!0:Me.push({instanceLocation:o,keyword:"unevaluatedProperties",keywordLocation:vt,error:`Property "${at}" does not match unevaluated properties schema.`},...qe.errors)}}}else if(d==="array"){ue!==void 0&&e.length>ue&&Me.push({instanceLocation:o,keyword:"maxItems",keywordLocation:`${c}/maxItems`,error:`Array has too many items (${e.length} > ${ue}).`}),me!==void 0&&e.length<me&&Me.push({instanceLocation:o,keyword:"minItems",keywordLocation:`${c}/minItems`,error:`Array has too few items (${e.length} < ${me}).`});let tt=e.length,Ke=0,Nt=!1;if(F!==void 0){let vt=`${c}/prefixItems`,at=Math.min(F.length,tt);for(;Ke<at;Ke++){let Ot=fa(e[Ke],F[Ke],n,r,i,s,`${o}/${Ke}`,`${vt}/${Ke}`);if(l[Ke]=!0,!Ot.valid&&(Nt=i,Me.push({instanceLocation:o,keyword:"prefixItems",keywordLocation:vt,error:"Items did not match schema."},...Ot.errors),Nt))break}}if(K!==void 0){let vt=`${c}/items`;if(Array.isArray(K)){let at=Math.min(K.length,tt);for(;Ke<at;Ke++){let Ot=fa(e[Ke],K[Ke],n,r,i,s,`${o}/${Ke}`,`${vt}/${Ke}`);if(l[Ke]=!0,!Ot.valid&&(Nt=i,Me.push({instanceLocation:o,keyword:"items",keywordLocation:vt,error:"Items did not match schema."},...Ot.errors),Nt))break}}else for(;Ke<tt;Ke++){let at=fa(e[Ke],K,n,r,i,s,`${o}/${Ke}`,vt);if(l[Ke]=!0,!at.valid&&(Nt=i,Me.push({instanceLocation:o,keyword:"items",keywordLocation:vt,error:"Items did not match schema."},...at.errors),Nt))break}if(!Nt&&Z!==void 0){let at=`${c}/additionalItems`;for(;Ke<tt;Ke++){let Ot=fa(e[Ke],Z,n,r,i,s,`${o}/${Ke}`,at);l[Ke]=!0,Ot.valid||(Nt=i,Me.push({instanceLocation:o,keyword:"additionalItems",keywordLocation:at,error:"Items did not match additional items schema."},...Ot.errors))}}}if(V!==void 0)if(tt===0&&se===void 0)Me.push({instanceLocation:o,keyword:"contains",keywordLocation:`${c}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(se!==void 0&&tt<se)Me.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array has less items (${tt}) than minContains (${se}).`});else{let vt=`${c}/contains`,at=Me.length,Ot=0;for(let qe=0;qe<tt;qe++){let Bt=fa(e[qe],V,n,r,i,s,`${o}/${qe}`,vt);Bt.valid?(l[qe]=!0,Ot++):Me.push(...Bt.errors)}Ot>=(se||0)&&(Me.length=at),se===void 0&&ve===void 0&&Ot===0?Me.splice(at,0,{instanceLocation:o,keyword:"contains",keywordLocation:vt,error:"Array does not contain item matching schema."}):se!==void 0&&Ot<se?Me.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array must contain at least ${se} items matching schema. Only ${Ot} items were found.`}):ve!==void 0&&Ot>ve&&Me.push({instanceLocation:o,keyword:"maxContains",keywordLocation:`${c}/maxContains`,error:`Array may contain at most ${ve} items matching schema. ${Ot} items were found.`})}if(!Nt&&ne!==void 0){let vt=`${c}/unevaluatedItems`;for(Ke;Ke<tt;Ke++){if(l[Ke])continue;let at=fa(e[Ke],ne,n,r,i,s,`${o}/${Ke}`,vt);l[Ke]=!0,at.valid||Me.push({instanceLocation:o,keyword:"unevaluatedItems",keywordLocation:vt,error:"Items did not match unevaluated items schema."},...at.errors)}}if(Ae)for(let vt=0;vt<tt;vt++){let at=e[vt],Ot=typeof at=="object"&&at!==null;for(let qe=0;qe<tt;qe++){if(vt===qe)continue;let Bt=e[qe];(at===Bt||Ot&&(typeof Bt=="object"&&Bt!==null)&&PI(at,Bt))&&(Me.push({instanceLocation:o,keyword:"uniqueItems",keywordLocation:`${c}/uniqueItems`,error:`Duplicate items at indexes ${vt} and ${qe}.`}),vt=Number.MAX_SAFE_INTEGER,qe=Number.MAX_SAFE_INTEGER)}}}else if(d==="number"){if(n==="4"?(Re!==void 0&&(pe===!0&&e<=Re||e<Re)&&Me.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${pe?"or equal to ":""} ${Re}.`}),fe!==void 0&&(et===!0&&e>=fe||e>fe)&&Me.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${et?"or equal to ":""} ${fe}.`})):(Re!==void 0&&e<Re&&Me.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${Re}.`}),fe!==void 0&&e>fe&&Me.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${fe}.`}),pe!==void 0&&e<=pe&&Me.push({instanceLocation:o,keyword:"exclusiveMinimum",keywordLocation:`${c}/exclusiveMinimum`,error:`${e} is less than ${pe}.`}),et!==void 0&&e>=et&&Me.push({instanceLocation:o,keyword:"exclusiveMaximum",keywordLocation:`${c}/exclusiveMaximum`,error:`${e} is greater than or equal to ${et}.`})),Xe!==void 0){let tt=e%Xe;Math.abs(0-tt)>=11920929e-14&&Math.abs(Xe-tt)>=11920929e-14&&Me.push({instanceLocation:o,keyword:"multipleOf",keywordLocation:`${c}/multipleOf`,error:`${e} is not a multiple of ${Xe}.`})}}else if(d==="string"){let tt=gt===void 0&&Fe===void 0?0:rJe(e);gt!==void 0&&tt<gt&&Me.push({instanceLocation:o,keyword:"minLength",keywordLocation:`${c}/minLength`,error:`String is too short (${tt} < ${gt}).`}),Fe!==void 0&&tt>Fe&&Me.push({instanceLocation:o,keyword:"maxLength",keywordLocation:`${c}/maxLength`,error:`String is too long (${tt} > ${Fe}).`}),Oe!==void 0&&!new RegExp(Oe,"u").test(e)&&Me.push({instanceLocation:o,keyword:"pattern",keywordLocation:`${c}/pattern`,error:"String does not match pattern."}),M!==void 0&&G0e[M]&&!G0e[M](e)&&Me.push({instanceLocation:o,keyword:"format",keywordLocation:`${c}/format`,error:`String does not match format "${M}".`})}return{valid:Me.length===0,errors:Me}}var Q0e=q(()=>{H0e();dB();V0e();uB();K0e();a(fa,"validate")});var pB,iJe=q(()=>{dB();Q0e();pB=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=K1(t)}validate(t){return fa(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,n){n&&(t={...t,$id:n}),K1(t,this.lookup)}}});var sJe=q(()=>{H0e();dB();V0e();uB();nJe();K0e();Q0e();iJe()});var hB,oJe=q(()=>{sJe();hB=class{static{a(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let n=new pB(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 ta,mB=q(()=>{"use strict";ta={probeTimeoutMs:3e4,callTimeoutMs:6e4,maxToolsPerServer:128,maxCatalogPages:10,maxCatalogBytes:131072,maxDescriptionLength:512,maxErrorMessageChars:300,maxPublicNameLength:64,maxInstructionsLength:1024,metaToolThreshold:20,maxResourceResponseBytes:1048576}});import{createHash as Wun}from"node:crypto";function zun(e){let t=e.replace(/[.*+?^${}()|[\]\\]/gu,n=>n==="*"?"\0":`\\${n}`);return new RegExp(`^${t.replaceAll("\0",".*")}$`)}function J0e(e,t,n){let r=t??"read_only";return r==="allow_all"?"allow":r==="approve_all"?"ask":n===!0?"allow":n===!1?"ask":Bun.some(i=>zun(i).test(e))?"allow":"ask"}function km(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,ta.maxErrorMessageChars)}function aJe(e,t){let n=`mcp__${e}__${t}`,r=n.replace(/[^A-Za-z0-9_-]/gu,"_");if(r===n&&r.length<=ta.maxPublicNameLength)return r;let i=Hun(e,t),s=ta.maxPublicNameLength-i.length-1;return`${r.slice(0,s)}_${i}`}function Hun(e,t){return Wun("sha256").update(`${e}\0${t}`).digest("hex").slice(0,12)}function cJe(e){if(!(e==null||typeof e!="object"))try{let t=JSON.parse(JSON.stringify(e));return x2(t),t}catch{return}}function Kun(e){return Gun.has(e)}function lJe(e){return e.type!=="image"||e.data===void 0||e.mimeType===void 0||!Kun(e.mimeType)||!Vun.test(e.data)?void 0:{data:Uint8Array.from(atob(e.data),n=>n.charCodeAt(0)),mediaType:e.mimeType}}function uJe(e){return e.some(t=>t.type==="image"&&t.data!==void 0)}function yO(e){if(e.isError)return[{type:"text",text:e.content.filter(i=>i.type==="text"&&typeof i.text=="string").map(i=>i.text).join(`
|
|
165
165
|
`)||"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} ---
|
|
166
166
|
${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(`
|
|
167
|
-
`)}),t.length>0?t:[{type:"text",text:"(empty MCP result)"}]}var Bun,Gun,Vun,fB=q(()=>{"use strict";uo();mB();Bun=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a(zun,"globToRegExp");a(J0e,"evaluateMcpToolPolicy");a(km,"scrubMcpErrorMessage");a(aJe,"publicToolName");a(Hun,"hashSuffix");a(cJe,"supportedOutputSchema");Gun=new Set(["image/png","image/jpeg"]),Vun=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(Kun,"isImageMediaType");a(lJe,"decodeImageBlock");a(uJe,"containsImage");a(yO,"mapMcpResultToContentBlocks")});var Y0e,dJe=q(()=>{Y0e={name:"dsh-edge",version:"0.29.0-alpha.1",description:"Your DeepSeek Harness, anywhere \u2014 deploy a persistent personal coding agent to Cloudflare Workers in one command",author:"pawaca",license:"MIT",type:"module",bin:{"dsh-edge":"scripts/cli.mjs"},files:["dist","worker","scripts/*.d.mts","scripts/*.mjs","wrangler.jsonc","README.md","README.zh.md","LICENSE","THIRD_PARTY_NOTICES.md"],repository:{type:"git",url:"git+https://github.com/pawaca/dsh-edge.git",directory:"apps/dsh-edge"},homepage:"https://github.com/pawaca/dsh-edge#readme",bugs:{url:"https://github.com/pawaca/dsh-edge/issues"},keywords:["deepseek","deepseek-harness","ai-agents","byok","cloudflare-workers","durable-objects","self-hosted"],engines:{node:">=22.14.0"},publishConfig:{access:"public"},dshEdge:{upstreamVersion:"0.2.1-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.5","@deepseek-ai/cosmokit":"1.8.6","@deepseek-ai/dsh-agent":"0.2.1-rc.2","@deepseek-ai/dsh-agent-instructions":"0.2.1-rc.2","@deepseek-ai/dsh-agent-loop":"0.2.1-rc.2","@deepseek-ai/dsh-anonymous-user-id":"0.2.1-rc.2","@deepseek-ai/dsh-api-gateway":"0.2.1-rc.2","@deepseek-ai/dsh-api-job-controller":"0.2.1-rc.2","@deepseek-ai/dsh-api-remote-access":"0.2.1-rc.2","@deepseek-ai/dsh-api-remotes":"0.2.1-rc.2","@deepseek-ai/dsh-api-session-controller":"0.2.1-rc.2","@deepseek-ai/dsh-api-settings-controller":"0.2.1-rc.2","@deepseek-ai/dsh-api-workspace-controller":"0.2.1-rc.2","@deepseek-ai/dsh-api-workspace-files":"0.2.1-rc.2","@deepseek-ai/dsh-attachment":"0.2.1-rc.2","@deepseek-ai/dsh-brand":"0.2.1-rc.2","@deepseek-ai/dsh-client-connection":"0.2.1-rc.2","@deepseek-ai/dsh-client-file-upload":"0.2.1-rc.2","@deepseek-ai/dsh-client-locale":"0.2.1-rc.2","@deepseek-ai/dsh-client-store":"0.2.1-rc.2","@deepseek-ai/dsh-client-ui-chat":"0.2.1-rc.2","@deepseek-ai/dsh-client-ui-conversation":"0.2.1-rc.2","@deepseek-ai/dsh-client-ui-settings":"0.2.1-rc.2","@deepseek-ai/dsh-client-ui-settings-general":"0.2.1-rc.2","@deepseek-ai/dsh-client-ui-theme":"0.2.1-rc.2","@deepseek-ai/dsh-command-compact":"0.2.1-rc.2","@deepseek-ai/dsh-command-feedback":"0.2.1-rc.2","@deepseek-ai/dsh-command-goal":"0.2.1-rc.2","@deepseek-ai/dsh-commands":"0.2.1-rc.2","@deepseek-ai/dsh-compaction":"0.2.1-rc.2","@deepseek-ai/dsh-compaction-basic":"0.2.1-rc.2","@deepseek-ai/dsh-compaction-image-offload":"0.2.1-rc.2","@deepseek-ai/dsh-compaction-tool-result-pruner":"0.2.1-rc.2","@deepseek-ai/dsh-credentials":"0.2.1-rc.2","@deepseek-ai/dsh-file-reference":"0.2.1-rc.2","@deepseek-ai/dsh-fs":"0.2.1-rc.2","@deepseek-ai/dsh-fs-observation-policy":"0.2.1-rc.2","@deepseek-ai/dsh-goal":"0.2.1-rc.2","@deepseek-ai/dsh-goal-round-driver":"0.2.1-rc.2","@deepseek-ai/dsh-home-paths":"0.2.1-rc.2","@deepseek-ai/dsh-host-directory-picker":"0.2.1-rc.2","@deepseek-ai/dsh-host-plugin-inventory":"0.2.1-rc.2","@deepseek-ai/dsh-jobs":"0.2.1-rc.2","@deepseek-ai/dsh-jobs-local":"0.2.1-rc.2","@deepseek-ai/dsh-launch-environment":"0.2.1-rc.2","@deepseek-ai/dsh-llm":"0.2.1-rc.2","@deepseek-ai/dsh-mcp-resources":"0.2.1-rc.2","@deepseek-ai/dsh-llm-deepseek":"0.2.1-rc.2","@deepseek-ai/dsh-llm-deepseek-api-key":"0.2.1-rc.2","@deepseek-ai/dsh-llm-pi-ai":"0.2.1-rc.2","@deepseek-ai/dsh-llm-retry":"0.2.1-rc.2","@deepseek-ai/dsh-message-feedback":"0.2.1-rc.2","@deepseek-ai/dsh-output-retention":"0.2.1-rc.2","@deepseek-ai/dsh-plan-mode":"0.2.1-rc.2","@deepseek-ai/dsh-ptc-runtime":"0.2.1-rc.2","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.1-rc.2","@deepseek-ai/dsh-sandbox":"0.2.1-rc.2","@deepseek-ai/dsh-schedule":"0.2.1-rc.2","@deepseek-ai/dsh-scope":"0.2.1-rc.2","@deepseek-ai/dsh-session":"0.2.1-rc.2","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.1-rc.2","@deepseek-ai/dsh-session-log-export":"0.2.1-rc.2","@deepseek-ai/dsh-session-format":"0.2.1-rc.2","@deepseek-ai/dsh-session-format-catalog":"0.2.1-rc.2","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.1-rc.2","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.1-rc.2","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.1-rc.2","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.1-rc.2","@deepseek-ai/dsh-session-persistence":"0.2.1-rc.2","@deepseek-ai/dsh-session-projection":"0.2.1-rc.2","@deepseek-ai/dsh-session-projection-cache":"0.2.1-rc.2","@deepseek-ai/dsh-session-stats":"0.2.1-rc.2","@deepseek-ai/dsh-session-turn-outline":"0.2.1-rc.2","@deepseek-ai/dsh-session-query":"0.2.1-rc.2","@deepseek-ai/dsh-session-reference":"0.2.1-rc.2","@deepseek-ai/dsh-session-title":"0.2.1-rc.2","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.1-rc.2","@deepseek-ai/dsh-shell-env":"0.2.1-rc.2","@deepseek-ai/dsh-session-title-llm":"0.2.1-rc.2","@deepseek-ai/dsh-settings":"0.2.1-rc.2","@deepseek-ai/dsh-skill":"0.2.1-rc.2","@deepseek-ai/dsh-spill":"0.2.1-rc.2","@deepseek-ai/dsh-spill-policy":"0.2.1-rc.2","@deepseek-ai/dsh-storage":"0.2.1-rc.2","@deepseek-ai/dsh-storage-domain":"0.2.1-rc.2","@deepseek-ai/dsh-subagent":"0.2.1-rc.2","@deepseek-ai/dsh-subagent-fork-in-process":"0.2.1-rc.2","@deepseek-ai/dsh-subagent-spawn-in-process":"0.2.1-rc.2","@deepseek-ai/dsh-system-prompt":"0.2.1-rc.2","@deepseek-ai/dsh-time-context":"0.2.1-rc.2","@deepseek-ai/dsh-timeout":"0.2.1-rc.2","@deepseek-ai/dsh-token-meter":"0.2.1-rc.2","@deepseek-ai/dsh-tool-ask-user":"0.2.1-rc.2","@deepseek-ai/dsh-tool-call-timeout-policy":"0.2.1-rc.2","@deepseek-ai/dsh-tool-fs":"0.2.1-rc.2","@deepseek-ai/dsh-tool-fs-search":"0.2.1-rc.2","@deepseek-ai/dsh-tool-goal":"0.2.1-rc.2","@deepseek-ai/dsh-tool-jobs":"0.2.1-rc.2","@deepseek-ai/dsh-tool-ralph":"0.2.1-rc.2","@deepseek-ai/dsh-tool-schedule":"0.2.1-rc.2","@deepseek-ai/dsh-tool-session-query":"0.2.1-rc.2","@deepseek-ai/dsh-tool-skill":"0.2.1-rc.2","@deepseek-ai/dsh-tool-subagent":"0.2.1-rc.2","@deepseek-ai/dsh-tool-subagent-control":"0.2.1-rc.2","@deepseek-ai/dsh-tool-present":"0.2.1-rc.2","@deepseek-ai/dsh-tool-todo":"0.2.1-rc.2","@deepseek-ai/dsh-tool-web":"0.2.1-rc.2","@deepseek-ai/dsh-tool-workflow":"0.2.1-rc.2","@deepseek-ai/dsh-tool-working-directory":"0.2.1-rc.2","@deepseek-ai/dsh-tools":"0.2.1-rc.2","@deepseek-ai/dsh-typert-protocol":"0.2.1-rc.2","@deepseek-ai/dsh-typert-registry":"0.2.1-rc.2","@deepseek-ai/dsh-user-approval":"0.2.1-rc.2","@deepseek-ai/dsh-user-questions":"0.2.1-rc.2","@deepseek-ai/dsh-util-values":"0.2.1-rc.2","@deepseek-ai/dsh-web":"0.2.1-rc.2","@deepseek-ai/dsh-web-deepseek-api":"0.2.1-rc.2","@deepseek-ai/dsh-web-fetch-http":"0.2.1-rc.2","@deepseek-ai/dsh-web-search-deepseek":"0.2.1-rc.2","@deepseek-ai/dsh-workflow":"0.2.1-rc.2","@deepseek-ai/dsh-working-directory":"0.2.1-rc.2","@deepseek-ai/dsh-workspace":"0.2.1-rc.2","@deepseek-ai/schemastery":"3.18.5","@mixmark-io/domino":"2.2.0","@modelcontextprotocol/sdk":"1.30.0",acorn:"8.18.0","fast-png":"8.0.0",fflate:"0.8.3","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 kS,pJe,hJe,vO=q(()=>{"use strict";dJe();kS=Y0e.version,pJe=Y0e.dshEdge.upstreamVersion,hJe=`npx dsh-edge@${kS.includes("-")?"next":"latest"} upgrade`});function Zun(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 edn(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 Jun)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(edn(i)){let s=Zun(i),o=s??i;for(let c of Yun)if(c.test(o))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`);if(s===void 0){for(let c of Xun)if(c.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function tdn(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}function rdn(e){return async(t,n)=>{let r=await Ib(t,n);if(r.body===null)return r;let i=0,s=r.body.pipeThrough(new TransformStream({transform(o,c){if(i+=o.byteLength,i>e){c.error(new Error(`MCP server response is larger than ${String(e)} bytes.`));return}c.enqueue(o)}}));return new Response(s,{status:r.status,statusText:r.statusText,headers:r.headers})}}async function X0e(e,t,n,r){Q1(e);let i=new lB(new URL(e),{requestInit:{headers:tdn(t),signal:n},fetch:r===void 0?Ib:rdn(r)}),s=new aB({name:"dsh-edge",version:kS},{capabilities:{},jsonSchemaValidator:ndn});return await s.connect(i),{client:s,close:a(async()=>{await s.close().catch(()=>{})},"close")}}async function mJe(e,t,n){let r=AbortSignal.timeout(ta.probeTimeoutMs),i;try{i=await X0e(t,n,r)}catch(c){throw new Error(km(c instanceof Error?c.message:String(c)))}let{client:s,close:o}=i;try{let c=[],l=new Set,u=new Set,d,p=s.getServerCapabilities?.()?.tools!==void 0;for(let g=0;p&&g<ta.maxCatalogPages;g++){let v=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let x of v.tools){if(c.length>=ta.maxToolsPerServer)break;let b=aJe(e,x.name);if(l.has(b))throw new Error(`Server listed tool "${x.name}" more than once`);l.add(b);let w=x.annotations?.readOnlyHint,k=cJe(x.outputSchema);c.push({name:x.name,publicName:b,description:x.description??"",inputSchema:x.inputSchema??{type:"object"},...k!==void 0?{outputSchema:k}:{},...w!==void 0?{annotations:{readOnlyHint:w}}:{}})}if(c.length>=ta.maxToolsPerServer||(d=v.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 h=s.getServerVersion?.(),m=s.getInstructions?.(),f=s.getServerCapabilities?.()?.resources!==void 0;return{tools:c,serverInfo:h?{name:h.name,version:h.version}:void 0,instructions:typeof m=="string"&&m.length>0?m.slice(0,ta.maxInstructionsLength):void 0,resources:f}}finally{await o()}}async function gB(e,t,n,r,i,s){let o=s??ta.callTimeoutMs,c=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),l;try{l=await X0e(e,r,c)}catch(u){throw new Error(km(u instanceof Error?u.message:String(u)))}try{let u=await l.client.callTool({name:t,arguments:n},void 0,{signal:c});return{content:u.content??[],structuredContent:u.structuredContent,isError:u.isError===!0}}catch(u){throw new Error(km(u instanceof Error?u.message:String(u)))}finally{await l.close()}}async function fJe(e,t,n,r,i){let s=i??ta.callTimeoutMs,o=r?AbortSignal.any([r,AbortSignal.timeout(s)]):AbortSignal.timeout(s),c;try{c=await X0e(e,n,o,ta.maxResourceResponseBytes)}catch(l){throw new Error(km(l instanceof Error?l.message:String(l)))}try{let{client:l}=c;if(t.method==="resources/read")return await l.readResource({uri:t.uri},{signal:o});let u=t.method==="resources/list"?"resources":"resourceTemplates",d=a(g=>t.method==="resources/list"?l.listResources(g===void 0?void 0:{cursor:g},{signal:o}):l.listResourceTemplates(g===void 0?void 0:{cursor:g},{signal:o}),"page");if(t.cursor!==void 0)return await d(t.cursor);let p=[],h=new Set,m=0,f;for(let g=0;g<ta.maxCatalogPages;g++){let v=await d(f),x=Array.isArray(v[u])?v[u]:[],b=new TextEncoder().encode(JSON.stringify(x)).byteLength;if(p.length>0&&m+b>ta.maxResourceResponseBytes)break;p.push(...x),m+=b;let w=typeof v.nextCursor=="string"?v.nextCursor:void 0;if(w===void 0){f=void 0;break}if(h.has(w))throw new Error(`Server repeated a ${t.method} continuation cursor`);h.add(w),f=w}return f===void 0?{[u]:p}:{[u]:p,nextCursor:f}}catch(l){throw new Error(km(l instanceof Error?l.message:String(l)))}finally{await c.close()}}var Jun,Yun,Xun,ndn,Ib,xO=q(()=>{"use strict";xQe();XQe();oJe();fB();mB();vO();Jun=[".internal",".local",".localhost"],Yun=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],Xun=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(Zun,"extractMappedIPv4");a(edn,"isIpAddress");a(Q1,"assertSafeUrl");a(tdn,"buildHeaders");ndn=new hB,Ib=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(rdn,"byteCappedFetch");a(X0e,"connectClient");a(mJe,"probe");a(gB,"callTool");a(fJe,"requestResources")});var vB={};Ut(vB,{buildAuthorizationUrl:()=>pdn,discoverEndpoints:()=>udn,exchangeCode:()=>hdn,isTokenExpired:()=>fdn,refreshToken:()=>mdn,registerClient:()=>ddn});function xJe(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 ldn(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 udn(e){let t=AbortSignal.timeout(yB),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 Ib(i.href,{signal:t});if(!s.ok)throw new Error(`PRM discovery failed: HTTP ${s.status}`);let c=(await s.json()).authorization_servers?.[0];if(typeof c!="string")throw new Error("No authorization server in PRM");let l=new URL(c),u=l.pathname==="/"?"/.well-known/oauth-authorization-server":`/.well-known/oauth-authorization-server${l.pathname}`,d=new URL(u,l.origin);Q1(d.href);let p=await Ib(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 ddn(e,t,n){let r=AbortSignal.timeout(yB);Q1(e);let i=await Ib(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 pdn(e,t,n,r,i){let s=xJe(32),o=xJe(64),c=await ldn(o),l=new URL(e.authorization);for(let[u,d]of Object.entries({response_type:"code",client_id:t.clientId,redirect_uri:n,state:s,code_challenge:c,code_challenge_method:"S256",resource:i}))l.searchParams.set(u,d);return{authorizationUrl:l.href,pendingFlow:{state:s,codeVerifier:o,redirectUri:n,serverName:r,serverUrl:i,stagedClient:t,createdAt:Date.now()}}}async function hdn(e,t,n,r,i,s){let o=AbortSignal.timeout(yB),c=new URLSearchParams({grant_type:"authorization_code",code:n,redirect_uri:i,client_id:t.clientId,code_verifier:r});s!==void 0&&c.set("resource",s),t.clientSecret!==void 0&&c.set("client_secret",t.clientSecret),Q1(e);let l=await Ib(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:c.toString(),signal:o});if(!l.ok)throw new Error(`Token exchange failed: HTTP ${l.status}`);return bJe(await l.json())}async function mdn(e,t,n,r){let i=AbortSignal.timeout(yB),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 Ib(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 bJe(await o.json())}function bJe(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 fdn(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var yB,xB=q(()=>{"use strict";xO();yB=1e4;a(xJe,"randomString");a(ldn,"sha256Base64Url");a(udn,"discoverEndpoints");a(ddn,"registerClient");a(pdn,"buildAuthorizationUrl");a(hdn,"exchangeCode");a(mdn,"refreshToken");a(bJe,"parseTokenResponse");a(fdn,"isTokenExpired")});var dr,IJe,OI=q(()=>{fr();Lr();dr=class extends ii{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},IJe=class extends Lt{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new dr("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function _O(e){return PB.test(e)}function OB(e){return e.invocation.modelInvocable}function NI(e){return e.invocation.userInvocable}function yye(e){let t=Zpn(e);return[`<skill_content name="${ehn(e.name)}">`,"<skill_resources>",...t,"</skill_resources>","","<skill_instructions>",e.content,"</skill_instructions>","</skill_content>"].join(`
|
|
167
|
+
`)}),t.length>0?t:[{type:"text",text:"(empty MCP result)"}]}var Bun,Gun,Vun,fB=q(()=>{"use strict";uo();mB();Bun=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a(zun,"globToRegExp");a(J0e,"evaluateMcpToolPolicy");a(km,"scrubMcpErrorMessage");a(aJe,"publicToolName");a(Hun,"hashSuffix");a(cJe,"supportedOutputSchema");Gun=new Set(["image/png","image/jpeg"]),Vun=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(Kun,"isImageMediaType");a(lJe,"decodeImageBlock");a(uJe,"containsImage");a(yO,"mapMcpResultToContentBlocks")});var Y0e,dJe=q(()=>{Y0e={name:"dsh-edge",version:"0.29.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.1-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.5","@deepseek-ai/cosmokit":"1.8.6","@deepseek-ai/dsh-agent":"0.2.1-rc.2","@deepseek-ai/dsh-agent-instructions":"0.2.1-rc.2","@deepseek-ai/dsh-agent-loop":"0.2.1-rc.2","@deepseek-ai/dsh-anonymous-user-id":"0.2.1-rc.2","@deepseek-ai/dsh-api-gateway":"0.2.1-rc.2","@deepseek-ai/dsh-api-job-controller":"0.2.1-rc.2","@deepseek-ai/dsh-api-remote-access":"0.2.1-rc.2","@deepseek-ai/dsh-api-remotes":"0.2.1-rc.2","@deepseek-ai/dsh-api-session-controller":"0.2.1-rc.2","@deepseek-ai/dsh-api-settings-controller":"0.2.1-rc.2","@deepseek-ai/dsh-api-workspace-controller":"0.2.1-rc.2","@deepseek-ai/dsh-api-workspace-files":"0.2.1-rc.2","@deepseek-ai/dsh-attachment":"0.2.1-rc.2","@deepseek-ai/dsh-brand":"0.2.1-rc.2","@deepseek-ai/dsh-client-connection":"0.2.1-rc.2","@deepseek-ai/dsh-client-file-upload":"0.2.1-rc.2","@deepseek-ai/dsh-client-locale":"0.2.1-rc.2","@deepseek-ai/dsh-client-store":"0.2.1-rc.2","@deepseek-ai/dsh-client-ui-chat":"0.2.1-rc.2","@deepseek-ai/dsh-client-ui-conversation":"0.2.1-rc.2","@deepseek-ai/dsh-client-ui-settings":"0.2.1-rc.2","@deepseek-ai/dsh-client-ui-settings-general":"0.2.1-rc.2","@deepseek-ai/dsh-client-ui-theme":"0.2.1-rc.2","@deepseek-ai/dsh-command-compact":"0.2.1-rc.2","@deepseek-ai/dsh-command-feedback":"0.2.1-rc.2","@deepseek-ai/dsh-command-goal":"0.2.1-rc.2","@deepseek-ai/dsh-commands":"0.2.1-rc.2","@deepseek-ai/dsh-compaction":"0.2.1-rc.2","@deepseek-ai/dsh-compaction-basic":"0.2.1-rc.2","@deepseek-ai/dsh-compaction-image-offload":"0.2.1-rc.2","@deepseek-ai/dsh-compaction-tool-result-pruner":"0.2.1-rc.2","@deepseek-ai/dsh-credentials":"0.2.1-rc.2","@deepseek-ai/dsh-file-reference":"0.2.1-rc.2","@deepseek-ai/dsh-fs":"0.2.1-rc.2","@deepseek-ai/dsh-fs-observation-policy":"0.2.1-rc.2","@deepseek-ai/dsh-goal":"0.2.1-rc.2","@deepseek-ai/dsh-goal-round-driver":"0.2.1-rc.2","@deepseek-ai/dsh-home-paths":"0.2.1-rc.2","@deepseek-ai/dsh-host-directory-picker":"0.2.1-rc.2","@deepseek-ai/dsh-host-plugin-inventory":"0.2.1-rc.2","@deepseek-ai/dsh-jobs":"0.2.1-rc.2","@deepseek-ai/dsh-jobs-local":"0.2.1-rc.2","@deepseek-ai/dsh-launch-environment":"0.2.1-rc.2","@deepseek-ai/dsh-llm":"0.2.1-rc.2","@deepseek-ai/dsh-mcp-resources":"0.2.1-rc.2","@deepseek-ai/dsh-llm-deepseek":"0.2.1-rc.2","@deepseek-ai/dsh-llm-deepseek-api-key":"0.2.1-rc.2","@deepseek-ai/dsh-llm-pi-ai":"0.2.1-rc.2","@deepseek-ai/dsh-llm-retry":"0.2.1-rc.2","@deepseek-ai/dsh-message-feedback":"0.2.1-rc.2","@deepseek-ai/dsh-output-retention":"0.2.1-rc.2","@deepseek-ai/dsh-plan-mode":"0.2.1-rc.2","@deepseek-ai/dsh-ptc-runtime":"0.2.1-rc.2","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.1-rc.2","@deepseek-ai/dsh-sandbox":"0.2.1-rc.2","@deepseek-ai/dsh-schedule":"0.2.1-rc.2","@deepseek-ai/dsh-scope":"0.2.1-rc.2","@deepseek-ai/dsh-session":"0.2.1-rc.2","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.1-rc.2","@deepseek-ai/dsh-session-log-export":"0.2.1-rc.2","@deepseek-ai/dsh-session-format":"0.2.1-rc.2","@deepseek-ai/dsh-session-format-catalog":"0.2.1-rc.2","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.1-rc.2","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.1-rc.2","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.1-rc.2","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.1-rc.2","@deepseek-ai/dsh-session-persistence":"0.2.1-rc.2","@deepseek-ai/dsh-session-projection":"0.2.1-rc.2","@deepseek-ai/dsh-session-projection-cache":"0.2.1-rc.2","@deepseek-ai/dsh-session-stats":"0.2.1-rc.2","@deepseek-ai/dsh-session-turn-outline":"0.2.1-rc.2","@deepseek-ai/dsh-session-query":"0.2.1-rc.2","@deepseek-ai/dsh-session-reference":"0.2.1-rc.2","@deepseek-ai/dsh-session-title":"0.2.1-rc.2","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.1-rc.2","@deepseek-ai/dsh-shell-env":"0.2.1-rc.2","@deepseek-ai/dsh-session-title-llm":"0.2.1-rc.2","@deepseek-ai/dsh-settings":"0.2.1-rc.2","@deepseek-ai/dsh-skill":"0.2.1-rc.2","@deepseek-ai/dsh-spill":"0.2.1-rc.2","@deepseek-ai/dsh-spill-policy":"0.2.1-rc.2","@deepseek-ai/dsh-storage":"0.2.1-rc.2","@deepseek-ai/dsh-storage-domain":"0.2.1-rc.2","@deepseek-ai/dsh-subagent":"0.2.1-rc.2","@deepseek-ai/dsh-subagent-fork-in-process":"0.2.1-rc.2","@deepseek-ai/dsh-subagent-spawn-in-process":"0.2.1-rc.2","@deepseek-ai/dsh-system-prompt":"0.2.1-rc.2","@deepseek-ai/dsh-time-context":"0.2.1-rc.2","@deepseek-ai/dsh-timeout":"0.2.1-rc.2","@deepseek-ai/dsh-token-meter":"0.2.1-rc.2","@deepseek-ai/dsh-tool-ask-user":"0.2.1-rc.2","@deepseek-ai/dsh-tool-call-timeout-policy":"0.2.1-rc.2","@deepseek-ai/dsh-tool-fs":"0.2.1-rc.2","@deepseek-ai/dsh-tool-fs-search":"0.2.1-rc.2","@deepseek-ai/dsh-tool-goal":"0.2.1-rc.2","@deepseek-ai/dsh-tool-jobs":"0.2.1-rc.2","@deepseek-ai/dsh-tool-ralph":"0.2.1-rc.2","@deepseek-ai/dsh-tool-schedule":"0.2.1-rc.2","@deepseek-ai/dsh-tool-session-query":"0.2.1-rc.2","@deepseek-ai/dsh-tool-skill":"0.2.1-rc.2","@deepseek-ai/dsh-tool-subagent":"0.2.1-rc.2","@deepseek-ai/dsh-tool-subagent-control":"0.2.1-rc.2","@deepseek-ai/dsh-tool-present":"0.2.1-rc.2","@deepseek-ai/dsh-tool-todo":"0.2.1-rc.2","@deepseek-ai/dsh-tool-web":"0.2.1-rc.2","@deepseek-ai/dsh-tool-workflow":"0.2.1-rc.2","@deepseek-ai/dsh-tool-working-directory":"0.2.1-rc.2","@deepseek-ai/dsh-tools":"0.2.1-rc.2","@deepseek-ai/dsh-typert-protocol":"0.2.1-rc.2","@deepseek-ai/dsh-typert-registry":"0.2.1-rc.2","@deepseek-ai/dsh-user-approval":"0.2.1-rc.2","@deepseek-ai/dsh-user-questions":"0.2.1-rc.2","@deepseek-ai/dsh-util-values":"0.2.1-rc.2","@deepseek-ai/dsh-web":"0.2.1-rc.2","@deepseek-ai/dsh-web-deepseek-api":"0.2.1-rc.2","@deepseek-ai/dsh-web-fetch-http":"0.2.1-rc.2","@deepseek-ai/dsh-web-search-deepseek":"0.2.1-rc.2","@deepseek-ai/dsh-workflow":"0.2.1-rc.2","@deepseek-ai/dsh-working-directory":"0.2.1-rc.2","@deepseek-ai/dsh-workspace":"0.2.1-rc.2","@deepseek-ai/schemastery":"3.18.5","@mixmark-io/domino":"2.2.0","@modelcontextprotocol/sdk":"1.30.0",acorn:"8.18.0","fast-png":"8.0.0",fflate:"0.8.3","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 kS,pJe,hJe,vO=q(()=>{"use strict";dJe();kS=Y0e.version,pJe=Y0e.dshEdge.upstreamVersion,hJe=`npx dsh-edge@${kS.includes("-")?"next":"latest"} upgrade`});function Zun(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 edn(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 Jun)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(edn(i)){let s=Zun(i),o=s??i;for(let c of Yun)if(c.test(o))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`);if(s===void 0){for(let c of Xun)if(c.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function tdn(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}function rdn(e){return async(t,n)=>{let r=await Ib(t,n);if(r.body===null)return r;let i=0,s=r.body.pipeThrough(new TransformStream({transform(o,c){if(i+=o.byteLength,i>e){c.error(new Error(`MCP server response is larger than ${String(e)} bytes.`));return}c.enqueue(o)}}));return new Response(s,{status:r.status,statusText:r.statusText,headers:r.headers})}}async function X0e(e,t,n,r){Q1(e);let i=new lB(new URL(e),{requestInit:{headers:tdn(t),signal:n},fetch:r===void 0?Ib:rdn(r)}),s=new aB({name:"dsh-edge",version:kS},{capabilities:{},jsonSchemaValidator:ndn});return await s.connect(i),{client:s,close:a(async()=>{await s.close().catch(()=>{})},"close")}}async function mJe(e,t,n){let r=AbortSignal.timeout(ta.probeTimeoutMs),i;try{i=await X0e(t,n,r)}catch(c){throw new Error(km(c instanceof Error?c.message:String(c)))}let{client:s,close:o}=i;try{let c=[],l=new Set,u=new Set,d,p=s.getServerCapabilities?.()?.tools!==void 0;for(let g=0;p&&g<ta.maxCatalogPages;g++){let v=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let x of v.tools){if(c.length>=ta.maxToolsPerServer)break;let b=aJe(e,x.name);if(l.has(b))throw new Error(`Server listed tool "${x.name}" more than once`);l.add(b);let w=x.annotations?.readOnlyHint,k=cJe(x.outputSchema);c.push({name:x.name,publicName:b,description:x.description??"",inputSchema:x.inputSchema??{type:"object"},...k!==void 0?{outputSchema:k}:{},...w!==void 0?{annotations:{readOnlyHint:w}}:{}})}if(c.length>=ta.maxToolsPerServer||(d=v.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 h=s.getServerVersion?.(),m=s.getInstructions?.(),f=s.getServerCapabilities?.()?.resources!==void 0;return{tools:c,serverInfo:h?{name:h.name,version:h.version}:void 0,instructions:typeof m=="string"&&m.length>0?m.slice(0,ta.maxInstructionsLength):void 0,resources:f}}finally{await o()}}async function gB(e,t,n,r,i,s){let o=s??ta.callTimeoutMs,c=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),l;try{l=await X0e(e,r,c)}catch(u){throw new Error(km(u instanceof Error?u.message:String(u)))}try{let u=await l.client.callTool({name:t,arguments:n},void 0,{signal:c});return{content:u.content??[],structuredContent:u.structuredContent,isError:u.isError===!0}}catch(u){throw new Error(km(u instanceof Error?u.message:String(u)))}finally{await l.close()}}async function fJe(e,t,n,r,i){let s=i??ta.callTimeoutMs,o=r?AbortSignal.any([r,AbortSignal.timeout(s)]):AbortSignal.timeout(s),c;try{c=await X0e(e,n,o,ta.maxResourceResponseBytes)}catch(l){throw new Error(km(l instanceof Error?l.message:String(l)))}try{let{client:l}=c;if(t.method==="resources/read")return await l.readResource({uri:t.uri},{signal:o});let u=t.method==="resources/list"?"resources":"resourceTemplates",d=a(g=>t.method==="resources/list"?l.listResources(g===void 0?void 0:{cursor:g},{signal:o}):l.listResourceTemplates(g===void 0?void 0:{cursor:g},{signal:o}),"page");if(t.cursor!==void 0)return await d(t.cursor);let p=[],h=new Set,m=0,f;for(let g=0;g<ta.maxCatalogPages;g++){let v=await d(f),x=Array.isArray(v[u])?v[u]:[],b=new TextEncoder().encode(JSON.stringify(x)).byteLength;if(p.length>0&&m+b>ta.maxResourceResponseBytes)break;p.push(...x),m+=b;let w=typeof v.nextCursor=="string"?v.nextCursor:void 0;if(w===void 0){f=void 0;break}if(h.has(w))throw new Error(`Server repeated a ${t.method} continuation cursor`);h.add(w),f=w}return f===void 0?{[u]:p}:{[u]:p,nextCursor:f}}catch(l){throw new Error(km(l instanceof Error?l.message:String(l)))}finally{await c.close()}}var Jun,Yun,Xun,ndn,Ib,xO=q(()=>{"use strict";xQe();XQe();oJe();fB();mB();vO();Jun=[".internal",".local",".localhost"],Yun=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],Xun=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(Zun,"extractMappedIPv4");a(edn,"isIpAddress");a(Q1,"assertSafeUrl");a(tdn,"buildHeaders");ndn=new hB,Ib=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(rdn,"byteCappedFetch");a(X0e,"connectClient");a(mJe,"probe");a(gB,"callTool");a(fJe,"requestResources")});var vB={};Ut(vB,{buildAuthorizationUrl:()=>pdn,discoverEndpoints:()=>udn,exchangeCode:()=>hdn,isTokenExpired:()=>fdn,refreshToken:()=>mdn,registerClient:()=>ddn});function xJe(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 ldn(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 udn(e){let t=AbortSignal.timeout(yB),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 Ib(i.href,{signal:t});if(!s.ok)throw new Error(`PRM discovery failed: HTTP ${s.status}`);let c=(await s.json()).authorization_servers?.[0];if(typeof c!="string")throw new Error("No authorization server in PRM");let l=new URL(c),u=l.pathname==="/"?"/.well-known/oauth-authorization-server":`/.well-known/oauth-authorization-server${l.pathname}`,d=new URL(u,l.origin);Q1(d.href);let p=await Ib(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 ddn(e,t,n){let r=AbortSignal.timeout(yB);Q1(e);let i=await Ib(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 pdn(e,t,n,r,i){let s=xJe(32),o=xJe(64),c=await ldn(o),l=new URL(e.authorization);for(let[u,d]of Object.entries({response_type:"code",client_id:t.clientId,redirect_uri:n,state:s,code_challenge:c,code_challenge_method:"S256",resource:i}))l.searchParams.set(u,d);return{authorizationUrl:l.href,pendingFlow:{state:s,codeVerifier:o,redirectUri:n,serverName:r,serverUrl:i,stagedClient:t,createdAt:Date.now()}}}async function hdn(e,t,n,r,i,s){let o=AbortSignal.timeout(yB),c=new URLSearchParams({grant_type:"authorization_code",code:n,redirect_uri:i,client_id:t.clientId,code_verifier:r});s!==void 0&&c.set("resource",s),t.clientSecret!==void 0&&c.set("client_secret",t.clientSecret),Q1(e);let l=await Ib(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:c.toString(),signal:o});if(!l.ok)throw new Error(`Token exchange failed: HTTP ${l.status}`);return bJe(await l.json())}async function mdn(e,t,n,r){let i=AbortSignal.timeout(yB),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 Ib(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 bJe(await o.json())}function bJe(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 fdn(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var yB,xB=q(()=>{"use strict";xO();yB=1e4;a(xJe,"randomString");a(ldn,"sha256Base64Url");a(udn,"discoverEndpoints");a(ddn,"registerClient");a(pdn,"buildAuthorizationUrl");a(hdn,"exchangeCode");a(mdn,"refreshToken");a(bJe,"parseTokenResponse");a(fdn,"isTokenExpired")});var dr,IJe,OI=q(()=>{fr();Lr();dr=class extends ii{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},IJe=class extends Lt{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new dr("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function _O(e){return PB.test(e)}function OB(e){return e.invocation.modelInvocable}function NI(e){return e.invocation.userInvocable}function yye(e){let t=Zpn(e);return[`<skill_content name="${ehn(e.name)}">`,"<skill_resources>",...t,"</skill_resources>","","<skill_instructions>",e.content,"</skill_instructions>","</skill_content>"].join(`
|
|
168
168
|
`)}function Zpn(e){let t=e.resourceBase;if(t===void 0)return[`Resources for this skill are managed by provider "${MI(e.provider)}".`,"Load referenced resources only as needed."];switch(t.kind){case"directory":return[`Base directory for this skill: ${MI(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: ${MI(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: ${MI(t.description)}`,"Load referenced resources only as needed."];default:return qr(t,"SkillResourceBase.kind")}}function ehn(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<")}function MI(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function nhn(e,t){if(Array.isArray(e))return{candidates:e,complete:!0};if(e===null||typeof e!="object")throw JJe(t);let n=e;if(!Array.isArray(n.candidates)||typeof n.complete!="boolean")throw JJe(t);return n}function JJe(e){return new TypeError(`skill provider "${e}" list() must return an array or { candidates, complete } observation`)}function ihn(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:Xpn,locator:e,...e.path!==void 0?{path:e.path}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}function shn(e,t){if(typeof e.name!="string")throw new TypeError(`skill provider "${t}" returned a non-string skill name`);if(!PB.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(vye(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 ohn(e){if(!PB.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`);vye(e.invocation,`runtime skill "${e.name}"`)}function ahn(e){let t=e.name,n=e.description,r=e.whenToUse,i=e.invocation,s=e.source,o=e.provider,c=e.content,l=e.path;if(typeof t!="string")throw new TypeError("loaded skill name must be a string");if(!PB.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(vye(i,`loaded skill "${t}"`),r!==void 0&&typeof r!="string")throw new TypeError(`loaded skill "${t}" whenToUse must be a string`);if(typeof s!="string")throw new TypeError(`loaded skill "${t}" source must be a string`);if(typeof o!="string")throw new TypeError(`loaded skill "${t}" provider must be a string`);if(typeof c!="string")throw new TypeError(`loaded skill "${t}" content must be a string`);if(l!==void 0&&typeof l!="string")throw new TypeError(`loaded skill "${t}" path must be a string`)}function chn(e){let{name:t,description:n,whenToUse:r,invocation:i,source:s,provider:o,resourceBase:c}=e;return{name:t,...e.path===void 0?{}:{path:e.path},description:n,...r!==void 0?{whenToUse:r}:{},invocation:i,source:s,provider:o,...c!==void 0?{resourceBase:c}:{}}}function vye(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 lhn(e,t){return eYe(e.name,t.name)}function eYe(e,t){return e<t?-1:e>t?1:0}function uhn(e,t){return e.candidate.rank-t.candidate.rank||e.providerOrder-t.providerOrder||e.localOrder-t.localOrder}function dhn(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 YJe(e,t){return t===void 0?e:(SO(t),new Promise((n,r)=>{let i=a(()=>{t.removeEventListener("abort",s)},"cleanup"),s=a(()=>{i(),r(CB(t.reason))},"onAbort");t.addEventListener("abort",s,{once:!0}),e.then(o=>{i(),n(o)},o=>{i(),r(CB(o))})}))}function SO(e){if(e?.aborted===!0)throw CB(e.reason)}function CB(e){try{if(e instanceof Error)return e}catch{}return new Error(RB(e))}function RB(e){try{return String(e)}catch{return"[unrenderable thrown value]"}}var PB,QJe,Ypn,IB,Xpn,XJe,thn,ZJe,rhn,_S=q(()=>{fr();vs();zl();kn();PB=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,QJe=128,Ypn=2,IB="runtime",Xpn=250,XJe=600;a(_O,"isSkillName");a(OB,"isModelInvocable");a(NI,"isUserInvocable");a(yye,"renderSkillContent");a(Zpn,"renderResourceHint");a(ehn,"escapeAttr");a(MI,"escapeText");thn=class{static{a(this,"SkillLayer")}providers;runtime=new Map;constructor(e){this.providers=new sm(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}},ZJe=class extends Lt{static{a(this,"SkillRegistry")}static Config=j.object({collectCacheMaxEntries:j.number().default(QJe)});collectCacheMaxEntries;layers=new om(e=>new thn(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??QJe,dhn("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===IB)throw new Error(`"${IB}" is reserved for runtime skill registrations`);let o=this.nextProviderOrder;return this.nextProviderOrder+=1,this.layers.effect(this.ctx,c=>{let l=c.providers.insert(s,{provider:r,order:o});return n={layer:c,name:s},()=>{n=void 0,l(),t.abort(new Error(`skill provider "${s}" disposed`))}},{label:"skills.registerProvider()"})}catch(s){throw t.abort(s),s}}register(e){ohn(e);let t=Qc(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??IB};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=>chn(n.candidate)).sort(lhn),complete:t.cacheable}}async get(e,t={}){if(!_O(e))return;let n=await this.collect(t);SO(t.signal);let r=n.entries.get(e);if(r===void 0)return;let i=await YJe(r.provider.get(r.candidate,t),t.signal);if(i!==void 0){if(ahn(i),i.name!==r.candidate.name){this.invalidateEntry(r);return}return i}}async collect(e){SO(e.signal);let t=1;for(;;){let n=this.revision,r=this.collectCacheKey(e.cwd,V3(e.scope),n),i=this.collectCache.get(r);if(i!==void 0)return{entries:i,cacheable:!0};let s=await this.collectFresh(e);if(SO(e.signal),n!==this.revision){if(t<Ypn){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(uhn);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){SO(t.signal);let n=[],r=!0,i=0;for(let s of[...e.runtime.values()].sort((o,c)=>eYe(o.name,c.name)))n.push({candidate:ihn(s),provider:rhn,providerOrder:-1,localOrder:i,layer:e}),i+=1;for(let{provider:s,order:o}of[...e.providers.values()]){let c=0,l;try{l=await YJe(s.list(t),t.signal)}catch(d){if(t.signal?.aborted===!0)throw CB(t.signal.reason);r=!1,this.ctx.logger.warn(`skill provider "${s.name}" skipped: ${RB(d)}`)}if(l===void 0)continue;let u=nhn(l,s.name);u.complete||(r=!1);for(let d of u.candidates)shn(d,s.name),n.push({candidate:d,provider:s,providerOrder:o,localOrder:c,layer:e}),c+=1}return{entries:n,cacheable:r}}invalidateCache(){this.revision+=1,this.collectCache.clear(),this.notifyChange()}invalidateEntry(e){e.layer.providers.get(e.provider.name)?.provider===e.provider&&this.invalidateCache()}scopeId(e){let t=this.scopeIds.get(e);return t===void 0&&(t=this.nextScopeId,this.nextScopeId+=1,this.scopeIds.set(e,t)),t}collectCacheKey(e,t,n){return JSON.stringify({cwd:e,scopes:t.map(r=>this.scopeId(r)),revision:n})}notifyChange(){for(let e of this.ctx.events.dispatch("emit",["skills/change"]))try{let t=e();Promise.resolve(t).catch(n=>{this.ctx.logger.warn(`skills/change listener rejected: ${RB(n)}`)})}catch(t){this.ctx.logger.warn(`skills/change listener threw: ${RB(t)}`)}}};a(nhn,"normalizeProviderObservation");a(JJe,"invalidProviderObservation");rhn={name:IB,list(){return Promise.resolve([])},get(e){return Promise.resolve(e.locator)}};a(ihn,"runtimeCandidate");a(shn,"validateCandidate");a(ohn,"validateRuntimeSkill");a(ahn,"validateDefinition");a(chn,"toSummary");a(vye,"validateInvocation");a(lhn,"compareSkillSummary");a(eYe,"compareCodePoints");a(uhn,"compareIndexedCandidates");a(dhn,"assertPositiveInteger");a(YJe,"waitWithAbort");a(SO,"throwIfAborted");a(CB,"toError");a(RB,"errorMessage")});var Sm,WI=q(()=>{Sm=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 ev,TZe,E1e=q(()=>{fr();ev=class extends Error{static{a(this,"DirectoryPickerError")}code;path;constructor(e,t,n){super(n),this.code=e,this.path=t,this.name="DirectoryPickerError"}},TZe=class extends Lt{static{a(this,"DirectoryPicker")}constructor(e){super(e,"directoryPicker")}}});var KG,Pve,ja,fg=q(()=>{KG=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()}},Pve=class{static{a(this,"EventStream")}queue=new KG;waiting=new KG;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}},ja=class extends Pve{static{a(this,"AssistantMessageEventStream")}#e=Date.now();#n=performance.now();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")})}push(t){t.type==="done"?this.#r(t.message):t.type==="error"&&this.#r(t.error),super.push(t)}end(t){t!==void 0&&this.#r(t),super.end(t)}#r(t){this.done||t.durationMs!==void 0||t.timestamp<this.#e||(t.durationMs=Math.max(0,Math.round(performance.now()-this.#n)))}}});function Ebn(e,t,n){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:n}}function Tbn(e){return typeof e.result=="function"}async function Abn(e,t){for await(let n of t)e.push(n);e.end(Tbn(t)?await t.result():void 0)}function Em(e,t){let n=Date.now(),r=new ja;return t().then(i=>Abn(r,i)).catch(i=>{let s=Ebn(e,i,n);r.push({type:"error",reason:"error",error:s}),r.end(s)}),r}function Pc(e,t){let n={stream:a((r,i,s)=>Em(r,async()=>(await e()).stream(r,i,s)),"stream"),streamSimple:a((r,i,s)=>Em(r,async()=>(await e()).streamSimple(r,i,s)),"streamSimple")};return t?.fetchDeferred&&(n.fetchDeferred=(r,i,s)=>Em(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 kh=q(()=>{fg();a(Ebn,"createSetupErrorMessage");a(Tbn,"hasResult");a(Abn,"forwardStream");a(Em,"lazyStream");a(Pc,"lazyApi")});function Rbn(){return globalThis.process?.env}function Qnt(){return{async env(e){let t=Rbn()?.[e];return typeof t=="string"&&t.trim().length>0?t:void 0},async fileExists(e){try{let t=await Knt("node:fs/promises"),n=e;return n.startsWith("~")&&(n=(await Knt("node:os")).homedir()+n.slice(1)),await t.access(n),!0}catch{return!1}}}}var Ibn,Knt,Jnt=q(()=>{Ibn=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},Knt=a(e=>import(Ibn(e)),"importNodeModule");a(Rbn,"getProcessEnv");a(Qnt,"defaultProviderAuthContext")});function Ynt(e){if(e.reason!==void 0)return e.reason;let t=new Error("The operation was aborted");return t.name="AbortError",t}function Tm(e){return e??new AbortController().signal}function Am(e,t){return t.aborted?(e.catch(()=>{}),Promise.reject(Ynt(t))):new Promise((n,r)=>{let i=!1,s=a(()=>t.removeEventListener("abort",o),"cleanup"),o=a(()=>{i||(i=!0,s(),r(Ynt(t)))},"onAbort");t.addEventListener("abort",o,{once:!0}),e.then(c=>{i||(i=!0,s(),n(c))},c=>{i||(i=!0,s(),r(c))}),t.aborted&&o()})}var QG=q(()=>{a(Ynt,"abortReason");a(Tm,"operationSignal");a(Am,"raceWithAbortSignal")});var JG,Xnt=q(()=>{QG();JG=class{static{a(this,"InMemoryCredentialStore")}credentials=new Map;chains=new Map;enqueue(t,n,r){let i=Tm(r?.signal),s=this.chains.get(t)??Promise.resolve(),o=(async()=>(await s.catch(()=>{}),i.throwIfAborted(),n()))(),c=o.catch(()=>{});return this.chains.set(t,c),c.then(()=>{this.chains.get(t)===c&&this.chains.delete(t)}),Am(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 zb(e){return e instanceof Error?e.message||e.name:typeof e=="string"?e:String(e)}function Cbn(e){if(!(e instanceof Error))return{name:"ThrownValue",message:zb(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 YG(e,t,n){return{type:e,timestamp:Date.now(),error:Cbn(t),details:n}}function Hb(e,t){e.diagnostics=[...e.diagnostics??[],t]}var dM=q(()=>{a(zb,"formatThrownValue");a(Cbn,"extractDiagnosticError");a(YG,"createAssistantMessageDiagnostic");a(Hb,"appendAssistantMessageDiagnostic")});function Pbn(e,t){if(t==null)return e;let n=zb(t).trim();return!n||e.includes(n)?e:`${e}: ${n}`}var is,XG=q(()=>{dM();is=class extends Error{static{a(this,"ModelsError")}code;constructor(t,n,r){super(Pbn(n,r?.cause),r),this.name="ModelsError",this.code=t}};a(Pbn,"withCauseDetail")});function Mve(e,t,n,r){let i=Tm(r?.signal);return Am(Obn(e,t,n,r,i),i)}async function Obn(e,t,n,r,i){i.throwIfAborted();let s=r?.env?Mbn(n,r.env):n;if(r?.apiKey!==void 0&&e.auth.apiKey)return Ove(s,e.auth.apiKey,e.id,{type:"api_key",key:r.apiKey,env:r.env},i);let o=await $bn(t,e.id,i);if(o){if(o.type==="oauth"&&e.auth.oauth)return Dbn(t,e.id,e.auth.oauth,o,i,r?.minOAuthValidityMs);if(o.type==="api_key"&&e.auth.apiKey){let c=r?.env?{...o,env:{...o.env,...r.env}}:o;return Ove(s,e.auth.apiKey,e.id,c,i)}return}return e.auth.apiKey?Ove(s,e.auth.apiKey,e.id,void 0,i):void 0}function Mbn(e,t){return{env:a(async n=>t[n]||await e.env(n),"env"),fileExists:a(n=>e.fileExists(n),"fileExists")}}async function Nve(e,t,n,r,i){let s,o=new AbortController,c=a(()=>o.abort(i.reason),"cancelLockWait");i.addEventListener("abort",c,{once:!0}),i.aborted&&c();try{s=await e.modify(t,async l=>{if(i.removeEventListener("abort",c),i.throwIfAborted(),l?.type==="oauth"&&r(l))try{return await n.refresh(l,AbortSignal.timeout(Lbn))}catch(u){throw new is("oauth",`OAuth refresh failed for ${t}`,{cause:u})}},{signal:o.signal})}catch(l){throw l instanceof is?l:(i.throwIfAborted(),new is("auth",`Credential store modify failed for ${t}`,{cause:l}))}finally{i.removeEventListener("abort",c)}return s?.type==="oauth"?s:void 0}async function Dbn(e,t,n,r,i,s){let o=Math.max(Nbn,s??0),c=a(u=>Date.now()+o>=u.expires,"expiresSoon"),l=r;if(c(l)){let u=await Nve(e,t,n,c,i);if(!u)return;if(l=u,s!==void 0&&c(l))throw new is("oauth",`OAuth refresh returned a token that expires too soon for ${t}`)}try{return{auth:await n.toAuth(l),source:"OAuth"}}catch(u){throw new is("oauth",`OAuth auth derivation failed for ${t}`,{cause:u})}}async function Ove(e,t,n,r,i){try{return await t.resolve({ctx:e,credential:r,signal:i})}catch(s){throw new is("auth",`API key auth failed for provider ${n}`,{cause:s})}}async function $bn(e,t,n){try{return await e.read(t,{signal:n})}catch(r){throw new is("auth",`Credential store read failed for ${t}`,{cause:r})}}var Nbn,Lbn,Znt=q(()=>{QG();XG();XG();a(Mve,"resolveProviderAuth");a(Obn,"resolveProviderAuthWithSignal");a(Mbn,"overlayEnvAuthContext");Nbn=300*1e3,Lbn=15e3;a(Nve,"refreshStoredOAuthCredential");a(Dbn,"resolveStoredOAuth");a(Ove,"resolveApiKey");a($bn,"readCredential")});var ZG,ert=q(()=>{ZG=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 cR(e){return e.type??"chat"}function gg(e,t){return cR(e)===t}function trt(e){if(!gg(e,"chat"))throw new is("provider",`Model ${e.provider}/${e.id} is not a chat model`)}function nrt(e){if(!gg(e,"image"))throw new is("provider",`Model ${e.provider}/${e.id} is not an image model`)}function rrt(e){if(!gg(e,"classifier"))throw new is("provider",`Model ${e.provider}/${e.id} is not a classifier model`)}function irt(e,t){if(t.images?.length&&!e.input.includes("image"))throw new is("provider",`Model ${e.provider}/${e.id} does not accept image input`)}function Lve(e,t,n=!1){return{api:e.api,provider:e.provider,model:e.id,output:[],stopReason:n?"aborted":"error",errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}function Dve(e,t,n=!1){return{api:e.api,provider:e.provider,model:e.id,answers:{},stopReason:n?"aborted":"error",errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}var $ve=q(()=>{XG();a(cR,"getModelType");a(gg,"isModelType");a(trt,"assertChatModel");a(nrt,"assertImageModel");a(rrt,"assertClassifierModel");a(irt,"assertClassifierInputSupported");a(Lve,"imageErrorResult");a(Dve,"classifierErrorResult")});function eV(e,t=`
|
|
169
169
|
`){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join(t)}function ru(e){let t=[eV(e.content)];for(let n of Object.values(e.sections??{}))n!==null&&t.push(n);return t.filter(n=>n.length>0).join(`
|
|
170
170
|
|
|
@@ -8517,7 +8517,7 @@ The web request used endpoint ${JSON.stringify(e)}. Search endpoint configuratio
|
|
|
8517
8517
|
.error { padding: .75rem; border-radius: .5rem; background: #461d2b; color: #ffd6df; }
|
|
8518
8518
|
.hint { margin: 1.5rem 0 0; font-size: .875rem; }
|
|
8519
8519
|
code { padding: .1rem .3rem; border-radius: .3rem; background: #0c1222; color: #edf2ff; }
|
|
8520
|
-
`}a(b6t,"pageStyles");vO();var J3e="enabled",Y3e=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")}),MD=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")}),X3e=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===J3e?"available":"needs-binding","probe")}),G1r=Object.freeze([X3e,MD,Y3e]);function Z3e(e,t=G1r){return t.filter(n=>n.probe(e)==="available")}a(Z3e,"availableEdgeRuntimeProviders");function e8e(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(e8e,"resolveEdgeRuntimeSelection");function yte(e){let t=Z3e(e),{bash:n,container:r}=e8e(t);return t.find(i=>i.id===(r??n)).shell}a(yte,"resolveEdgeRuntimeShell");function V1r(){return"dsh-edge@0.29.0-alpha.1/direct"}a(V1r,"resolveEdgeDeploymentId");function $E(e){return{baseURL:oAe(e.DEEPSEEK_BASE_URL),maxTokens:lAe(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:tE(e.DEEPSEEK_MODEL),reasoningEffort:aAe(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:zL(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:cAe(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:Nk(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a($E,"resolveEdgeDeploymentConfig");function K1r(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(K1r,"edgeDeploymentApiKeyConfigured");function Q1r(e){let t=oAe(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(Q1r,"projectedEdgeBaseURL");function t8e(e,t){return{shell:yte(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:V1r(),apiKeyConfigured:K1r(e),baseURL:Q1r(e.DEEPSEEK_BASE_URL),maxTokens:lAe(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:tE(e.DEEPSEEK_MODEL),reasoningEffort:aAe(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:zL(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:cAe(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:Nk(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(t8e,"resolveEdgeDeploymentProfile");function vte(e){$E(e);let t=t8e(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:kS,upstreamVersion:pJe,status:"ready"}}a(vte,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as s3r}from"node:async_hooks";import{RpcTarget as J1r}from"cloudflare:workers";function Y1r(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(Y1r,"startHeartbeat");async function X1r(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(X1r,"probeComputerdHealth");var Z1r="computer.internal",evr="/health",n8e="/api",tvr=8080,nvr=3e4,rvr=2e4,ivr=1,svr=2e3,ovr=250,avr=2e3;function cvr(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(cvr,"bearerMatches");var bte=class{static{a(this,"CloudflareContainerBackend")}type="cloudflare-container";id;#e;#n;#r;#t;#i;#s;#a;#u;constructor(e){this.id=e.id??"container-shell",this.#n=e.egress??{mode:"none"},this.#r=this.#n.mode==="http-gateway"?crypto.randomUUID():void 0,this.#e={container:e.container,workspace:e.workspace,containerEnv:e.containerEnv,egressHost:e.egressHost??Z1r,containerPort:e.containerPort??tvr,connectTimeoutMs:e.connectTimeoutMs??nvr,heartbeatIntervalMs:e.heartbeatIntervalMs??rvr,restartAttempts:e.restartAttempts??ivr,healthProbeTimeoutMs:e.healthProbeTimeoutMs??svr,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??ovr,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??avr}}async connect(){if(this.#u)return this.#u;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.#n.mode==="direct"}))}catch(p){throw new ad(this.#h("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.#n.mode==="http-gateway"&&this.#r!==void 0&&await t.interceptAllOutboundHttp(this.#e.workspace,this.#r)}catch(p){throw new ad(this.#h("egress",{attempt:1,maxAttempts:this.#e.restartAttempts+1,restarts:0,lastError:p,priorExit:n}),{cause:p})}this.#t=s,this.#c(),i=await this.#p(t,r,e,n,i),await this.#l(t,e),await this.#f(t,e,s);let o=await this.#d(e),c=Vre(o),l,u=new Promise(p=>{let h=!1,m=a(()=>{h||(h=!0,l?.(),p(),this.#u=void 0)},"onClose");o.addEventListener("close",m,{once:!0}),o.addEventListener("error",m,{once:!0}),c.onRpcBroken(m)});this.#e.heartbeatIntervalMs>0&&(l=Y1r({intervalMs:this.#e.heartbeatIntervalMs,ping:a(()=>c.sync.watermarks(),"ping"),onFailure:a(()=>{try{o.close()}catch{}},"onFailure")}));let d={rpc:c,runtimeId:i,closed:u,close:a(async()=>{l?.();try{c[Symbol.dispose]?.()}catch{}try{o.close()}catch{}this.#u=void 0},"close")};return this.#u=d,d}async handleFetch(e){if(this.#n.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(y3),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(H$),i.delete(y3);let c=new Request(e,{headers:i});return this.#n.gateway.fetch(new Request(o,c))}if(new URL(e.url).pathname!==n8e)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${n8e} requires a websocket upgrade`,{status:400});if(!cvr(e.headers.get("authorization"),this.#t))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})}#c(){this.#i=new Promise((e,t)=>{this.#s=e,this.#a=t}),this.#i.catch(()=>{})}#o(){this.#i=void 0,this.#s=void 0,this.#a=void 0}async#p(e,t,n,r,i){let s=this.#e.restartAttempts+1,o=Math.max(0,n-Date.now()),c=Math.max(250,Math.floor(o/s)),l=0,u=0,d,p=i;for(;l<s;){l++;let h=Math.min(n,Date.now()+c);if(await this.#m(e,h).then(()=>!0,m=>(d=m,!1)))return p;if(l<s)try{({runtimeId:p}=await e.restart({env:t,enableInternet:this.#n.mode==="direct"})),u++}catch(m){throw this.#a?.(m),this.#o(),new ad(this.#h("restart",{attempt:l,maxAttempts:s,restarts:u,lastError:m}),{cause:m})}}throw this.#a?.(new Error("computerd never became healthy")),this.#o(),new ad(this.#h("health",{attempt:l,maxAttempts:s,restarts:u,lastError:d,priorExit:r}),d instanceof Error?{cause:d}:void 0)}async#m(e,t){let n=this.#e.healthRetryInitialDelayMs,r;for(;Date.now()<t;)try{await X1r(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 lvr(Math.min(n,s)),n=Math.min(n*2,this.#e.healthRetryMaxDelayMs)}throw r??new Error("computerd health probe timed out")}#h(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=${w6t(t.lastError)}`}async#l(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 ad(`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#f(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:evr,api:n8e,healthTimeoutMs:r})})}catch(s){throw this.#a?.(s),this.#o(),new ad(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${w6t(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 ad(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect returned ${i.status}: ${s}`,{cause:o})}}async#d(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 ad(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#o()}}};function lvr(e){return new Promise(t=>setTimeout(t,e))}a(lvr,"sleep");function w6t(e){return e instanceof Error?e.message:String(e)}a(w6t,"describeError");var k6t="computer:container-client-secret",uvr=16;function dvr(){let e=crypto.getRandomValues(new Uint8Array(uvr));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(dvr,"generate");var pvr=class{static{a(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(k6t);if(typeof e=="string"&&e.length>0)return e;let t=dvr();return await this.storage.put(k6t,t),t}},S6t="computer:container-launch-record";async function _6t(e){return{enableInternet:e.enableInternet,envDigest:await mvr(e.env)}}a(_6t,"launchRecordFor");function hvr(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}a(hvr,"sameLaunch");async function mvr(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(mvr,"digestEnv");var fvr=class{static{a(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(S6t)??null}async set(e){await this.storage.put(S6t,e)}},E6t=new WeakMap;function s8e(e){let t=E6t.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},E6t.set(e,t)),t}a(s8e,"getContainerLifecycle");function xte(e){return s8e(e).exit}a(xte,"containerExitInfo");function T6t(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}a(T6t,"formatExitReason");function A6t(e,t,n){let r=s8e(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>I6t(r,i,void 0,n),s=>I6t(r,i,s,n))}a(A6t,"installContainerMonitor");async function r8e(e,t){let n=s8e(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}a(r8e,"destroyContainerExpectingExit");async function I6t(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=T6t(n),o=Date.now();e.exit={reason:s,exitedAt:o},i?console.info({message:"workspace.container.exited",reason:s,exitedAt:o,expected:!0}):console.warn({message:"workspace.container.exited",reason:s,exitedAt:o,expected:!1});try{await r?.()}catch(c){console.error({message:"workspace.container.exit_cleanup_failed",reason:T6t(c),exitedAt:Date.now()})}}a(I6t,"recordExit");var i8e="computer:container-runtime-identity",gvr=class{static{a(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(i8e)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(i8e,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(i8e)}},yvr=class extends J1r{static{a(this,"WorkspaceContainerAPI")}#e;#n;#r;#t;#i;constructor(e){if(super(),!e.container)throw new Error("WorkspaceContainerAPI: DO is not container-enabled (check wrangler.jsonc)");this.#e=e.container,this.#n=e,this.#r=new gvr(e.storage),this.#t=new pvr(e.storage),this.#i=new fvr(e.storage)}async start(e){let t=xte(this.#n),n=await this.#t.ensure(),r=await _6t(e);if(t!==null){try{await r8e(this.#n,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||!hvr(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 r8e(this.#n,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return A6t(this.#n,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await r8e(this.#n,this.#e)}catch{}let t=await this.#t.ensure();return this.#s(e,t,await _6t(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),A6t(this.#n,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:xte(this.#n)}}async exitInfo(){return xte(this.#n)}async interceptAllOutboundHttp(e,t){let n=this.#n.exports.WorkspaceProxy({props:{...e,egressToken:t}});await Promise.all([this.#e.interceptAllOutboundHttp(n),this.#e.interceptOutboundHttps("*",n)])}async interceptOutboundHttp(e,t){let n=this.#n.exports;await this.#e.interceptOutboundHttp(e,n.WorkspaceProxy({props:t}))}fetchPort(e,t,n){let r=xte(this.#n);if(r!==null)throw new ad(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function R6t(e){class t extends e{static{a(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new yvr(this.ctx)}}return t}a(R6t,"withWorkspaceContainer");var vvr={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function P6t(e,t){let n=t.indexOf("."),r=t.indexOf("/"),i=n>=0?n:r;if(i<0)return;let s=t.slice(0,i),o=t.slice(i+1),c=vvr[s]??s,l=e[c];if(l===void 0)return;let u=l[o];return typeof u=="function"?u:void 0}a(P6t,"resolve");function xvr(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}a(xvr,"errorResponse");async function o8e(e,t,n,r,i){let s=P6t(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}a(o8e,"callEdgeApi");async function O6t(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(P6t(e,i)===void 0)return new Response("not found",{status:404});let s;try{s=await t.json()}catch{return new Response("body is not JSON",{status:400})}let o=typeof s.rpcId=="string"?s.rpcId:"invalid-request",c=s.payload??{};try{let l=await o8e(e,i,o,c,t.signal);return l===void 0?new Response("not found",{status:404}):Response.json({type:"server-response",rpcId:l.rpcId,result:l.result})}catch(l){return xvr(o,{code:"gateway/internal",message:String(l),details:{}})}}a(O6t,"dispatchEdgeApi");Lr();ro();j1();import{DurableObject as o3r}from"cloudflare:workers";var wte=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 bvr(this.stopping,t);continue}await new Promise((r,i)=>{let s=a(()=>{t?.removeEventListener("abort",o),r()},"wake"),o=a(()=>{let c=this.waiters.indexOf(s);c!==-1&&this.waiters.splice(c,1),i(t.reason)},"abort");this.waiters.push(s),t?.addEventListener("abort",o,{once:!0})})}return t?.aborted===!0&&(this.waiters.shift()?.(),t.throwIfAborted()),{release:this.begin(),queuedMs:this.now()-n}}begin(){this.inFlight+=1,this.lastActivity=this.now();let t=!1;return()=>{t||(t=!0,this.inFlight-=1,this.lastActivity=this.now(),this.waiters.shift()?.())}}async stopIfIdle(t){return this.idle()?await this.stop(t):"busy"}async stopNow(t){return this.inFlight===0?await this.stop(t):"busy"}snapshot(){return{runningCommands:this.inFlight,lastActivityAt:this.lastActivity??null}}async stop(t){if(this.stopping!==void 0)return"busy";let n="stopped",r=t().catch(i=>{n="failed",this.lastActivity=this.now(),console.error("dsh-edge container stop failed.",i)});this.stopping=r;try{await r}finally{this.stopping=void 0}return n}deadline(){return this.inFlight>0?this.now()+this.sleepAfterMs():this.lastActivity===void 0?this.now():this.lastActivity+this.sleepAfterMs()}idle(){return this.inFlight===0&&(this.lastActivity===void 0||this.now()>=this.lastActivity+this.sleepAfterMs())}};function bvr(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(bvr,"untilAborted");import{WorkerEntrypoint as Eds}from"cloudflare:workers";var mT=pl(M6t());import{gunzipSync as Ebr}from"node:zlib";var ND=class{static{a(this,"Diff")}diff(t,n,r={}){let i;typeof r=="function"?(i=r,r={}):"callback"in r&&(i=r.callback);let s=this.castInput(t,r),o=this.castInput(n,r),c=this.removeEmpty(this.tokenize(s,r)),l=this.removeEmpty(this.tokenize(o,r));return this.diffWithOptionsObj(c,l,r,i)}diffWithOptionsObj(t,n,r,i){var s;let o=a(b=>{if(b=this.postProcess(b,r),i){setTimeout(function(){i(b)},0);return}else return b},"done"),c=n.length,l=t.length,u=1,d=c+l;r.maxEditLength!=null&&(d=Math.min(d,r.maxEditLength));let p=(s=r.timeout)!==null&&s!==void 0?s:1/0,h=Date.now()+p,m=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(m[0],n,t,0,r);if(m[0].oldPos+1>=l&&f+1>=c)return o(this.buildValues(m[0].lastComponent,n,t));let g=-1/0,v=1/0,x=a(()=>{for(let b=Math.max(g,-u);b<=Math.min(v,u);b+=2){let w,k=m[b-1],E=m[b+1];k&&(m[b-1]=void 0);let A=!1;if(E){let O=E.oldPos-b;A=E&&0<=O&&O<c}let I=k&&k.oldPos+1<l;if(!A&&!I){m[b]=void 0;continue}if(!I||A&&k.oldPos<E.oldPos?w=this.addToPath(E,!0,!1,0,r):w=this.addToPath(k,!1,!0,1,r),f=this.extractCommon(w,n,t,b,r),w.oldPos+1>=l&&f+1>=c)return o(this.buildValues(w.lastComponent,n,t))||!0;m[b]=w,w.oldPos+1>=l&&(v=Math.min(v,b-1)),f+1>=c&&(g=Math.max(g,b+1))}u++},"execEditLength");if(i)a(function b(){setTimeout(function(){if(u>d||Date.now()>h)return i(void 0);x()||b()},0)},"exec")();else for(;u<=d&&Date.now()<=h;){let b=x();if(b)return b}}addToPath(t,n,r,i,s){let o=t.lastComponent;return o&&!s.oneChangePerToken&&o.added===n&&o.removed===r?{oldPos:t.oldPos+i,lastComponent:{count:o.count+1,added:n,removed:r,previousComponent:o.previousComponent}}:{oldPos:t.oldPos+i,lastComponent:{count:1,added:n,removed:r,previousComponent:o}}}extractCommon(t,n,r,i,s){let o=n.length,c=r.length,l=t.oldPos,u=l-i,d=0;for(;u+1<o&&l+1<c&&this.equals(r[l+1],n[u+1],s);)u++,l++,d++,s.oneChangePerToken&&(t.lastComponent={count:1,previousComponent:t.lastComponent,added:!1,removed:!1});return d&&!s.oneChangePerToken&&(t.lastComponent={count:d,previousComponent:t.lastComponent,added:!1,removed:!1}),t.oldPos=l,u}equals(t,n,r){return r.comparator?r.comparator(t,n):t===n||!!r.ignoreCase&&t.toLowerCase()===n.toLowerCase()}removeEmpty(t){let n=[];for(let r=0;r<t.length;r++)t[r]&&n.push(t[r]);return n}castInput(t,n){return t}tokenize(t,n){return Array.from(t)}join(t){return t.join("")}postProcess(t,n){return t}get useLongestToken(){return!1}buildValues(t,n,r){let i=[],s;for(;t;)i.push(t),s=t.previousComponent,delete t.previousComponent,t=s;i.reverse();let o=i.length,c=0,l=0,u=0;for(;c<o;c++){let d=i[c];if(d.removed)d.value=this.join(r.slice(u,u+d.count)),u+=d.count;else{if(!d.added&&this.useLongestToken){let p=n.slice(l,l+d.count);p=p.map(function(h,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(l,l+d.count));l+=d.count,d.added||(u+=d.count)}}return i}};var a8e=class extends ND{static{a(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=kvr}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
|
|
8520
|
+
`}a(b6t,"pageStyles");vO();var J3e="enabled",Y3e=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")}),MD=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")}),X3e=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===J3e?"available":"needs-binding","probe")}),G1r=Object.freeze([X3e,MD,Y3e]);function Z3e(e,t=G1r){return t.filter(n=>n.probe(e)==="available")}a(Z3e,"availableEdgeRuntimeProviders");function e8e(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(e8e,"resolveEdgeRuntimeSelection");function yte(e){let t=Z3e(e),{bash:n,container:r}=e8e(t);return t.find(i=>i.id===(r??n)).shell}a(yte,"resolveEdgeRuntimeShell");function V1r(){return"dsh-edge@0.29.0/direct"}a(V1r,"resolveEdgeDeploymentId");function $E(e){return{baseURL:oAe(e.DEEPSEEK_BASE_URL),maxTokens:lAe(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:tE(e.DEEPSEEK_MODEL),reasoningEffort:aAe(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:zL(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:cAe(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:Nk(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a($E,"resolveEdgeDeploymentConfig");function K1r(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(K1r,"edgeDeploymentApiKeyConfigured");function Q1r(e){let t=oAe(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(Q1r,"projectedEdgeBaseURL");function t8e(e,t){return{shell:yte(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:V1r(),apiKeyConfigured:K1r(e),baseURL:Q1r(e.DEEPSEEK_BASE_URL),maxTokens:lAe(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:tE(e.DEEPSEEK_MODEL),reasoningEffort:aAe(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:zL(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:cAe(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:Nk(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(t8e,"resolveEdgeDeploymentProfile");function vte(e){$E(e);let t=t8e(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:kS,upstreamVersion:pJe,status:"ready"}}a(vte,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as s3r}from"node:async_hooks";import{RpcTarget as J1r}from"cloudflare:workers";function Y1r(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(Y1r,"startHeartbeat");async function X1r(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(X1r,"probeComputerdHealth");var Z1r="computer.internal",evr="/health",n8e="/api",tvr=8080,nvr=3e4,rvr=2e4,ivr=1,svr=2e3,ovr=250,avr=2e3;function cvr(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(cvr,"bearerMatches");var bte=class{static{a(this,"CloudflareContainerBackend")}type="cloudflare-container";id;#e;#n;#r;#t;#i;#s;#a;#u;constructor(e){this.id=e.id??"container-shell",this.#n=e.egress??{mode:"none"},this.#r=this.#n.mode==="http-gateway"?crypto.randomUUID():void 0,this.#e={container:e.container,workspace:e.workspace,containerEnv:e.containerEnv,egressHost:e.egressHost??Z1r,containerPort:e.containerPort??tvr,connectTimeoutMs:e.connectTimeoutMs??nvr,heartbeatIntervalMs:e.heartbeatIntervalMs??rvr,restartAttempts:e.restartAttempts??ivr,healthProbeTimeoutMs:e.healthProbeTimeoutMs??svr,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??ovr,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??avr}}async connect(){if(this.#u)return this.#u;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.#n.mode==="direct"}))}catch(p){throw new ad(this.#h("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.#n.mode==="http-gateway"&&this.#r!==void 0&&await t.interceptAllOutboundHttp(this.#e.workspace,this.#r)}catch(p){throw new ad(this.#h("egress",{attempt:1,maxAttempts:this.#e.restartAttempts+1,restarts:0,lastError:p,priorExit:n}),{cause:p})}this.#t=s,this.#c(),i=await this.#p(t,r,e,n,i),await this.#l(t,e),await this.#f(t,e,s);let o=await this.#d(e),c=Vre(o),l,u=new Promise(p=>{let h=!1,m=a(()=>{h||(h=!0,l?.(),p(),this.#u=void 0)},"onClose");o.addEventListener("close",m,{once:!0}),o.addEventListener("error",m,{once:!0}),c.onRpcBroken(m)});this.#e.heartbeatIntervalMs>0&&(l=Y1r({intervalMs:this.#e.heartbeatIntervalMs,ping:a(()=>c.sync.watermarks(),"ping"),onFailure:a(()=>{try{o.close()}catch{}},"onFailure")}));let d={rpc:c,runtimeId:i,closed:u,close:a(async()=>{l?.();try{c[Symbol.dispose]?.()}catch{}try{o.close()}catch{}this.#u=void 0},"close")};return this.#u=d,d}async handleFetch(e){if(this.#n.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(y3),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(H$),i.delete(y3);let c=new Request(e,{headers:i});return this.#n.gateway.fetch(new Request(o,c))}if(new URL(e.url).pathname!==n8e)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${n8e} requires a websocket upgrade`,{status:400});if(!cvr(e.headers.get("authorization"),this.#t))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})}#c(){this.#i=new Promise((e,t)=>{this.#s=e,this.#a=t}),this.#i.catch(()=>{})}#o(){this.#i=void 0,this.#s=void 0,this.#a=void 0}async#p(e,t,n,r,i){let s=this.#e.restartAttempts+1,o=Math.max(0,n-Date.now()),c=Math.max(250,Math.floor(o/s)),l=0,u=0,d,p=i;for(;l<s;){l++;let h=Math.min(n,Date.now()+c);if(await this.#m(e,h).then(()=>!0,m=>(d=m,!1)))return p;if(l<s)try{({runtimeId:p}=await e.restart({env:t,enableInternet:this.#n.mode==="direct"})),u++}catch(m){throw this.#a?.(m),this.#o(),new ad(this.#h("restart",{attempt:l,maxAttempts:s,restarts:u,lastError:m}),{cause:m})}}throw this.#a?.(new Error("computerd never became healthy")),this.#o(),new ad(this.#h("health",{attempt:l,maxAttempts:s,restarts:u,lastError:d,priorExit:r}),d instanceof Error?{cause:d}:void 0)}async#m(e,t){let n=this.#e.healthRetryInitialDelayMs,r;for(;Date.now()<t;)try{await X1r(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 lvr(Math.min(n,s)),n=Math.min(n*2,this.#e.healthRetryMaxDelayMs)}throw r??new Error("computerd health probe timed out")}#h(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=${w6t(t.lastError)}`}async#l(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 ad(`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#f(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:evr,api:n8e,healthTimeoutMs:r})})}catch(s){throw this.#a?.(s),this.#o(),new ad(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${w6t(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 ad(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect returned ${i.status}: ${s}`,{cause:o})}}async#d(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 ad(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#o()}}};function lvr(e){return new Promise(t=>setTimeout(t,e))}a(lvr,"sleep");function w6t(e){return e instanceof Error?e.message:String(e)}a(w6t,"describeError");var k6t="computer:container-client-secret",uvr=16;function dvr(){let e=crypto.getRandomValues(new Uint8Array(uvr));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(dvr,"generate");var pvr=class{static{a(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(k6t);if(typeof e=="string"&&e.length>0)return e;let t=dvr();return await this.storage.put(k6t,t),t}},S6t="computer:container-launch-record";async function _6t(e){return{enableInternet:e.enableInternet,envDigest:await mvr(e.env)}}a(_6t,"launchRecordFor");function hvr(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}a(hvr,"sameLaunch");async function mvr(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(mvr,"digestEnv");var fvr=class{static{a(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(S6t)??null}async set(e){await this.storage.put(S6t,e)}},E6t=new WeakMap;function s8e(e){let t=E6t.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},E6t.set(e,t)),t}a(s8e,"getContainerLifecycle");function xte(e){return s8e(e).exit}a(xte,"containerExitInfo");function T6t(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}a(T6t,"formatExitReason");function A6t(e,t,n){let r=s8e(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>I6t(r,i,void 0,n),s=>I6t(r,i,s,n))}a(A6t,"installContainerMonitor");async function r8e(e,t){let n=s8e(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}a(r8e,"destroyContainerExpectingExit");async function I6t(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=T6t(n),o=Date.now();e.exit={reason:s,exitedAt:o},i?console.info({message:"workspace.container.exited",reason:s,exitedAt:o,expected:!0}):console.warn({message:"workspace.container.exited",reason:s,exitedAt:o,expected:!1});try{await r?.()}catch(c){console.error({message:"workspace.container.exit_cleanup_failed",reason:T6t(c),exitedAt:Date.now()})}}a(I6t,"recordExit");var i8e="computer:container-runtime-identity",gvr=class{static{a(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(i8e)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(i8e,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(i8e)}},yvr=class extends J1r{static{a(this,"WorkspaceContainerAPI")}#e;#n;#r;#t;#i;constructor(e){if(super(),!e.container)throw new Error("WorkspaceContainerAPI: DO is not container-enabled (check wrangler.jsonc)");this.#e=e.container,this.#n=e,this.#r=new gvr(e.storage),this.#t=new pvr(e.storage),this.#i=new fvr(e.storage)}async start(e){let t=xte(this.#n),n=await this.#t.ensure(),r=await _6t(e);if(t!==null){try{await r8e(this.#n,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||!hvr(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 r8e(this.#n,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return A6t(this.#n,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await r8e(this.#n,this.#e)}catch{}let t=await this.#t.ensure();return this.#s(e,t,await _6t(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),A6t(this.#n,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:xte(this.#n)}}async exitInfo(){return xte(this.#n)}async interceptAllOutboundHttp(e,t){let n=this.#n.exports.WorkspaceProxy({props:{...e,egressToken:t}});await Promise.all([this.#e.interceptAllOutboundHttp(n),this.#e.interceptOutboundHttps("*",n)])}async interceptOutboundHttp(e,t){let n=this.#n.exports;await this.#e.interceptOutboundHttp(e,n.WorkspaceProxy({props:t}))}fetchPort(e,t,n){let r=xte(this.#n);if(r!==null)throw new ad(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function R6t(e){class t extends e{static{a(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new yvr(this.ctx)}}return t}a(R6t,"withWorkspaceContainer");var vvr={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function P6t(e,t){let n=t.indexOf("."),r=t.indexOf("/"),i=n>=0?n:r;if(i<0)return;let s=t.slice(0,i),o=t.slice(i+1),c=vvr[s]??s,l=e[c];if(l===void 0)return;let u=l[o];return typeof u=="function"?u:void 0}a(P6t,"resolve");function xvr(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}a(xvr,"errorResponse");async function o8e(e,t,n,r,i){let s=P6t(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}a(o8e,"callEdgeApi");async function O6t(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(P6t(e,i)===void 0)return new Response("not found",{status:404});let s;try{s=await t.json()}catch{return new Response("body is not JSON",{status:400})}let o=typeof s.rpcId=="string"?s.rpcId:"invalid-request",c=s.payload??{};try{let l=await o8e(e,i,o,c,t.signal);return l===void 0?new Response("not found",{status:404}):Response.json({type:"server-response",rpcId:l.rpcId,result:l.result})}catch(l){return xvr(o,{code:"gateway/internal",message:String(l),details:{}})}}a(O6t,"dispatchEdgeApi");Lr();ro();j1();import{DurableObject as o3r}from"cloudflare:workers";var wte=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 bvr(this.stopping,t);continue}await new Promise((r,i)=>{let s=a(()=>{t?.removeEventListener("abort",o),r()},"wake"),o=a(()=>{let c=this.waiters.indexOf(s);c!==-1&&this.waiters.splice(c,1),i(t.reason)},"abort");this.waiters.push(s),t?.addEventListener("abort",o,{once:!0})})}return t?.aborted===!0&&(this.waiters.shift()?.(),t.throwIfAborted()),{release:this.begin(),queuedMs:this.now()-n}}begin(){this.inFlight+=1,this.lastActivity=this.now();let t=!1;return()=>{t||(t=!0,this.inFlight-=1,this.lastActivity=this.now(),this.waiters.shift()?.())}}async stopIfIdle(t){return this.idle()?await this.stop(t):"busy"}async stopNow(t){return this.inFlight===0?await this.stop(t):"busy"}snapshot(){return{runningCommands:this.inFlight,lastActivityAt:this.lastActivity??null}}async stop(t){if(this.stopping!==void 0)return"busy";let n="stopped",r=t().catch(i=>{n="failed",this.lastActivity=this.now(),console.error("dsh-edge container stop failed.",i)});this.stopping=r;try{await r}finally{this.stopping=void 0}return n}deadline(){return this.inFlight>0?this.now()+this.sleepAfterMs():this.lastActivity===void 0?this.now():this.lastActivity+this.sleepAfterMs()}idle(){return this.inFlight===0&&(this.lastActivity===void 0||this.now()>=this.lastActivity+this.sleepAfterMs())}};function bvr(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(bvr,"untilAborted");import{WorkerEntrypoint as Eds}from"cloudflare:workers";var mT=pl(M6t());import{gunzipSync as Ebr}from"node:zlib";var ND=class{static{a(this,"Diff")}diff(t,n,r={}){let i;typeof r=="function"?(i=r,r={}):"callback"in r&&(i=r.callback);let s=this.castInput(t,r),o=this.castInput(n,r),c=this.removeEmpty(this.tokenize(s,r)),l=this.removeEmpty(this.tokenize(o,r));return this.diffWithOptionsObj(c,l,r,i)}diffWithOptionsObj(t,n,r,i){var s;let o=a(b=>{if(b=this.postProcess(b,r),i){setTimeout(function(){i(b)},0);return}else return b},"done"),c=n.length,l=t.length,u=1,d=c+l;r.maxEditLength!=null&&(d=Math.min(d,r.maxEditLength));let p=(s=r.timeout)!==null&&s!==void 0?s:1/0,h=Date.now()+p,m=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(m[0],n,t,0,r);if(m[0].oldPos+1>=l&&f+1>=c)return o(this.buildValues(m[0].lastComponent,n,t));let g=-1/0,v=1/0,x=a(()=>{for(let b=Math.max(g,-u);b<=Math.min(v,u);b+=2){let w,k=m[b-1],E=m[b+1];k&&(m[b-1]=void 0);let A=!1;if(E){let O=E.oldPos-b;A=E&&0<=O&&O<c}let I=k&&k.oldPos+1<l;if(!A&&!I){m[b]=void 0;continue}if(!I||A&&k.oldPos<E.oldPos?w=this.addToPath(E,!0,!1,0,r):w=this.addToPath(k,!1,!0,1,r),f=this.extractCommon(w,n,t,b,r),w.oldPos+1>=l&&f+1>=c)return o(this.buildValues(w.lastComponent,n,t))||!0;m[b]=w,w.oldPos+1>=l&&(v=Math.min(v,b-1)),f+1>=c&&(g=Math.max(g,b+1))}u++},"execEditLength");if(i)a(function b(){setTimeout(function(){if(u>d||Date.now()>h)return i(void 0);x()||b()},0)},"exec")();else for(;u<=d&&Date.now()<=h;){let b=x();if(b)return b}}addToPath(t,n,r,i,s){let o=t.lastComponent;return o&&!s.oneChangePerToken&&o.added===n&&o.removed===r?{oldPos:t.oldPos+i,lastComponent:{count:o.count+1,added:n,removed:r,previousComponent:o.previousComponent}}:{oldPos:t.oldPos+i,lastComponent:{count:1,added:n,removed:r,previousComponent:o}}}extractCommon(t,n,r,i,s){let o=n.length,c=r.length,l=t.oldPos,u=l-i,d=0;for(;u+1<o&&l+1<c&&this.equals(r[l+1],n[u+1],s);)u++,l++,d++,s.oneChangePerToken&&(t.lastComponent={count:1,previousComponent:t.lastComponent,added:!1,removed:!1});return d&&!s.oneChangePerToken&&(t.lastComponent={count:d,previousComponent:t.lastComponent,added:!1,removed:!1}),t.oldPos=l,u}equals(t,n,r){return r.comparator?r.comparator(t,n):t===n||!!r.ignoreCase&&t.toLowerCase()===n.toLowerCase()}removeEmpty(t){let n=[];for(let r=0;r<t.length;r++)t[r]&&n.push(t[r]);return n}castInput(t,n){return t}tokenize(t,n){return Array.from(t)}join(t){return t.join("")}postProcess(t,n){return t}get useLongestToken(){return!1}buildValues(t,n,r){let i=[],s;for(;t;)i.push(t),s=t.previousComponent,delete t.previousComponent,t=s;i.reverse();let o=i.length,c=0,l=0,u=0;for(;c<o;c++){let d=i[c];if(d.removed)d.value=this.join(r.slice(u,u+d.count)),u+=d.count;else{if(!d.added&&this.useLongestToken){let p=n.slice(l,l+d.count);p=p.map(function(h,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(l,l+d.count));l+=d.count,d.added||(u+=d.count)}}return i}};var a8e=class extends ND{static{a(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=kvr}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
|
|
8521
8521
|
`))&&(t=t.trim()),(!r.newlineIsToken||!n.includes(`
|
|
8522
8522
|
`))&&(n=n.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
|
|
8523
8523
|
`)&&(t=t.slice(0,-1)),n.endsWith(`
|
package/worker/isolated/index.js
CHANGED
|
@@ -164,7 +164,7 @@ Known schemas:
|
|
|
164
164
|
- `)}`,new Error(ot)}let Ot=`${l}/$ref`,yt=Ko(e,Ve,n,r,i,s,o,Ot,c);if(yt.valid||Oe.push({instanceLocation:o,keyword:"$ref",keywordLocation:Ot,error:"A subschema had errors."},...yt.errors),n==="4"||n==="7")return{valid:Oe.length===0,errors:Oe}}if(Array.isArray(g)){let et=g.length,Ve=!1;for(let Ot=0;Ot<et;Ot++)if(d===g[Ot]||g[Ot]==="integer"&&d==="number"&&e%1===0&&e===e){Ve=!0;break}Ve||Oe.push({instanceLocation:o,keyword:"type",keywordLocation:`${l}/type`,error:`Instance type "${d}" is invalid. Expected "${g.join('", "')}".`})}else g==="integer"?(d!=="number"||e%1||e!==e)&&Oe.push({instanceLocation:o,keyword:"type",keywordLocation:`${l}/type`,error:`Instance type "${d}" is invalid. Expected "${g}".`}):g!==void 0&&d!==g&&Oe.push({instanceLocation:o,keyword:"type",keywordLocation:`${l}/type`,error:`Instance type "${d}" is invalid. Expected "${g}".`});if(y!==void 0&&(d==="object"||d==="array"?KE(e,y)||Oe.push({instanceLocation:o,keyword:"const",keywordLocation:`${l}/const`,error:`Instance does not match ${JSON.stringify(y)}.`}):e!==y&&Oe.push({instanceLocation:o,keyword:"const",keywordLocation:`${l}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})),v!==void 0&&(d==="object"||d==="array"?v.some(et=>KE(e,et))||Oe.push({instanceLocation:o,keyword:"enum",keywordLocation:`${l}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`}):v.some(et=>e===et)||Oe.push({instanceLocation:o,keyword:"enum",keywordLocation:`${l}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})),b!==void 0){let et=`${l}/not`;Ko(e,b,n,r,i,s,o,et).valid&&Oe.push({instanceLocation:o,keyword:"not",keywordLocation:et,error:'Instance matched "not" schema.'})}let kt=[];if(_!==void 0){let et=`${l}/anyOf`,Ve=Oe.length,Ot=!1;for(let yt=0;yt<_.length;yt++){let ot=_[yt],Ct=Object.create(c),Ue=Ko(e,ot,n,r,i,m===!0?s:null,o,`${et}/${yt}`,Ct);Oe.push(...Ue.errors),Ot=Ot||Ue.valid,Ue.valid&&kt.push(Ct)}Ot?Oe.length=Ve:Oe.splice(Ve,0,{instanceLocation:o,keyword:"anyOf",keywordLocation:et,error:"Instance does not match any subschemas."})}if(k!==void 0){let et=`${l}/allOf`,Ve=Oe.length,Ot=!0;for(let yt=0;yt<k.length;yt++){let ot=k[yt],Ct=Object.create(c),Ue=Ko(e,ot,n,r,i,m===!0?s:null,o,`${et}/${yt}`,Ct);Oe.push(...Ue.errors),Ot=Ot&&Ue.valid,Ue.valid&&kt.push(Ct)}Ot?Oe.length=Ve:Oe.splice(Ve,0,{instanceLocation:o,keyword:"allOf",keywordLocation:et,error:"Instance does not match every subschema."})}if(T!==void 0){let et=`${l}/oneOf`,Ve=Oe.length,Ot=T.filter((yt,ot)=>{let Ct=Object.create(c),Ue=Ko(e,yt,n,r,i,m===!0?s:null,o,`${et}/${ot}`,Ct);return Oe.push(...Ue.errors),Ue.valid&&kt.push(Ct),Ue.valid}).length;Ot===1?Oe.length=Ve:Oe.splice(Ve,0,{instanceLocation:o,keyword:"oneOf",keywordLocation:et,error:`Instance does not match exactly one subschema (${Ot} matches).`})}if((d==="object"||d==="array")&&Object.assign(c,...kt),A!==void 0){let et=`${l}/if`;if(Ko(e,A,n,r,i,s,o,et,c).valid){if(R!==void 0){let Ot=Ko(e,R,n,r,i,s,o,`${l}/then`,c);Ot.valid||Oe.push({instanceLocation:o,keyword:"if",keywordLocation:et,error:'Instance does not match "then" schema.'},...Ot.errors)}}else if(M!==void 0){let Ot=Ko(e,M,n,r,i,s,o,`${l}/else`,c);Ot.valid||Oe.push({instanceLocation:o,keyword:"if",keywordLocation:et,error:'Instance does not match "else" schema.'},...Ot.errors)}}if(d==="object"){if(x!==void 0)for(let yt of x)yt in e||Oe.push({instanceLocation:o,keyword:"required",keywordLocation:`${l}/required`,error:`Instance does not have required property "${yt}".`});let et=Object.keys(e);if(I!==void 0&&et.length<I&&Oe.push({instanceLocation:o,keyword:"minProperties",keywordLocation:`${l}/minProperties`,error:`Instance does not have at least ${I} properties.`}),V!==void 0&&et.length>V&&Oe.push({instanceLocation:o,keyword:"maxProperties",keywordLocation:`${l}/maxProperties`,error:`Instance does not have at least ${V} properties.`}),P!==void 0){let yt=`${l}/propertyNames`;for(let ot in e){let Ct=`${o}/${Cp(ot)}`,Ue=Ko(ot,P,n,r,i,s,Ct,yt);Ue.valid||Oe.push({instanceLocation:o,keyword:"propertyNames",keywordLocation:yt,error:`Property name "${ot}" does not match schema.`},...Ue.errors)}}if(O!==void 0){let yt=`${l}/dependantRequired`;for(let ot in O)if(ot in e){let Ct=O[ot];for(let Ue of Ct)Ue in e||Oe.push({instanceLocation:o,keyword:"dependentRequired",keywordLocation:yt,error:`Instance has "${ot}" but does not have "${Ue}".`})}}if(U!==void 0)for(let yt in U){let ot=`${l}/dependentSchemas`;if(yt in e){let Ct=Ko(e,U[yt],n,r,i,s,o,`${ot}/${Cp(yt)}`,c);Ct.valid||Oe.push({instanceLocation:o,keyword:"dependentSchemas",keywordLocation:ot,error:`Instance has "${yt}" but does not match dependant schema.`},...Ct.errors)}}if(D!==void 0){let yt=`${l}/dependencies`;for(let ot in D)if(ot in e){let Ct=D[ot];if(Array.isArray(Ct))for(let Ue of Ct)Ue in e||Oe.push({instanceLocation:o,keyword:"dependencies",keywordLocation:yt,error:`Instance has "${ot}" but does not have "${Ue}".`});else{let Ue=Ko(e,Ct,n,r,i,s,o,`${yt}/${Cp(ot)}`);Ue.valid||Oe.push({instanceLocation:o,keyword:"dependencies",keywordLocation:yt,error:`Instance has "${ot}" but does not match dependant schema.`},...Ue.errors)}}}let Ve=Object.create(null),Ot=!1;if(F!==void 0){let yt=`${l}/properties`;for(let ot in F){if(!(ot in e))continue;let Ct=`${o}/${Cp(ot)}`,Ue=Ko(e[ot],F[ot],n,r,i,s,Ct,`${yt}/${Cp(ot)}`);if(Ue.valid)c[ot]=Ve[ot]=!0;else if(Ot=i,Oe.push({instanceLocation:o,keyword:"properties",keywordLocation:yt,error:`Property "${ot}" does not match schema.`},...Ue.errors),Ot)break}}if(!Ot&&$!==void 0){let yt=`${l}/patternProperties`;for(let ot in $){let Ct=new RegExp(ot,"u"),Ue=$[ot];for(let qt in e){if(!Ct.test(qt))continue;let hn=`${o}/${Cp(qt)}`,Tt=Ko(e[qt],Ue,n,r,i,s,hn,`${yt}/${Cp(ot)}`);Tt.valid?c[qt]=Ve[qt]=!0:(Ot=i,Oe.push({instanceLocation:o,keyword:"patternProperties",keywordLocation:yt,error:`Property "${qt}" matches pattern "${ot}" but does not match associated schema.`},...Tt.errors))}}}if(!Ot&&H!==void 0){let yt=`${l}/additionalProperties`;for(let ot in e){if(Ve[ot])continue;let Ct=`${o}/${Cp(ot)}`,Ue=Ko(e[ot],H,n,r,i,s,Ct,yt);Ue.valid?c[ot]=!0:(Ot=i,Oe.push({instanceLocation:o,keyword:"additionalProperties",keywordLocation:yt,error:`Property "${ot}" does not match additional properties schema.`},...Ue.errors))}}else if(!Ot&&ne!==void 0){let yt=`${l}/unevaluatedProperties`;for(let ot in e)if(!c[ot]){let Ct=`${o}/${Cp(ot)}`,Ue=Ko(e[ot],ne,n,r,i,s,Ct,yt);Ue.valid?c[ot]=!0:Oe.push({instanceLocation:o,keyword:"unevaluatedProperties",keywordLocation:yt,error:`Property "${ot}" does not match unevaluated properties schema.`},...Ue.errors)}}}else if(d==="array"){le!==void 0&&e.length>le&&Oe.push({instanceLocation:o,keyword:"maxItems",keywordLocation:`${l}/maxItems`,error:`Array has too many items (${e.length} > ${le}).`}),pe!==void 0&&e.length<pe&&Oe.push({instanceLocation:o,keyword:"minItems",keywordLocation:`${l}/minItems`,error:`Array has too few items (${e.length} < ${pe}).`});let et=e.length,Ve=0,Ot=!1;if(q!==void 0){let yt=`${l}/prefixItems`,ot=Math.min(q.length,et);for(;Ve<ot;Ve++){let Ct=Ko(e[Ve],q[Ve],n,r,i,s,`${o}/${Ve}`,`${yt}/${Ve}`);if(c[Ve]=!0,!Ct.valid&&(Ot=i,Oe.push({instanceLocation:o,keyword:"prefixItems",keywordLocation:yt,error:"Items did not match schema."},...Ct.errors),Ot))break}}if(Q!==void 0){let yt=`${l}/items`;if(Array.isArray(Q)){let ot=Math.min(Q.length,et);for(;Ve<ot;Ve++){let Ct=Ko(e[Ve],Q[Ve],n,r,i,s,`${o}/${Ve}`,`${yt}/${Ve}`);if(c[Ve]=!0,!Ct.valid&&(Ot=i,Oe.push({instanceLocation:o,keyword:"items",keywordLocation:yt,error:"Items did not match schema."},...Ct.errors),Ot))break}}else for(;Ve<et;Ve++){let ot=Ko(e[Ve],Q,n,r,i,s,`${o}/${Ve}`,yt);if(c[Ve]=!0,!ot.valid&&(Ot=i,Oe.push({instanceLocation:o,keyword:"items",keywordLocation:yt,error:"Items did not match schema."},...ot.errors),Ot))break}if(!Ot&&Z!==void 0){let ot=`${l}/additionalItems`;for(;Ve<et;Ve++){let Ct=Ko(e[Ve],Z,n,r,i,s,`${o}/${Ve}`,ot);c[Ve]=!0,Ct.valid||(Ot=i,Oe.push({instanceLocation:o,keyword:"additionalItems",keywordLocation:ot,error:"Items did not match additional items schema."},...Ct.errors))}}}if(G!==void 0)if(et===0&&re===void 0)Oe.push({instanceLocation:o,keyword:"contains",keywordLocation:`${l}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(re!==void 0&&et<re)Oe.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${l}/minContains`,error:`Array has less items (${et}) than minContains (${re}).`});else{let yt=`${l}/contains`,ot=Oe.length,Ct=0;for(let Ue=0;Ue<et;Ue++){let qt=Ko(e[Ue],G,n,r,i,s,`${o}/${Ue}`,yt);qt.valid?(c[Ue]=!0,Ct++):Oe.push(...qt.errors)}Ct>=(re||0)&&(Oe.length=ot),re===void 0&&xe===void 0&&Ct===0?Oe.splice(ot,0,{instanceLocation:o,keyword:"contains",keywordLocation:yt,error:"Array does not contain item matching schema."}):re!==void 0&&Ct<re?Oe.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${l}/minContains`,error:`Array must contain at least ${re} items matching schema. Only ${Ct} items were found.`}):xe!==void 0&&Ct>xe&&Oe.push({instanceLocation:o,keyword:"maxContains",keywordLocation:`${l}/maxContains`,error:`Array may contain at most ${xe} items matching schema. ${Ct} items were found.`})}if(!Ot&&ee!==void 0){let yt=`${l}/unevaluatedItems`;for(Ve;Ve<et;Ve++){if(c[Ve])continue;let ot=Ko(e[Ve],ee,n,r,i,s,`${o}/${Ve}`,yt);c[Ve]=!0,ot.valid||Oe.push({instanceLocation:o,keyword:"unevaluatedItems",keywordLocation:yt,error:"Items did not match unevaluated items schema."},...ot.errors)}}if(Te)for(let yt=0;yt<et;yt++){let ot=e[yt],Ct=typeof ot=="object"&&ot!==null;for(let Ue=0;Ue<et;Ue++){if(yt===Ue)continue;let qt=e[Ue];(ot===qt||Ct&&(typeof qt=="object"&&qt!==null)&&KE(ot,qt))&&(Oe.push({instanceLocation:o,keyword:"uniqueItems",keywordLocation:`${l}/uniqueItems`,error:`Duplicate items at indexes ${yt} and ${Ue}.`}),yt=Number.MAX_SAFE_INTEGER,Ue=Number.MAX_SAFE_INTEGER)}}}else if(d==="number"){if(n==="4"?(Ie!==void 0&&(ue===!0&&e<=Ie||e<Ie)&&Oe.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${l}/minimum`,error:`${e} is less than ${ue?"or equal to ":""} ${Ie}.`}),he!==void 0&&(Xe===!0&&e>=he||e>he)&&Oe.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${l}/maximum`,error:`${e} is greater than ${Xe?"or equal to ":""} ${he}.`})):(Ie!==void 0&&e<Ie&&Oe.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${l}/minimum`,error:`${e} is less than ${Ie}.`}),he!==void 0&&e>he&&Oe.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${l}/maximum`,error:`${e} is greater than ${he}.`}),ue!==void 0&&e<=ue&&Oe.push({instanceLocation:o,keyword:"exclusiveMinimum",keywordLocation:`${l}/exclusiveMinimum`,error:`${e} is less than ${ue}.`}),Xe!==void 0&&e>=Xe&&Oe.push({instanceLocation:o,keyword:"exclusiveMaximum",keywordLocation:`${l}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Xe}.`})),Ye!==void 0){let et=e%Ye;Math.abs(0-et)>=11920929e-14&&Math.abs(Ye-et)>=11920929e-14&&Oe.push({instanceLocation:o,keyword:"multipleOf",keywordLocation:`${l}/multipleOf`,error:`${e} is not a multiple of ${Ye}.`})}}else if(d==="string"){let et=ft===void 0&&je===void 0?0:Xze(e);ft!==void 0&&et<ft&&Oe.push({instanceLocation:o,keyword:"minLength",keywordLocation:`${l}/minLength`,error:`String is too short (${et} < ${ft}).`}),je!==void 0&&et>je&&Oe.push({instanceLocation:o,keyword:"maxLength",keywordLocation:`${l}/maxLength`,error:`String is too long (${et} > ${je}).`}),Pe!==void 0&&!new RegExp(Pe,"u").test(e)&&Oe.push({instanceLocation:o,keyword:"pattern",keywordLocation:`${l}/pattern`,error:"String does not match pattern."}),N!==void 0&&Ame[N]&&!Ame[N](e)&&Oe.push({instanceLocation:o,keyword:"format",keywordLocation:`${l}/format`,error:`String does not match format "${N}".`})}return{valid:Oe.length===0,errors:Oe}}var Cme=j(()=>{Tme();LU();Ime();$U();Rme();a(Ko,"validate")});var jU,eHe=j(()=>{LU();Cme();jU=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=F1(t)}validate(t){return Ko(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,n){n&&(t={...t,$id:n}),F1(t,this.lookup)}}});var tHe=j(()=>{Tme();LU();Ime();$U();Zze();Rme();Cme();eHe()});var FU,nHe=j(()=>{tHe();FU=class{static{a(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let n=new jU(t,this.draft,this.shortcircuit);return r=>{let i=n.validate(r);return i.valid?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:i.errors.map(s=>`${s.instanceLocation}: ${s.error}`).join("; ")}}}}});var Do,UU=j(()=>{"use strict";Do={probeTimeoutMs:3e4,callTimeoutMs:6e4,maxToolsPerServer:128,maxCatalogPages:10,maxCatalogBytes:131072,maxDescriptionLength:512,maxErrorMessageChars:300,maxPublicNameLength:64,maxInstructionsLength:1024,metaToolThreshold:20,maxResourceResponseBytes:1048576}});import{createHash as mtn}from"node:crypto";function gtn(e){let t=e.replace(/[.*+?^${}()|[\]\\]/gu,n=>n==="*"?"\0":`\\${n}`);return new RegExp(`^${t.replaceAll("\0",".*")}$`)}function Pme(e,t,n){let r=t??"read_only";return r==="allow_all"?"allow":r==="approve_all"?"ask":n===!0?"allow":n===!1?"ask":ftn.some(i=>gtn(i).test(e))?"allow":"ask"}function Ph(e){return e.replace(/Bearer\s+[^\s"']+/giu,"Bearer ***").replace(/(https?:\/\/[^\s"'?]+)\?[^\s"']*/giu,"$1?***").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/gu,"").slice(0,Do.maxErrorMessageChars)}function rHe(e,t){let n=`mcp__${e}__${t}`,r=n.replace(/[^A-Za-z0-9_-]/gu,"_");if(r===n&&r.length<=Do.maxPublicNameLength)return r;let i=ytn(e,t),s=Do.maxPublicNameLength-i.length-1;return`${r.slice(0,s)}_${i}`}function ytn(e,t){return mtn("sha256").update(`${e}\0${t}`).digest("hex").slice(0,12)}function iHe(e){if(!(e==null||typeof e!="object"))try{let t=JSON.parse(JSON.stringify(e));return Qb(t),t}catch{return}}function btn(e){return vtn.has(e)}function sHe(e){return e.type!=="image"||e.data===void 0||e.mimeType===void 0||!btn(e.mimeType)||!xtn.test(e.data)?void 0:{data:Uint8Array.from(atob(e.data),n=>n.charCodeAt(0)),mediaType:e.mimeType}}function oHe(e){return e.some(t=>t.type==="image"&&t.data!==void 0)}function c8(e){if(e.isError)return[{type:"text",text:e.content.filter(i=>i.type==="text"&&typeof i.text=="string").map(i=>i.text).join(`
|
|
165
165
|
`)||"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} ---
|
|
166
166
|
${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(`
|
|
167
|
-
`)}),t.length>0?t:[{type:"text",text:"(empty MCP result)"}]}var ftn,vtn,xtn,qU=j(()=>{"use strict";Ys();UU();ftn=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a(gtn,"globToRegExp");a(Pme,"evaluateMcpToolPolicy");a(Ph,"scrubMcpErrorMessage");a(rHe,"publicToolName");a(ytn,"hashSuffix");a(iHe,"supportedOutputSchema");vtn=new Set(["image/png","image/jpeg"]),xtn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(btn,"isImageMediaType");a(sHe,"decodeImageBlock");a(oHe,"containsImage");a(c8,"mapMcpResultToContentBlocks")});var Ome,aHe=j(()=>{Ome={name:"dsh-edge",version:"0.29.0-alpha.1",description:"Your DeepSeek Harness, anywhere \u2014 deploy a persistent personal coding agent to Cloudflare Workers in one command",author:"pawaca",license:"MIT",type:"module",bin:{"dsh-edge":"scripts/cli.mjs"},files:["dist","worker","scripts/*.d.mts","scripts/*.mjs","wrangler.jsonc","README.md","README.zh.md","LICENSE","THIRD_PARTY_NOTICES.md"],repository:{type:"git",url:"git+https://github.com/pawaca/dsh-edge.git",directory:"apps/dsh-edge"},homepage:"https://github.com/pawaca/dsh-edge#readme",bugs:{url:"https://github.com/pawaca/dsh-edge/issues"},keywords:["deepseek","deepseek-harness","ai-agents","byok","cloudflare-workers","durable-objects","self-hosted"],engines:{node:">=22.14.0"},publishConfig:{access:"public"},dshEdge:{upstreamVersion:"0.2.1-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.5","@deepseek-ai/cosmokit":"1.8.6","@deepseek-ai/dsh-agent":"0.2.1-rc.2","@deepseek-ai/dsh-agent-instructions":"0.2.1-rc.2","@deepseek-ai/dsh-agent-loop":"0.2.1-rc.2","@deepseek-ai/dsh-anonymous-user-id":"0.2.1-rc.2","@deepseek-ai/dsh-api-gateway":"0.2.1-rc.2","@deepseek-ai/dsh-api-job-controller":"0.2.1-rc.2","@deepseek-ai/dsh-api-remote-access":"0.2.1-rc.2","@deepseek-ai/dsh-api-remotes":"0.2.1-rc.2","@deepseek-ai/dsh-api-session-controller":"0.2.1-rc.2","@deepseek-ai/dsh-api-settings-controller":"0.2.1-rc.2","@deepseek-ai/dsh-api-workspace-controller":"0.2.1-rc.2","@deepseek-ai/dsh-api-workspace-files":"0.2.1-rc.2","@deepseek-ai/dsh-attachment":"0.2.1-rc.2","@deepseek-ai/dsh-brand":"0.2.1-rc.2","@deepseek-ai/dsh-client-connection":"0.2.1-rc.2","@deepseek-ai/dsh-client-file-upload":"0.2.1-rc.2","@deepseek-ai/dsh-client-locale":"0.2.1-rc.2","@deepseek-ai/dsh-client-store":"0.2.1-rc.2","@deepseek-ai/dsh-client-ui-chat":"0.2.1-rc.2","@deepseek-ai/dsh-client-ui-conversation":"0.2.1-rc.2","@deepseek-ai/dsh-client-ui-settings":"0.2.1-rc.2","@deepseek-ai/dsh-client-ui-settings-general":"0.2.1-rc.2","@deepseek-ai/dsh-client-ui-theme":"0.2.1-rc.2","@deepseek-ai/dsh-command-compact":"0.2.1-rc.2","@deepseek-ai/dsh-command-feedback":"0.2.1-rc.2","@deepseek-ai/dsh-command-goal":"0.2.1-rc.2","@deepseek-ai/dsh-commands":"0.2.1-rc.2","@deepseek-ai/dsh-compaction":"0.2.1-rc.2","@deepseek-ai/dsh-compaction-basic":"0.2.1-rc.2","@deepseek-ai/dsh-compaction-image-offload":"0.2.1-rc.2","@deepseek-ai/dsh-compaction-tool-result-pruner":"0.2.1-rc.2","@deepseek-ai/dsh-credentials":"0.2.1-rc.2","@deepseek-ai/dsh-file-reference":"0.2.1-rc.2","@deepseek-ai/dsh-fs":"0.2.1-rc.2","@deepseek-ai/dsh-fs-observation-policy":"0.2.1-rc.2","@deepseek-ai/dsh-goal":"0.2.1-rc.2","@deepseek-ai/dsh-goal-round-driver":"0.2.1-rc.2","@deepseek-ai/dsh-home-paths":"0.2.1-rc.2","@deepseek-ai/dsh-host-directory-picker":"0.2.1-rc.2","@deepseek-ai/dsh-host-plugin-inventory":"0.2.1-rc.2","@deepseek-ai/dsh-jobs":"0.2.1-rc.2","@deepseek-ai/dsh-jobs-local":"0.2.1-rc.2","@deepseek-ai/dsh-launch-environment":"0.2.1-rc.2","@deepseek-ai/dsh-llm":"0.2.1-rc.2","@deepseek-ai/dsh-mcp-resources":"0.2.1-rc.2","@deepseek-ai/dsh-llm-deepseek":"0.2.1-rc.2","@deepseek-ai/dsh-llm-deepseek-api-key":"0.2.1-rc.2","@deepseek-ai/dsh-llm-pi-ai":"0.2.1-rc.2","@deepseek-ai/dsh-llm-retry":"0.2.1-rc.2","@deepseek-ai/dsh-message-feedback":"0.2.1-rc.2","@deepseek-ai/dsh-output-retention":"0.2.1-rc.2","@deepseek-ai/dsh-plan-mode":"0.2.1-rc.2","@deepseek-ai/dsh-ptc-runtime":"0.2.1-rc.2","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.1-rc.2","@deepseek-ai/dsh-sandbox":"0.2.1-rc.2","@deepseek-ai/dsh-schedule":"0.2.1-rc.2","@deepseek-ai/dsh-scope":"0.2.1-rc.2","@deepseek-ai/dsh-session":"0.2.1-rc.2","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.1-rc.2","@deepseek-ai/dsh-session-log-export":"0.2.1-rc.2","@deepseek-ai/dsh-session-format":"0.2.1-rc.2","@deepseek-ai/dsh-session-format-catalog":"0.2.1-rc.2","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.1-rc.2","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.1-rc.2","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.1-rc.2","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.1-rc.2","@deepseek-ai/dsh-session-persistence":"0.2.1-rc.2","@deepseek-ai/dsh-session-projection":"0.2.1-rc.2","@deepseek-ai/dsh-session-projection-cache":"0.2.1-rc.2","@deepseek-ai/dsh-session-stats":"0.2.1-rc.2","@deepseek-ai/dsh-session-turn-outline":"0.2.1-rc.2","@deepseek-ai/dsh-session-query":"0.2.1-rc.2","@deepseek-ai/dsh-session-reference":"0.2.1-rc.2","@deepseek-ai/dsh-session-title":"0.2.1-rc.2","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.1-rc.2","@deepseek-ai/dsh-shell-env":"0.2.1-rc.2","@deepseek-ai/dsh-session-title-llm":"0.2.1-rc.2","@deepseek-ai/dsh-settings":"0.2.1-rc.2","@deepseek-ai/dsh-skill":"0.2.1-rc.2","@deepseek-ai/dsh-spill":"0.2.1-rc.2","@deepseek-ai/dsh-spill-policy":"0.2.1-rc.2","@deepseek-ai/dsh-storage":"0.2.1-rc.2","@deepseek-ai/dsh-storage-domain":"0.2.1-rc.2","@deepseek-ai/dsh-subagent":"0.2.1-rc.2","@deepseek-ai/dsh-subagent-fork-in-process":"0.2.1-rc.2","@deepseek-ai/dsh-subagent-spawn-in-process":"0.2.1-rc.2","@deepseek-ai/dsh-system-prompt":"0.2.1-rc.2","@deepseek-ai/dsh-time-context":"0.2.1-rc.2","@deepseek-ai/dsh-timeout":"0.2.1-rc.2","@deepseek-ai/dsh-token-meter":"0.2.1-rc.2","@deepseek-ai/dsh-tool-ask-user":"0.2.1-rc.2","@deepseek-ai/dsh-tool-call-timeout-policy":"0.2.1-rc.2","@deepseek-ai/dsh-tool-fs":"0.2.1-rc.2","@deepseek-ai/dsh-tool-fs-search":"0.2.1-rc.2","@deepseek-ai/dsh-tool-goal":"0.2.1-rc.2","@deepseek-ai/dsh-tool-jobs":"0.2.1-rc.2","@deepseek-ai/dsh-tool-ralph":"0.2.1-rc.2","@deepseek-ai/dsh-tool-schedule":"0.2.1-rc.2","@deepseek-ai/dsh-tool-session-query":"0.2.1-rc.2","@deepseek-ai/dsh-tool-skill":"0.2.1-rc.2","@deepseek-ai/dsh-tool-subagent":"0.2.1-rc.2","@deepseek-ai/dsh-tool-subagent-control":"0.2.1-rc.2","@deepseek-ai/dsh-tool-present":"0.2.1-rc.2","@deepseek-ai/dsh-tool-todo":"0.2.1-rc.2","@deepseek-ai/dsh-tool-web":"0.2.1-rc.2","@deepseek-ai/dsh-tool-workflow":"0.2.1-rc.2","@deepseek-ai/dsh-tool-working-directory":"0.2.1-rc.2","@deepseek-ai/dsh-tools":"0.2.1-rc.2","@deepseek-ai/dsh-typert-protocol":"0.2.1-rc.2","@deepseek-ai/dsh-typert-registry":"0.2.1-rc.2","@deepseek-ai/dsh-user-approval":"0.2.1-rc.2","@deepseek-ai/dsh-user-questions":"0.2.1-rc.2","@deepseek-ai/dsh-util-values":"0.2.1-rc.2","@deepseek-ai/dsh-web":"0.2.1-rc.2","@deepseek-ai/dsh-web-deepseek-api":"0.2.1-rc.2","@deepseek-ai/dsh-web-fetch-http":"0.2.1-rc.2","@deepseek-ai/dsh-web-search-deepseek":"0.2.1-rc.2","@deepseek-ai/dsh-workflow":"0.2.1-rc.2","@deepseek-ai/dsh-working-directory":"0.2.1-rc.2","@deepseek-ai/dsh-workspace":"0.2.1-rc.2","@deepseek-ai/schemastery":"3.18.5","@mixmark-io/domino":"2.2.0","@modelcontextprotocol/sdk":"1.30.0",acorn:"8.18.0","fast-png":"8.0.0",fflate:"0.8.3","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 Zw,lHe,cHe,u8=j(()=>{"use strict";aHe();Zw=Ome.version,lHe=Ome.dshEdge.upstreamVersion,cHe=`npx dsh-edge@${Zw.includes("-")?"next":"latest"} upgrade`});function Etn(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 Ttn(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function U1(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 ktn)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(Ttn(i)){let s=Etn(i),o=s??i;for(let l of Stn)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 _tn)if(l.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function Atn(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}function Rtn(e){return async(t,n)=>{let r=await c2(t,n);if(r.body===null)return r;let i=0,s=r.body.pipeThrough(new TransformStream({transform(o,l){if(i+=o.byteLength,i>e){l.error(new Error(`MCP server response is larger than ${String(e)} bytes.`));return}l.enqueue(o)}}));return new Response(s,{status:r.status,statusText:r.statusText,headers:r.headers})}}async function Mme(e,t,n,r){U1(e);let i=new DU(new URL(e),{requestInit:{headers:Atn(t),signal:n},fetch:r===void 0?c2:Rtn(r)}),s=new MU({name:"dsh-edge",version:Zw},{capabilities:{},jsonSchemaValidator:Itn});return await s.connect(i),{client:s,close:a(async()=>{await s.close().catch(()=>{})},"close")}}async function uHe(e,t,n){let r=AbortSignal.timeout(Do.probeTimeoutMs),i;try{i=await Mme(t,n,r)}catch(l){throw new Error(Ph(l instanceof Error?l.message:String(l)))}let{client:s,close:o}=i;try{let l=[],c=new Set,u=new Set,d,p=s.getServerCapabilities?.()?.tools!==void 0;for(let y=0;p&&y<Do.maxCatalogPages;y++){let v=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let x of v.tools){if(l.length>=Do.maxToolsPerServer)break;let b=rHe(e,x.name);if(c.has(b))throw new Error(`Server listed tool "${x.name}" more than once`);c.add(b);let _=x.annotations?.readOnlyHint,k=iHe(x.outputSchema);l.push({name:x.name,publicName:b,description:x.description??"",inputSchema:x.inputSchema??{type:"object"},...k!==void 0?{outputSchema:k}:{},..._!==void 0?{annotations:{readOnlyHint:_}}:{}})}if(l.length>=Do.maxToolsPerServer||(d=v.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 h=s.getServerVersion?.(),m=s.getInstructions?.(),g=s.getServerCapabilities?.()?.resources!==void 0;return{tools:l,serverInfo:h?{name:h.name,version:h.version}:void 0,instructions:typeof m=="string"&&m.length>0?m.slice(0,Do.maxInstructionsLength):void 0,resources:g}}finally{await o()}}async function WU(e,t,n,r,i,s){let o=s??Do.callTimeoutMs,l=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),c;try{c=await Mme(e,r,l)}catch(u){throw new Error(Ph(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(Ph(u instanceof Error?u.message:String(u)))}finally{await c.close()}}async function dHe(e,t,n,r,i){let s=i??Do.callTimeoutMs,o=r?AbortSignal.any([r,AbortSignal.timeout(s)]):AbortSignal.timeout(s),l;try{l=await Mme(e,n,o,Do.maxResourceResponseBytes)}catch(c){throw new Error(Ph(c instanceof Error?c.message:String(c)))}try{let{client:c}=l;if(t.method==="resources/read")return await c.readResource({uri:t.uri},{signal:o});let u=t.method==="resources/list"?"resources":"resourceTemplates",d=a(y=>t.method==="resources/list"?c.listResources(y===void 0?void 0:{cursor:y},{signal:o}):c.listResourceTemplates(y===void 0?void 0:{cursor:y},{signal:o}),"page");if(t.cursor!==void 0)return await d(t.cursor);let p=[],h=new Set,m=0,g;for(let y=0;y<Do.maxCatalogPages;y++){let v=await d(g),x=Array.isArray(v[u])?v[u]:[],b=new TextEncoder().encode(JSON.stringify(x)).byteLength;if(p.length>0&&m+b>Do.maxResourceResponseBytes)break;p.push(...x),m+=b;let _=typeof v.nextCursor=="string"?v.nextCursor:void 0;if(_===void 0){g=void 0;break}if(h.has(_))throw new Error(`Server repeated a ${t.method} continuation cursor`);h.add(_),g=_}return g===void 0?{[u]:p}:{[u]:p,nextCursor:g}}catch(c){throw new Error(Ph(c instanceof Error?c.message:String(c)))}finally{await l.close()}}var ktn,Stn,_tn,Itn,c2,d8=j(()=>{"use strict";fze();Kze();nHe();qU();UU();u8();ktn=[".internal",".local",".localhost"],Stn=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],_tn=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(Etn,"extractMappedIPv4");a(Ttn,"isIpAddress");a(U1,"assertSafeUrl");a(Atn,"buildHeaders");Itn=new FU,c2=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(Rtn,"byteCappedFetch");a(Mme,"connectClient");a(uHe,"probe");a(WU,"callTool");a(dHe,"requestResources")});var zU={};$t(zU,{buildAuthorizationUrl:()=>jtn,discoverEndpoints:()=>$tn,exchangeCode:()=>Ftn,isTokenExpired:()=>qtn,refreshToken:()=>Utn,registerClient:()=>Ltn});function fHe(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 Dtn(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 $tn(e){let t=AbortSignal.timeout(BU),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);U1(i.href);let s=await c2(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);U1(d.href);let p=await c2(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 Ltn(e,t,n){let r=AbortSignal.timeout(BU);U1(e);let i=await c2(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 jtn(e,t,n,r,i){let s=fHe(32),o=fHe(64),l=await Dtn(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 Ftn(e,t,n,r,i,s){let o=AbortSignal.timeout(BU),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),U1(e);let c=await c2(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 gHe(await c.json())}async function Utn(e,t,n,r){let i=AbortSignal.timeout(BU),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),U1(e);let o=await c2(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 gHe(await o.json())}function gHe(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 qtn(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var BU,HU=j(()=>{"use strict";d8();BU=1e4;a(fHe,"randomString");a(Dtn,"sha256Base64Url");a($tn,"discoverEndpoints");a(Ltn,"registerClient");a(jtn,"buildAuthorizationUrl");a(Ftn,"exchangeCode");a(Utn,"refreshToken");a(gHe,"parseTokenResponse");a(qtn,"isTokenExpired")});var lr,_He,QE=j(()=>{pr();Pr();lr=class extends ei{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},_He=class extends Mt{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new lr("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function g8(e){return rq.test(e)}function iq(e){return e.invocation.modelInvocable}function YE(e){return e.invocation.userInvocable}function Zme(e){let t=Ern(e);return[`<skill_content name="${Trn(e.name)}">`,"<skill_resources>",...t,"</skill_resources>","","<skill_instructions>",e.content,"</skill_instructions>","</skill_content>"].join(`
|
|
167
|
+
`)}),t.length>0?t:[{type:"text",text:"(empty MCP result)"}]}var ftn,vtn,xtn,qU=j(()=>{"use strict";Ys();UU();ftn=["get_*","list_*","read_*","search_*","find_*","fetch_*","describe_*"];a(gtn,"globToRegExp");a(Pme,"evaluateMcpToolPolicy");a(Ph,"scrubMcpErrorMessage");a(rHe,"publicToolName");a(ytn,"hashSuffix");a(iHe,"supportedOutputSchema");vtn=new Set(["image/png","image/jpeg"]),xtn=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;a(btn,"isImageMediaType");a(sHe,"decodeImageBlock");a(oHe,"containsImage");a(c8,"mapMcpResultToContentBlocks")});var Ome,aHe=j(()=>{Ome={name:"dsh-edge",version:"0.29.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.1-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.5","@deepseek-ai/cosmokit":"1.8.6","@deepseek-ai/dsh-agent":"0.2.1-rc.2","@deepseek-ai/dsh-agent-instructions":"0.2.1-rc.2","@deepseek-ai/dsh-agent-loop":"0.2.1-rc.2","@deepseek-ai/dsh-anonymous-user-id":"0.2.1-rc.2","@deepseek-ai/dsh-api-gateway":"0.2.1-rc.2","@deepseek-ai/dsh-api-job-controller":"0.2.1-rc.2","@deepseek-ai/dsh-api-remote-access":"0.2.1-rc.2","@deepseek-ai/dsh-api-remotes":"0.2.1-rc.2","@deepseek-ai/dsh-api-session-controller":"0.2.1-rc.2","@deepseek-ai/dsh-api-settings-controller":"0.2.1-rc.2","@deepseek-ai/dsh-api-workspace-controller":"0.2.1-rc.2","@deepseek-ai/dsh-api-workspace-files":"0.2.1-rc.2","@deepseek-ai/dsh-attachment":"0.2.1-rc.2","@deepseek-ai/dsh-brand":"0.2.1-rc.2","@deepseek-ai/dsh-client-connection":"0.2.1-rc.2","@deepseek-ai/dsh-client-file-upload":"0.2.1-rc.2","@deepseek-ai/dsh-client-locale":"0.2.1-rc.2","@deepseek-ai/dsh-client-store":"0.2.1-rc.2","@deepseek-ai/dsh-client-ui-chat":"0.2.1-rc.2","@deepseek-ai/dsh-client-ui-conversation":"0.2.1-rc.2","@deepseek-ai/dsh-client-ui-settings":"0.2.1-rc.2","@deepseek-ai/dsh-client-ui-settings-general":"0.2.1-rc.2","@deepseek-ai/dsh-client-ui-theme":"0.2.1-rc.2","@deepseek-ai/dsh-command-compact":"0.2.1-rc.2","@deepseek-ai/dsh-command-feedback":"0.2.1-rc.2","@deepseek-ai/dsh-command-goal":"0.2.1-rc.2","@deepseek-ai/dsh-commands":"0.2.1-rc.2","@deepseek-ai/dsh-compaction":"0.2.1-rc.2","@deepseek-ai/dsh-compaction-basic":"0.2.1-rc.2","@deepseek-ai/dsh-compaction-image-offload":"0.2.1-rc.2","@deepseek-ai/dsh-compaction-tool-result-pruner":"0.2.1-rc.2","@deepseek-ai/dsh-credentials":"0.2.1-rc.2","@deepseek-ai/dsh-file-reference":"0.2.1-rc.2","@deepseek-ai/dsh-fs":"0.2.1-rc.2","@deepseek-ai/dsh-fs-observation-policy":"0.2.1-rc.2","@deepseek-ai/dsh-goal":"0.2.1-rc.2","@deepseek-ai/dsh-goal-round-driver":"0.2.1-rc.2","@deepseek-ai/dsh-home-paths":"0.2.1-rc.2","@deepseek-ai/dsh-host-directory-picker":"0.2.1-rc.2","@deepseek-ai/dsh-host-plugin-inventory":"0.2.1-rc.2","@deepseek-ai/dsh-jobs":"0.2.1-rc.2","@deepseek-ai/dsh-jobs-local":"0.2.1-rc.2","@deepseek-ai/dsh-launch-environment":"0.2.1-rc.2","@deepseek-ai/dsh-llm":"0.2.1-rc.2","@deepseek-ai/dsh-mcp-resources":"0.2.1-rc.2","@deepseek-ai/dsh-llm-deepseek":"0.2.1-rc.2","@deepseek-ai/dsh-llm-deepseek-api-key":"0.2.1-rc.2","@deepseek-ai/dsh-llm-pi-ai":"0.2.1-rc.2","@deepseek-ai/dsh-llm-retry":"0.2.1-rc.2","@deepseek-ai/dsh-message-feedback":"0.2.1-rc.2","@deepseek-ai/dsh-output-retention":"0.2.1-rc.2","@deepseek-ai/dsh-plan-mode":"0.2.1-rc.2","@deepseek-ai/dsh-ptc-runtime":"0.2.1-rc.2","@deepseek-ai/dsh-repeat-tool-reminder":"0.2.1-rc.2","@deepseek-ai/dsh-sandbox":"0.2.1-rc.2","@deepseek-ai/dsh-schedule":"0.2.1-rc.2","@deepseek-ai/dsh-scope":"0.2.1-rc.2","@deepseek-ai/dsh-session":"0.2.1-rc.2","@deepseek-ai/dsh-session-checkpoint-policy":"0.2.1-rc.2","@deepseek-ai/dsh-session-log-export":"0.2.1-rc.2","@deepseek-ai/dsh-session-format":"0.2.1-rc.2","@deepseek-ai/dsh-session-format-catalog":"0.2.1-rc.2","@deepseek-ai/dsh-session-format-v0-to-v1":"0.2.1-rc.2","@deepseek-ai/dsh-session-format-v1-to-v2":"0.2.1-rc.2","@deepseek-ai/dsh-session-format-v2-to-v3":"0.2.1-rc.2","@deepseek-ai/dsh-session-format-v3-to-v4":"0.2.1-rc.2","@deepseek-ai/dsh-session-persistence":"0.2.1-rc.2","@deepseek-ai/dsh-session-projection":"0.2.1-rc.2","@deepseek-ai/dsh-session-projection-cache":"0.2.1-rc.2","@deepseek-ai/dsh-session-stats":"0.2.1-rc.2","@deepseek-ai/dsh-session-turn-outline":"0.2.1-rc.2","@deepseek-ai/dsh-session-query":"0.2.1-rc.2","@deepseek-ai/dsh-session-reference":"0.2.1-rc.2","@deepseek-ai/dsh-session-title":"0.2.1-rc.2","@deepseek-ai/dsh-session-title-first-prompt-llm":"0.2.1-rc.2","@deepseek-ai/dsh-shell-env":"0.2.1-rc.2","@deepseek-ai/dsh-session-title-llm":"0.2.1-rc.2","@deepseek-ai/dsh-settings":"0.2.1-rc.2","@deepseek-ai/dsh-skill":"0.2.1-rc.2","@deepseek-ai/dsh-spill":"0.2.1-rc.2","@deepseek-ai/dsh-spill-policy":"0.2.1-rc.2","@deepseek-ai/dsh-storage":"0.2.1-rc.2","@deepseek-ai/dsh-storage-domain":"0.2.1-rc.2","@deepseek-ai/dsh-subagent":"0.2.1-rc.2","@deepseek-ai/dsh-subagent-fork-in-process":"0.2.1-rc.2","@deepseek-ai/dsh-subagent-spawn-in-process":"0.2.1-rc.2","@deepseek-ai/dsh-system-prompt":"0.2.1-rc.2","@deepseek-ai/dsh-time-context":"0.2.1-rc.2","@deepseek-ai/dsh-timeout":"0.2.1-rc.2","@deepseek-ai/dsh-token-meter":"0.2.1-rc.2","@deepseek-ai/dsh-tool-ask-user":"0.2.1-rc.2","@deepseek-ai/dsh-tool-call-timeout-policy":"0.2.1-rc.2","@deepseek-ai/dsh-tool-fs":"0.2.1-rc.2","@deepseek-ai/dsh-tool-fs-search":"0.2.1-rc.2","@deepseek-ai/dsh-tool-goal":"0.2.1-rc.2","@deepseek-ai/dsh-tool-jobs":"0.2.1-rc.2","@deepseek-ai/dsh-tool-ralph":"0.2.1-rc.2","@deepseek-ai/dsh-tool-schedule":"0.2.1-rc.2","@deepseek-ai/dsh-tool-session-query":"0.2.1-rc.2","@deepseek-ai/dsh-tool-skill":"0.2.1-rc.2","@deepseek-ai/dsh-tool-subagent":"0.2.1-rc.2","@deepseek-ai/dsh-tool-subagent-control":"0.2.1-rc.2","@deepseek-ai/dsh-tool-present":"0.2.1-rc.2","@deepseek-ai/dsh-tool-todo":"0.2.1-rc.2","@deepseek-ai/dsh-tool-web":"0.2.1-rc.2","@deepseek-ai/dsh-tool-workflow":"0.2.1-rc.2","@deepseek-ai/dsh-tool-working-directory":"0.2.1-rc.2","@deepseek-ai/dsh-tools":"0.2.1-rc.2","@deepseek-ai/dsh-typert-protocol":"0.2.1-rc.2","@deepseek-ai/dsh-typert-registry":"0.2.1-rc.2","@deepseek-ai/dsh-user-approval":"0.2.1-rc.2","@deepseek-ai/dsh-user-questions":"0.2.1-rc.2","@deepseek-ai/dsh-util-values":"0.2.1-rc.2","@deepseek-ai/dsh-web":"0.2.1-rc.2","@deepseek-ai/dsh-web-deepseek-api":"0.2.1-rc.2","@deepseek-ai/dsh-web-fetch-http":"0.2.1-rc.2","@deepseek-ai/dsh-web-search-deepseek":"0.2.1-rc.2","@deepseek-ai/dsh-workflow":"0.2.1-rc.2","@deepseek-ai/dsh-working-directory":"0.2.1-rc.2","@deepseek-ai/dsh-workspace":"0.2.1-rc.2","@deepseek-ai/schemastery":"3.18.5","@mixmark-io/domino":"2.2.0","@modelcontextprotocol/sdk":"1.30.0",acorn:"8.18.0","fast-png":"8.0.0",fflate:"0.8.3","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 Zw,lHe,cHe,u8=j(()=>{"use strict";aHe();Zw=Ome.version,lHe=Ome.dshEdge.upstreamVersion,cHe=`npx dsh-edge@${Zw.includes("-")?"next":"latest"} upgrade`});function Etn(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 Ttn(e){return/^\d+\.\d+\.\d+\.\d+$/u.test(e)||e.includes(":")}function U1(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 ktn)if(i.endsWith(s))throw new Error(`MCP server hostname "${i}" is blocked.`);if(Ttn(i)){let s=Etn(i),o=s??i;for(let l of Stn)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 _tn)if(l.test(i))throw new Error(`MCP server address "${i}" is a private IP and is blocked.`)}}}}function Atn(e){return e?.type==="bearer"&&e.token!==void 0?{Authorization:`Bearer ${e.token}`}:{}}function Rtn(e){return async(t,n)=>{let r=await c2(t,n);if(r.body===null)return r;let i=0,s=r.body.pipeThrough(new TransformStream({transform(o,l){if(i+=o.byteLength,i>e){l.error(new Error(`MCP server response is larger than ${String(e)} bytes.`));return}l.enqueue(o)}}));return new Response(s,{status:r.status,statusText:r.statusText,headers:r.headers})}}async function Mme(e,t,n,r){U1(e);let i=new DU(new URL(e),{requestInit:{headers:Atn(t),signal:n},fetch:r===void 0?c2:Rtn(r)}),s=new MU({name:"dsh-edge",version:Zw},{capabilities:{},jsonSchemaValidator:Itn});return await s.connect(i),{client:s,close:a(async()=>{await s.close().catch(()=>{})},"close")}}async function uHe(e,t,n){let r=AbortSignal.timeout(Do.probeTimeoutMs),i;try{i=await Mme(t,n,r)}catch(l){throw new Error(Ph(l instanceof Error?l.message:String(l)))}let{client:s,close:o}=i;try{let l=[],c=new Set,u=new Set,d,p=s.getServerCapabilities?.()?.tools!==void 0;for(let y=0;p&&y<Do.maxCatalogPages;y++){let v=await s.listTools(d===void 0?void 0:{cursor:d},{signal:r});for(let x of v.tools){if(l.length>=Do.maxToolsPerServer)break;let b=rHe(e,x.name);if(c.has(b))throw new Error(`Server listed tool "${x.name}" more than once`);c.add(b);let _=x.annotations?.readOnlyHint,k=iHe(x.outputSchema);l.push({name:x.name,publicName:b,description:x.description??"",inputSchema:x.inputSchema??{type:"object"},...k!==void 0?{outputSchema:k}:{},..._!==void 0?{annotations:{readOnlyHint:_}}:{}})}if(l.length>=Do.maxToolsPerServer||(d=v.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 h=s.getServerVersion?.(),m=s.getInstructions?.(),g=s.getServerCapabilities?.()?.resources!==void 0;return{tools:l,serverInfo:h?{name:h.name,version:h.version}:void 0,instructions:typeof m=="string"&&m.length>0?m.slice(0,Do.maxInstructionsLength):void 0,resources:g}}finally{await o()}}async function WU(e,t,n,r,i,s){let o=s??Do.callTimeoutMs,l=i?AbortSignal.any([i,AbortSignal.timeout(o)]):AbortSignal.timeout(o),c;try{c=await Mme(e,r,l)}catch(u){throw new Error(Ph(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(Ph(u instanceof Error?u.message:String(u)))}finally{await c.close()}}async function dHe(e,t,n,r,i){let s=i??Do.callTimeoutMs,o=r?AbortSignal.any([r,AbortSignal.timeout(s)]):AbortSignal.timeout(s),l;try{l=await Mme(e,n,o,Do.maxResourceResponseBytes)}catch(c){throw new Error(Ph(c instanceof Error?c.message:String(c)))}try{let{client:c}=l;if(t.method==="resources/read")return await c.readResource({uri:t.uri},{signal:o});let u=t.method==="resources/list"?"resources":"resourceTemplates",d=a(y=>t.method==="resources/list"?c.listResources(y===void 0?void 0:{cursor:y},{signal:o}):c.listResourceTemplates(y===void 0?void 0:{cursor:y},{signal:o}),"page");if(t.cursor!==void 0)return await d(t.cursor);let p=[],h=new Set,m=0,g;for(let y=0;y<Do.maxCatalogPages;y++){let v=await d(g),x=Array.isArray(v[u])?v[u]:[],b=new TextEncoder().encode(JSON.stringify(x)).byteLength;if(p.length>0&&m+b>Do.maxResourceResponseBytes)break;p.push(...x),m+=b;let _=typeof v.nextCursor=="string"?v.nextCursor:void 0;if(_===void 0){g=void 0;break}if(h.has(_))throw new Error(`Server repeated a ${t.method} continuation cursor`);h.add(_),g=_}return g===void 0?{[u]:p}:{[u]:p,nextCursor:g}}catch(c){throw new Error(Ph(c instanceof Error?c.message:String(c)))}finally{await l.close()}}var ktn,Stn,_tn,Itn,c2,d8=j(()=>{"use strict";fze();Kze();nHe();qU();UU();u8();ktn=[".internal",".local",".localhost"],Stn=[/^127\./u,/^10\./u,/^172\.(1[6-9]|2\d|3[01])\./u,/^192\.168\./u,/^0\./u,/^169\.254\./u],_tn=[/^::1$/u,/^fc/iu,/^fd/iu,/^fe[89ab][0-9a-f]:/iu];a(Etn,"extractMappedIPv4");a(Ttn,"isIpAddress");a(U1,"assertSafeUrl");a(Atn,"buildHeaders");Itn=new FU,c2=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(Rtn,"byteCappedFetch");a(Mme,"connectClient");a(uHe,"probe");a(WU,"callTool");a(dHe,"requestResources")});var zU={};$t(zU,{buildAuthorizationUrl:()=>jtn,discoverEndpoints:()=>$tn,exchangeCode:()=>Ftn,isTokenExpired:()=>qtn,refreshToken:()=>Utn,registerClient:()=>Ltn});function fHe(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 Dtn(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 $tn(e){let t=AbortSignal.timeout(BU),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);U1(i.href);let s=await c2(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);U1(d.href);let p=await c2(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 Ltn(e,t,n){let r=AbortSignal.timeout(BU);U1(e);let i=await c2(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 jtn(e,t,n,r,i){let s=fHe(32),o=fHe(64),l=await Dtn(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 Ftn(e,t,n,r,i,s){let o=AbortSignal.timeout(BU),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),U1(e);let c=await c2(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 gHe(await c.json())}async function Utn(e,t,n,r){let i=AbortSignal.timeout(BU),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),U1(e);let o=await c2(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 gHe(await o.json())}function gHe(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 qtn(e){return e.expiresAt===void 0?!1:Date.now()>e.expiresAt-12e4}var BU,HU=j(()=>{"use strict";d8();BU=1e4;a(fHe,"randomString");a(Dtn,"sha256Base64Url");a($tn,"discoverEndpoints");a(Ltn,"registerClient");a(jtn,"buildAuthorizationUrl");a(Ftn,"exchangeCode");a(Utn,"refreshToken");a(gHe,"parseTokenResponse");a(qtn,"isTokenExpired")});var lr,_He,QE=j(()=>{pr();Pr();lr=class extends ei{static{a(this,"FsError")}code;constructor(e,t,n){super(e,t,n),this.code=t}},_He=class extends Mt{static{a(this,"FileSystem")}constructor(e){super(e,"fs")}watch(e,t,n){return n.throwIfAborted(),Promise.reject(new lr("Filesystem watching is not supported by this provider.","FS_IO_ERROR"))}get sandboxMode(){}processPathFromHostPath(e){}}});function g8(e){return rq.test(e)}function iq(e){return e.invocation.modelInvocable}function YE(e){return e.invocation.userInvocable}function Zme(e){let t=Ern(e);return[`<skill_content name="${Trn(e.name)}">`,"<skill_resources>",...t,"</skill_resources>","","<skill_instructions>",e.content,"</skill_instructions>","</skill_content>"].join(`
|
|
168
168
|
`)}function Ern(e){let t=e.resourceBase;if(t===void 0)return[`Resources for this skill are managed by provider "${JE(e.provider)}".`,"Load referenced resources only as needed."];switch(t.kind){case"directory":return[`Base directory for this skill: ${JE(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: ${JE(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: ${JE(t.description)}`,"Load referenced resources only as needed."];default:return Lr(t,"SkillResourceBase.kind")}}function Trn(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<")}function JE(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function Irn(e,t){if(Array.isArray(e))return{candidates:e,complete:!0};if(e===null||typeof e!="object")throw GHe(t);let n=e;if(!Array.isArray(n.candidates)||typeof n.complete!="boolean")throw GHe(t);return n}function GHe(e){return new TypeError(`skill provider "${e}" list() must return an array or { candidates, complete } observation`)}function Crn(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:_rn,locator:e,...e.path!==void 0?{path:e.path}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}function Prn(e,t){if(typeof e.name!="string")throw new TypeError(`skill provider "${t}" returned a non-string skill name`);if(!rq.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(Xme(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 Orn(e){if(!rq.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`);Xme(e.invocation,`runtime skill "${e.name}"`)}function Mrn(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(!rq.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(Xme(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 Nrn(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 Xme(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 Drn(e,t){return JHe(e.name,t.name)}function JHe(e,t){return e<t?-1:e>t?1:0}function $rn(e,t){return e.candidate.rank-t.candidate.rank||e.providerOrder-t.providerOrder||e.localOrder-t.localOrder}function Lrn(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 VHe(e,t){return t===void 0?e:(f8(t),new Promise((n,r)=>{let i=a(()=>{t.removeEventListener("abort",s)},"cleanup"),s=a(()=>{i(),r(nq(t.reason))},"onAbort");t.addEventListener("abort",s,{once:!0}),e.then(o=>{i(),n(o)},o=>{i(),r(nq(o))})}))}function f8(e){if(e?.aborted===!0)throw nq(e.reason)}function nq(e){try{if(e instanceof Error)return e}catch{}return new Error(tq(e))}function tq(e){try{return String(e)}catch{return"[unrenderable thrown value]"}}var rq,HHe,Srn,eq,_rn,KHe,Arn,QHe,Rrn,e3=j(()=>{pr();cs();pc();vn();rq=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,HHe=128,Srn=2,eq="runtime",_rn=250,KHe=600;a(g8,"isSkillName");a(iq,"isModelInvocable");a(YE,"isUserInvocable");a(Zme,"renderSkillContent");a(Ern,"renderResourceHint");a(Trn,"escapeAttr");a(JE,"escapeText");Arn=class{static{a(this,"SkillLayer")}providers;runtime=new Map;constructor(e){this.providers=new mh(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}},QHe=class extends Mt{static{a(this,"SkillRegistry")}static Config=L.object({collectCacheMaxEntries:L.number().default(HHe)});collectCacheMaxEntries;layers=new fh(e=>new Arn(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??HHe,Lrn("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===eq)throw new Error(`"${eq}" 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){Orn(e);let t=wl(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??eq};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=>Nrn(n.candidate)).sort(Drn),complete:t.cacheable}}async get(e,t={}){if(!g8(e))return;let n=await this.collect(t);f8(t.signal);let r=n.entries.get(e);if(r===void 0)return;let i=await VHe(r.provider.get(r.candidate,t),t.signal);if(i!==void 0){if(Mrn(i),i.name!==r.candidate.name){this.invalidateEntry(r);return}return i}}async collect(e){f8(e.signal);let t=1;for(;;){let n=this.revision,r=this.collectCacheKey(e.cwd,FI(e.scope),n),i=this.collectCache.get(r);if(i!==void 0)return{entries:i,cacheable:!0};let s=await this.collectFresh(e);if(f8(e.signal),n!==this.revision){if(t<Srn){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($rn);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){f8(t.signal);let n=[],r=!0,i=0;for(let s of[...e.runtime.values()].sort((o,l)=>JHe(o.name,l.name)))n.push({candidate:Crn(s),provider:Rrn,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 VHe(s.list(t),t.signal)}catch(d){if(t.signal?.aborted===!0)throw nq(t.signal.reason);r=!1,this.ctx.logger.warn(`skill provider "${s.name}" skipped: ${tq(d)}`)}if(c===void 0)continue;let u=Irn(c,s.name);u.complete||(r=!1);for(let d of u.candidates)Prn(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: ${tq(n)}`)})}catch(t){this.ctx.logger.warn(`skills/change listener threw: ${tq(t)}`)}}};a(Irn,"normalizeProviderObservation");a(GHe,"invalidProviderObservation");Rrn={name:eq,list(){return Promise.resolve([])},get(e){return Promise.resolve(e.locator)}};a(Crn,"runtimeCandidate");a(Prn,"validateCandidate");a(Orn,"validateRuntimeSkill");a(Mrn,"validateDefinition");a(Nrn,"toSummary");a(Xme,"validateInvocation");a(Drn,"compareSkillSummary");a(JHe,"compareCodePoints");a($rn,"compareIndexedCandidates");a(Lrn,"assertPositiveInteger");a(VHe,"waitWithAbort");a(f8,"throwIfAborted");a(nq,"toError");a(tq,"errorMessage")});var Oh,s4=j(()=>{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 H1,kKe,oge=j(()=>{pr();H1=class extends Error{static{a(this,"DirectoryPickerError")}code;path;constructor(e,t,n){super(n),this.code=e,this.path=t,this.name="DirectoryPickerError"}},kKe=class extends Mt{static{a(this,"DirectoryPicker")}constructor(e){super(e,"directoryPicker")}}});var xz,p0e,ga,vf=j(()=>{xz=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()}},p0e=class{static{a(this,"EventStream")}queue=new xz;waiting=new xz;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}},ga=class extends p0e{static{a(this,"AssistantMessageEventStream")}#e=Date.now();#n=performance.now();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")})}push(t){t.type==="done"?this.#r(t.message):t.type==="error"&&this.#r(t.error),super.push(t)}end(t){t!==void 0&&this.#r(t),super.end(t)}#r(t){this.done||t.durationMs!==void 0||t.timestamp<this.#e||(t.durationMs=Math.max(0,Math.round(performance.now()-this.#n)))}}});function Zpn(e,t,n){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:n}}function Xpn(e){return typeof e.result=="function"}async function ehn(e,t){for await(let n of t)e.push(n);e.end(Xpn(t)?await t.result():void 0)}function Nh(e,t){let n=Date.now(),r=new ga;return t().then(i=>ehn(r,i)).catch(i=>{let s=Zpn(e,i,n);r.push({type:"error",reason:"error",error:s}),r.end(s)}),r}function rl(e,t){let n={stream:a((r,i,s)=>Nh(r,async()=>(await e()).stream(r,i,s)),"stream"),streamSimple:a((r,i,s)=>Nh(r,async()=>(await e()).streamSimple(r,i,s)),"streamSimple")};return t?.fetchDeferred&&(n.fetchDeferred=(r,i,s)=>Nh(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 Dp=j(()=>{vf();a(Zpn,"createSetupErrorMessage");a(Xpn,"hasResult");a(ehn,"forwardStream");a(Nh,"lazyStream");a(rl,"lazyApi")});function nhn(){return globalThis.process?.env}function zYe(){return{async env(e){let t=nhn()?.[e];return typeof t=="string"&&t.trim().length>0?t:void 0},async fileExists(e){try{let t=await BYe("node:fs/promises"),n=e;return n.startsWith("~")&&(n=(await BYe("node:os")).homedir()+n.slice(1)),await t.access(n),!0}catch{return!1}}}}var thn,BYe,HYe=j(()=>{thn=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},BYe=a(e=>import(thn(e)),"importNodeModule");a(nhn,"getProcessEnv");a(zYe,"defaultProviderAuthContext")});function GYe(e){if(e.reason!==void 0)return e.reason;let t=new Error("The operation was aborted");return t.name="AbortError",t}function Dh(e){return e??new AbortController().signal}function $h(e,t){return t.aborted?(e.catch(()=>{}),Promise.reject(GYe(t))):new Promise((n,r)=>{let i=!1,s=a(()=>t.removeEventListener("abort",o),"cleanup"),o=a(()=>{i||(i=!0,s(),r(GYe(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 bz=j(()=>{a(GYe,"abortReason");a(Dh,"operationSignal");a($h,"raceWithAbortSignal")});var wz,VYe=j(()=>{bz();wz=class{static{a(this,"InMemoryCredentialStore")}credentials=new Map;chains=new Map;enqueue(t,n,r){let i=Dh(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)}),$h(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 E2(e){return e instanceof Error?e.message||e.name:typeof e=="string"?e:String(e)}function rhn(e){if(!(e instanceof Error))return{name:"ThrownValue",message:E2(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 kz(e,t,n){return{type:e,timestamp:Date.now(),error:rhn(t),details:n}}function T2(e,t){e.diagnostics=[...e.diagnostics??[],t]}var n9=j(()=>{a(E2,"formatThrownValue");a(rhn,"extractDiagnosticError");a(kz,"createAssistantMessageDiagnostic");a(T2,"appendAssistantMessageDiagnostic")});function ihn(e,t){if(t==null)return e;let n=E2(t).trim();return!n||e.includes(n)?e:`${e}: ${n}`}var Ji,Sz=j(()=>{n9();Ji=class extends Error{static{a(this,"ModelsError")}code;constructor(t,n,r){super(ihn(n,r?.cause),r),this.name="ModelsError",this.code=t}};a(ihn,"withCauseDetail")});function m0e(e,t,n,r){let i=Dh(r?.signal);return $h(shn(e,t,n,r,i),i)}async function shn(e,t,n,r,i){i.throwIfAborted();let s=r?.env?ohn(n,r.env):n;if(r?.apiKey!==void 0&&e.auth.apiKey)return h0e(s,e.auth.apiKey,e.id,{type:"api_key",key:r.apiKey,env:r.env},i);let o=await uhn(t,e.id,i);if(o){if(o.type==="oauth"&&e.auth.oauth)return chn(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 h0e(s,e.auth.apiKey,e.id,l,i)}return}return e.auth.apiKey?h0e(s,e.auth.apiKey,e.id,void 0,i):void 0}function ohn(e,t){return{env:a(async n=>t[n]||await e.env(n),"env"),fileExists:a(n=>e.fileExists(n),"fileExists")}}async function f0e(e,t,n,r,i){let s,o=new AbortController,l=a(()=>o.abort(i.reason),"cancelLockWait");i.addEventListener("abort",l,{once:!0}),i.aborted&&l();try{s=await e.modify(t,async c=>{if(i.removeEventListener("abort",l),i.throwIfAborted(),c?.type==="oauth"&&r(c))try{return await n.refresh(c,AbortSignal.timeout(lhn))}catch(u){throw new Ji("oauth",`OAuth refresh failed for ${t}`,{cause:u})}},{signal:o.signal})}catch(c){throw c instanceof Ji?c:(i.throwIfAborted(),new Ji("auth",`Credential store modify failed for ${t}`,{cause:c}))}finally{i.removeEventListener("abort",l)}return s?.type==="oauth"?s:void 0}async function chn(e,t,n,r,i,s){let o=Math.max(ahn,s??0),l=a(u=>Date.now()+o>=u.expires,"expiresSoon"),c=r;if(l(c)){let u=await f0e(e,t,n,l,i);if(!u)return;if(c=u,s!==void 0&&l(c))throw new Ji("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 Ji("oauth",`OAuth auth derivation failed for ${t}`,{cause:u})}}async function h0e(e,t,n,r,i){try{return await t.resolve({ctx:e,credential:r,signal:i})}catch(s){throw new Ji("auth",`API key auth failed for provider ${n}`,{cause:s})}}async function uhn(e,t,n){try{return await e.read(t,{signal:n})}catch(r){throw new Ji("auth",`Credential store read failed for ${t}`,{cause:r})}}var ahn,lhn,KYe=j(()=>{bz();Sz();Sz();a(m0e,"resolveProviderAuth");a(shn,"resolveProviderAuthWithSignal");a(ohn,"overlayEnvAuthContext");ahn=300*1e3,lhn=15e3;a(f0e,"refreshStoredOAuthCredential");a(chn,"resolveStoredOAuth");a(h0e,"resolveApiKey");a(uhn,"readCredential")});var _z,QYe=j(()=>{_z=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 E4(e){return e.type??"chat"}function xf(e,t){return E4(e)===t}function JYe(e){if(!xf(e,"chat"))throw new Ji("provider",`Model ${e.provider}/${e.id} is not a chat model`)}function YYe(e){if(!xf(e,"image"))throw new Ji("provider",`Model ${e.provider}/${e.id} is not an image model`)}function ZYe(e){if(!xf(e,"classifier"))throw new Ji("provider",`Model ${e.provider}/${e.id} is not a classifier model`)}function XYe(e,t){if(t.images?.length&&!e.input.includes("image"))throw new Ji("provider",`Model ${e.provider}/${e.id} does not accept image input`)}function g0e(e,t,n=!1){return{api:e.api,provider:e.provider,model:e.id,output:[],stopReason:n?"aborted":"error",errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}function y0e(e,t,n=!1){return{api:e.api,provider:e.provider,model:e.id,answers:{},stopReason:n?"aborted":"error",errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}var v0e=j(()=>{Sz();a(E4,"getModelType");a(xf,"isModelType");a(JYe,"assertChatModel");a(YYe,"assertImageModel");a(ZYe,"assertClassifierModel");a(XYe,"assertClassifierInputSupported");a(g0e,"imageErrorResult");a(y0e,"classifierErrorResult")});function Ez(e,t=`
|
|
169
169
|
`){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join(t)}function Ec(e){let t=[Ez(e.content)];for(let n of Object.values(e.sections??{}))n!==null&&t.push(n);return t.filter(n=>n.length>0).join(`
|
|
170
170
|
|
|
@@ -8517,7 +8517,7 @@ The web request used endpoint ${JSON.stringify(e)}. Search endpoint configuratio
|
|
|
8517
8517
|
.error { padding: .75rem; border-radius: .5rem; background: #461d2b; color: #ffd6df; }
|
|
8518
8518
|
.hint { margin: 1.5rem 0 0; font-size: .875rem; }
|
|
8519
8519
|
code { padding: .1rem .3rem; border-radius: .3rem; background: #0c1222; color: #edf2ff; }
|
|
8520
|
-
`}a(y_t,"pageStyles");u8();var P5e="enabled",O5e=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")}),_N=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")}),M5e=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===P5e?"available":"needs-binding","probe")}),xur=Object.freeze([M5e,_N,O5e]);function N5e(e,t=xur){return t.filter(n=>n.probe(e)==="available")}a(N5e,"availableEdgeRuntimeProviders");function D5e(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(D5e,"resolveEdgeRuntimeSelection");function WZ(e){let t=N5e(e),{bash:n,container:r}=D5e(t);return t.find(i=>i.id===(r??n)).shell}a(WZ,"resolveEdgeRuntimeShell");function bur(){return"dsh-edge@0.29.0-alpha.1/isolated"}a(bur,"resolveEdgeDeploymentId");function hS(e){return{baseURL:qke(e.DEEPSEEK_BASE_URL),maxTokens:zke(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Pk(e.DEEPSEEK_MODEL),reasoningEffort:Wke(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:DM(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:Bke(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:fb(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(hS,"resolveEdgeDeploymentConfig");function wur(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(wur,"edgeDeploymentApiKeyConfigured");function kur(e){let t=qke(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(kur,"projectedEdgeBaseURL");function $5e(e,t){return{shell:WZ(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:bur(),apiKeyConfigured:wur(e),baseURL:kur(e.DEEPSEEK_BASE_URL),maxTokens:zke(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Pk(e.DEEPSEEK_MODEL),reasoningEffort:Wke(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:DM(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:Bke(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:fb(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a($5e,"resolveEdgeDeploymentProfile");function BZ(e){hS(e);let t=$5e(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:Zw,upstreamVersion:lHe,status:"ready"}}a(BZ,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as Wvr}from"node:async_hooks";import{RpcTarget as Sur}from"cloudflare:workers";function _ur(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(_ur,"startHeartbeat");async function Eur(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(Eur,"probeComputerdHealth");var Tur="computer.internal",Aur="/health",L5e="/api",Iur=8080,Rur=3e4,Cur=2e4,Pur=1,Our=2e3,Mur=250,Nur=2e3;function Dur(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(Dur,"bearerMatches");var HZ=class{static{a(this,"CloudflareContainerBackend")}type="cloudflare-container";id;#e;#n;#r;#t;#i;#s;#a;#u;constructor(e){this.id=e.id??"container-shell",this.#n=e.egress??{mode:"none"},this.#r=this.#n.mode==="http-gateway"?crypto.randomUUID():void 0,this.#e={container:e.container,workspace:e.workspace,containerEnv:e.containerEnv,egressHost:e.egressHost??Tur,containerPort:e.containerPort??Iur,connectTimeoutMs:e.connectTimeoutMs??Rur,heartbeatIntervalMs:e.heartbeatIntervalMs??Cur,restartAttempts:e.restartAttempts??Pur,healthProbeTimeoutMs:e.healthProbeTimeoutMs??Our,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??Mur,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??Nur}}async connect(){if(this.#u)return this.#u;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.#n.mode==="direct"}))}catch(p){throw new Au(this.#h("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.#n.mode==="http-gateway"&&this.#r!==void 0&&await t.interceptAllOutboundHttp(this.#e.workspace,this.#r)}catch(p){throw new Au(this.#h("egress",{attempt:1,maxAttempts:this.#e.restartAttempts+1,restarts:0,lastError:p,priorExit:n}),{cause:p})}this.#t=s,this.#l(),i=await this.#p(t,r,e,n,i),await this.#c(t,e),await this.#f(t,e,s);let o=await this.#d(e),l=Iee(o),c,u=new Promise(p=>{let h=!1,m=a(()=>{h||(h=!0,c?.(),p(),this.#u=void 0)},"onClose");o.addEventListener("close",m,{once:!0}),o.addEventListener("error",m,{once:!0}),l.onRpcBroken(m)});this.#e.heartbeatIntervalMs>0&&(c=_ur({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.#u=void 0},"close")};return this.#u=d,d}async handleFetch(e){if(this.#n.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(cI),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(yD),i.delete(cI);let l=new Request(e,{headers:i});return this.#n.gateway.fetch(new Request(o,l))}if(new URL(e.url).pathname!==L5e)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${L5e} requires a websocket upgrade`,{status:400});if(!Dur(e.headers.get("authorization"),this.#t))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})}#l(){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,m=>(d=m,!1)))return p;if(c<s)try{({runtimeId:p}=await e.restart({env:t,enableInternet:this.#n.mode==="direct"})),u++}catch(m){throw this.#a?.(m),this.#o(),new Au(this.#h("restart",{attempt:c,maxAttempts:s,restarts:u,lastError:m}),{cause:m})}}throw this.#a?.(new Error("computerd never became healthy")),this.#o(),new Au(this.#h("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 Eur(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 $ur(Math.min(n,s)),n=Math.min(n*2,this.#e.healthRetryMaxDelayMs)}throw r??new Error("computerd health probe timed out")}#h(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=${v_t(t.lastError)}`}async#c(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 Au(`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#f(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:Aur,api:L5e,healthTimeoutMs:r})})}catch(s){throw this.#a?.(s),this.#o(),new Au(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${v_t(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 Au(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect returned ${i.status}: ${s}`,{cause:o})}}async#d(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 Au(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#o()}}};function $ur(e){return new Promise(t=>setTimeout(t,e))}a($ur,"sleep");function v_t(e){return e instanceof Error?e.message:String(e)}a(v_t,"describeError");var x_t="computer:container-client-secret",Lur=16;function jur(){let e=crypto.getRandomValues(new Uint8Array(Lur));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(jur,"generate");var Fur=class{static{a(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(x_t);if(typeof e=="string"&&e.length>0)return e;let t=jur();return await this.storage.put(x_t,t),t}},b_t="computer:container-launch-record";async function w_t(e){return{enableInternet:e.enableInternet,envDigest:await qur(e.env)}}a(w_t,"launchRecordFor");function Uur(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}a(Uur,"sameLaunch");async function qur(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(qur,"digestEnv");var Wur=class{static{a(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(b_t)??null}async set(e){await this.storage.put(b_t,e)}},k_t=new WeakMap;function U5e(e){let t=k_t.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},k_t.set(e,t)),t}a(U5e,"getContainerLifecycle");function zZ(e){return U5e(e).exit}a(zZ,"containerExitInfo");function S_t(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}a(S_t,"formatExitReason");function __t(e,t,n){let r=U5e(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>E_t(r,i,void 0,n),s=>E_t(r,i,s,n))}a(__t,"installContainerMonitor");async function j5e(e,t){let n=U5e(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}a(j5e,"destroyContainerExpectingExit");async function E_t(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=S_t(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:S_t(l),exitedAt:Date.now()})}}a(E_t,"recordExit");var F5e="computer:container-runtime-identity",Bur=class{static{a(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(F5e)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(F5e,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(F5e)}},zur=class extends Sur{static{a(this,"WorkspaceContainerAPI")}#e;#n;#r;#t;#i;constructor(e){if(super(),!e.container)throw new Error("WorkspaceContainerAPI: DO is not container-enabled (check wrangler.jsonc)");this.#e=e.container,this.#n=e,this.#r=new Bur(e.storage),this.#t=new Fur(e.storage),this.#i=new Wur(e.storage)}async start(e){let t=zZ(this.#n),n=await this.#t.ensure(),r=await w_t(e);if(t!==null){try{await j5e(this.#n,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||!Uur(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 j5e(this.#n,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return __t(this.#n,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await j5e(this.#n,this.#e)}catch{}let t=await this.#t.ensure();return this.#s(e,t,await w_t(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),__t(this.#n,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:zZ(this.#n)}}async exitInfo(){return zZ(this.#n)}async interceptAllOutboundHttp(e,t){let n=this.#n.exports.WorkspaceProxy({props:{...e,egressToken:t}});await Promise.all([this.#e.interceptAllOutboundHttp(n),this.#e.interceptOutboundHttps("*",n)])}async interceptOutboundHttp(e,t){let n=this.#n.exports;await this.#e.interceptOutboundHttp(e,n.WorkspaceProxy({props:t}))}fetchPort(e,t,n){let r=zZ(this.#n);if(r!==null)throw new Au(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function T_t(e){class t extends e{static{a(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new zur(this.ctx)}}return t}a(T_t,"withWorkspaceContainer");var Hur={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function I_t(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=Hur[s]??s,c=e[l];if(c===void 0)return;let u=c[o];return typeof u=="function"?u:void 0}a(I_t,"resolve");function Gur(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}a(Gur,"errorResponse");async function q5e(e,t,n,r,i){let s=I_t(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}a(q5e,"callEdgeApi");async function R_t(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(I_t(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 q5e(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 Gur(o,{code:"gateway/internal",message:String(c),details:{}})}}a(R_t,"dispatchEdgeApi");Pr();Hs();P1();import{DurableObject as Bvr}from"cloudflare:workers";var GZ=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 Vur(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 Vur(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(Vur,"untilAborted");import{WorkerEntrypoint as TJi}from"cloudflare:workers";var CS=$l(C_t(),1);import{gunzipSync as yhr}from"node:zlib";var EN=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(b=>{if(b=this.postProcess(b,r),i){setTimeout(function(){i(b)},0);return}else return b},"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}],g=this.extractCommon(m[0],n,t,0,r);if(m[0].oldPos+1>=c&&g+1>=l)return o(this.buildValues(m[0].lastComponent,n,t));let y=-1/0,v=1/0,x=a(()=>{for(let b=Math.max(y,-u);b<=Math.min(v,u);b+=2){let _,k=m[b-1],T=m[b+1];k&&(m[b-1]=void 0);let A=!1;if(T){let M=T.oldPos-b;A=T&&0<=M&&M<l}let R=k&&k.oldPos+1<c;if(!A&&!R){m[b]=void 0;continue}if(!R||A&&k.oldPos<T.oldPos?_=this.addToPath(T,!0,!1,0,r):_=this.addToPath(k,!1,!0,1,r),g=this.extractCommon(_,n,t,b,r),_.oldPos+1>=c&&g+1>=l)return o(this.buildValues(_.lastComponent,n,t))||!0;m[b]=_,_.oldPos+1>=c&&(v=Math.min(v,b-1)),g+1>=l&&(y=Math.max(y,b+1))}u++},"execEditLength");if(i)a(function b(){setTimeout(function(){if(u>d||Date.now()>h)return i(void 0);x()||b()},0)},"exec")();else for(;u<=d&&Date.now()<=h;){let b=x();if(b)return b}}addToPath(t,n,r,i,s){let o=t.lastComponent;return o&&!s.oneChangePerToken&&o.added===n&&o.removed===r?{oldPos:t.oldPos+i,lastComponent:{count:o.count+1,added:n,removed:r,previousComponent:o.previousComponent}}:{oldPos:t.oldPos+i,lastComponent:{count:1,added:n,removed:r,previousComponent:o}}}extractCommon(t,n,r,i,s){let o=n.length,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 g=r[u+m];return g.length>h.length?g: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 W5e=class extends EN{static{a(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=Qur}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
|
|
8520
|
+
`}a(y_t,"pageStyles");u8();var P5e="enabled",O5e=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")}),_N=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")}),M5e=Object.freeze({id:"container",capabilities:Object.freeze(["container"]),plan:"paid",shell:"linux-container",probe:a(e=>e.DSH_EDGE_CONTAINER_RUNTIME===P5e?"available":"needs-binding","probe")}),xur=Object.freeze([M5e,_N,O5e]);function N5e(e,t=xur){return t.filter(n=>n.probe(e)==="available")}a(N5e,"availableEdgeRuntimeProviders");function D5e(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(D5e,"resolveEdgeRuntimeSelection");function WZ(e){let t=N5e(e),{bash:n,container:r}=D5e(t);return t.find(i=>i.id===(r??n)).shell}a(WZ,"resolveEdgeRuntimeShell");function bur(){return"dsh-edge@0.29.0/isolated"}a(bur,"resolveEdgeDeploymentId");function hS(e){return{baseURL:qke(e.DEEPSEEK_BASE_URL),maxTokens:zke(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Pk(e.DEEPSEEK_MODEL),reasoningEffort:Wke(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:DM(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:Bke(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:fb(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a(hS,"resolveEdgeDeploymentConfig");function wur(e){return typeof e.DEEPSEEK_API_KEY=="string"&&e.DEEPSEEK_API_KEY.trim().length>0}a(wur,"edgeDeploymentApiKeyConfigured");function kur(e){let t=qke(e),n=new URL(t);return n.search.length===0&&n.hash.length===0?t:(n.search="",n.hash="",n.href)}a(kur,"projectedEdgeBaseURL");function $5e(e,t){return{shell:WZ(e),storage:"durable-object-sqlite-vfs",attachmentStorage:t??(e.DSH_EDGE_ATTACHMENTS===void 0?"temporary-do":"private-r2"),deploymentId:bur(),apiKeyConfigured:wur(e),baseURL:kur(e.DEEPSEEK_BASE_URL),maxTokens:zke(e.DEEPSEEK_MAX_OUTPUT_TOKENS),model:Pk(e.DEEPSEEK_MODEL),reasoningEffort:Wke(e.DEEPSEEK_REASONING_EFFORT),searchBaseURL:DM(e.DEEPSEEK_SEARCH_BASE_URL),streamIdleTimeoutMs:Bke(e.DEEPSEEK_STREAM_IDLE_TIMEOUT_MS),commandTimeoutPolicy:fb(e.DSH_EDGE_DEFAULT_COMMAND_TIMEOUT_MS,e.DSH_EDGE_MAX_COMMAND_TIMEOUT_MS)}}a($5e,"resolveEdgeDeploymentProfile");function BZ(e){hS(e);let t=$5e(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:Zw,upstreamVersion:lHe,status:"ready"}}a(BZ,"resolveEdgeDeploymentHealth");import{AsyncLocalStorage as Wvr}from"node:async_hooks";import{RpcTarget as Sur}from"cloudflare:workers";function _ur(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(_ur,"startHeartbeat");async function Eur(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(Eur,"probeComputerdHealth");var Tur="computer.internal",Aur="/health",L5e="/api",Iur=8080,Rur=3e4,Cur=2e4,Pur=1,Our=2e3,Mur=250,Nur=2e3;function Dur(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(Dur,"bearerMatches");var HZ=class{static{a(this,"CloudflareContainerBackend")}type="cloudflare-container";id;#e;#n;#r;#t;#i;#s;#a;#u;constructor(e){this.id=e.id??"container-shell",this.#n=e.egress??{mode:"none"},this.#r=this.#n.mode==="http-gateway"?crypto.randomUUID():void 0,this.#e={container:e.container,workspace:e.workspace,containerEnv:e.containerEnv,egressHost:e.egressHost??Tur,containerPort:e.containerPort??Iur,connectTimeoutMs:e.connectTimeoutMs??Rur,heartbeatIntervalMs:e.heartbeatIntervalMs??Cur,restartAttempts:e.restartAttempts??Pur,healthProbeTimeoutMs:e.healthProbeTimeoutMs??Our,healthRetryInitialDelayMs:e.healthRetryInitialDelayMs??Mur,healthRetryMaxDelayMs:e.healthRetryMaxDelayMs??Nur}}async connect(){if(this.#u)return this.#u;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.#n.mode==="direct"}))}catch(p){throw new Au(this.#h("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.#n.mode==="http-gateway"&&this.#r!==void 0&&await t.interceptAllOutboundHttp(this.#e.workspace,this.#r)}catch(p){throw new Au(this.#h("egress",{attempt:1,maxAttempts:this.#e.restartAttempts+1,restarts:0,lastError:p,priorExit:n}),{cause:p})}this.#t=s,this.#l(),i=await this.#p(t,r,e,n,i),await this.#c(t,e),await this.#f(t,e,s);let o=await this.#d(e),l=Iee(o),c,u=new Promise(p=>{let h=!1,m=a(()=>{h||(h=!0,c?.(),p(),this.#u=void 0)},"onClose");o.addEventListener("close",m,{once:!0}),o.addEventListener("error",m,{once:!0}),l.onRpcBroken(m)});this.#e.heartbeatIntervalMs>0&&(c=_ur({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.#u=void 0},"close")};return this.#u=d,d}async handleFetch(e){if(this.#n.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(cI),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(yD),i.delete(cI);let l=new Request(e,{headers:i});return this.#n.gateway.fetch(new Request(o,l))}if(new URL(e.url).pathname!==L5e)return new Response("not found",{status:404});if(e.headers.get("upgrade")!=="websocket")return new Response(`${L5e} requires a websocket upgrade`,{status:400});if(!Dur(e.headers.get("authorization"),this.#t))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})}#l(){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,m=>(d=m,!1)))return p;if(c<s)try{({runtimeId:p}=await e.restart({env:t,enableInternet:this.#n.mode==="direct"})),u++}catch(m){throw this.#a?.(m),this.#o(),new Au(this.#h("restart",{attempt:c,maxAttempts:s,restarts:u,lastError:m}),{cause:m})}}throw this.#a?.(new Error("computerd never became healthy")),this.#o(),new Au(this.#h("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 Eur(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 $ur(Math.min(n,s)),n=Math.min(n*2,this.#e.healthRetryMaxDelayMs)}throw r??new Error("computerd health probe timed out")}#h(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=${v_t(t.lastError)}`}async#c(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 Au(`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#f(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:Aur,api:L5e,healthTimeoutMs:r})})}catch(s){throw this.#a?.(s),this.#o(),new Au(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect failed: ${v_t(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 Au(`CloudflareContainerBackend(${this.id}) [stage=connect]: POST /connect returned ${i.status}: ${s}`,{cause:o})}}async#d(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 Au(`CloudflareContainerBackend(${this.id}) [stage=ws]: /api upgrade did not arrive within ${this.#e.connectTimeoutMs}ms`)),n)})])}finally{r&&clearTimeout(r),this.#o()}}};function $ur(e){return new Promise(t=>setTimeout(t,e))}a($ur,"sleep");function v_t(e){return e instanceof Error?e.message:String(e)}a(v_t,"describeError");var x_t="computer:container-client-secret",Lur=16;function jur(){let e=crypto.getRandomValues(new Uint8Array(Lur));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}a(jur,"generate");var Fur=class{static{a(this,"ContainerClientSecret")}storage;constructor(e){this.storage=e}async ensure(){let e=await this.storage.get(x_t);if(typeof e=="string"&&e.length>0)return e;let t=jur();return await this.storage.put(x_t,t),t}},b_t="computer:container-launch-record";async function w_t(e){return{enableInternet:e.enableInternet,envDigest:await qur(e.env)}}a(w_t,"launchRecordFor");function Uur(e,t){return e.enableInternet===t.enableInternet&&e.envDigest===t.envDigest}a(Uur,"sameLaunch");async function qur(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(qur,"digestEnv");var Wur=class{static{a(this,"CurrentContainerLaunchRecord")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(b_t)??null}async set(e){await this.storage.put(b_t,e)}},k_t=new WeakMap;function U5e(e){let t=k_t.get(e);return t===void 0&&(t={exit:null,currentGeneration:0,expectedExitGeneration:null,currentMonitorSettled:null},k_t.set(e,t)),t}a(U5e,"getContainerLifecycle");function zZ(e){return U5e(e).exit}a(zZ,"containerExitInfo");function S_t(e){return e===void 0?"exited normally":e instanceof Error?e.message:String(e)}a(S_t,"formatExitReason");function __t(e,t,n){let r=U5e(e);r.currentGeneration+=1;let i=r.currentGeneration;r.exit=null,r.currentMonitorSettled=t.monitor().then(()=>E_t(r,i,void 0,n),s=>E_t(r,i,s,n))}a(__t,"installContainerMonitor");async function j5e(e,t){let n=U5e(e);n.expectedExitGeneration=n.currentGeneration;let r=n.currentMonitorSettled;await t.destroy(),r&&await r}a(j5e,"destroyContainerExpectingExit");async function E_t(e,t,n,r){if(t!==e.currentGeneration)return;let i=e.expectedExitGeneration===t;i&&(e.expectedExitGeneration=null);let s=S_t(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:S_t(l),exitedAt:Date.now()})}}a(E_t,"recordExit");var F5e="computer:container-runtime-identity",Bur=class{static{a(this,"CurrentContainerRuntimeIdentity")}storage;constructor(e){this.storage=e}async get(){return await this.storage.get(F5e)??null}async markStarted(){let e={id:crypto.randomUUID()};return await this.storage.put(F5e,e),e}async clear(e){(await this.get())?.id===e.id&&await this.storage.delete(F5e)}},zur=class extends Sur{static{a(this,"WorkspaceContainerAPI")}#e;#n;#r;#t;#i;constructor(e){if(super(),!e.container)throw new Error("WorkspaceContainerAPI: DO is not container-enabled (check wrangler.jsonc)");this.#e=e.container,this.#n=e,this.#r=new Bur(e.storage),this.#t=new Fur(e.storage),this.#i=new Wur(e.storage)}async start(e){let t=zZ(this.#n),n=await this.#t.ensure(),r=await w_t(e);if(t!==null){try{await j5e(this.#n,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||!Uur(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 j5e(this.#n,this.#e)}catch{}return this.#s(e,n,r,"relaunched")}let s=await this.#r.get()??await this.#r.markStarted();return __t(this.#n,this.#e,()=>this.#r.clear(s)),{runtimeId:s.id,clientSecret:n,outcome:"adopted"}}async restart(e){try{await j5e(this.#n,this.#e)}catch{}let t=await this.#t.ensure();return this.#s(e,t,await w_t(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),__t(this.#n,this.#e,()=>this.#r.clear(i)),{runtimeId:i.id,clientSecret:t,outcome:r}}async status(){return{running:this.#e.running,exit:zZ(this.#n)}}async exitInfo(){return zZ(this.#n)}async interceptAllOutboundHttp(e,t){let n=this.#n.exports.WorkspaceProxy({props:{...e,egressToken:t}});await Promise.all([this.#e.interceptAllOutboundHttp(n),this.#e.interceptOutboundHttps("*",n)])}async interceptOutboundHttp(e,t){let n=this.#n.exports;await this.#e.interceptOutboundHttp(e,n.WorkspaceProxy({props:t}))}fetchPort(e,t,n){let r=zZ(this.#n);if(r!==null)throw new Au(`container exited: ${r.reason}`);return this.#e.getTcpPort(e).fetch(t,n)}port(e){return this.#e.getTcpPort(e)}};function T_t(e){class t extends e{static{a(this,"WithWorkspaceContainer")}getWorkspaceContainer(){return new zur(this.ctx)}}return t}a(T_t,"withWorkspaceContainer");var Hur={session:"sessions",skill:"skills",agentPreset:"agentPresets",subagent:"subagents",goal:"goals",event:"events",download:"downloads"};function I_t(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=Hur[s]??s,c=e[l];if(c===void 0)return;let u=c[o];return typeof u=="function"?u:void 0}a(I_t,"resolve");function Gur(e,t){return Response.json({type:"server-response",rpcId:e,result:{ok:!1,error:t}})}a(Gur,"errorResponse");async function q5e(e,t,n,r,i){let s=I_t(e,t);if(s!==void 0)return await s({rpcId:n,payload:r},i)}a(q5e,"callEdgeApi");async function R_t(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(I_t(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 q5e(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 Gur(o,{code:"gateway/internal",message:String(c),details:{}})}}a(R_t,"dispatchEdgeApi");Pr();Hs();P1();import{DurableObject as Bvr}from"cloudflare:workers";var GZ=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 Vur(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 Vur(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(Vur,"untilAborted");import{WorkerEntrypoint as TJi}from"cloudflare:workers";var CS=$l(C_t(),1);import{gunzipSync as yhr}from"node:zlib";var EN=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(b=>{if(b=this.postProcess(b,r),i){setTimeout(function(){i(b)},0);return}else return b},"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}],g=this.extractCommon(m[0],n,t,0,r);if(m[0].oldPos+1>=c&&g+1>=l)return o(this.buildValues(m[0].lastComponent,n,t));let y=-1/0,v=1/0,x=a(()=>{for(let b=Math.max(y,-u);b<=Math.min(v,u);b+=2){let _,k=m[b-1],T=m[b+1];k&&(m[b-1]=void 0);let A=!1;if(T){let M=T.oldPos-b;A=T&&0<=M&&M<l}let R=k&&k.oldPos+1<c;if(!A&&!R){m[b]=void 0;continue}if(!R||A&&k.oldPos<T.oldPos?_=this.addToPath(T,!0,!1,0,r):_=this.addToPath(k,!1,!0,1,r),g=this.extractCommon(_,n,t,b,r),_.oldPos+1>=c&&g+1>=l)return o(this.buildValues(_.lastComponent,n,t))||!0;m[b]=_,_.oldPos+1>=c&&(v=Math.min(v,b-1)),g+1>=l&&(y=Math.max(y,b+1))}u++},"execEditLength");if(i)a(function b(){setTimeout(function(){if(u>d||Date.now()>h)return i(void 0);x()||b()},0)},"exec")();else for(;u<=d&&Date.now()<=h;){let b=x();if(b)return b}}addToPath(t,n,r,i,s){let o=t.lastComponent;return o&&!s.oneChangePerToken&&o.added===n&&o.removed===r?{oldPos:t.oldPos+i,lastComponent:{count:o.count+1,added:n,removed:r,previousComponent:o.previousComponent}}:{oldPos:t.oldPos+i,lastComponent:{count:1,added:n,removed:r,previousComponent:o}}}extractCommon(t,n,r,i,s){let o=n.length,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 g=r[u+m];return g.length>h.length?g: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 W5e=class extends EN{static{a(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=Qur}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
|
|
8521
8521
|
`))&&(t=t.trim()),(!r.newlineIsToken||!n.includes(`
|
|
8522
8522
|
`))&&(n=n.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
|
|
8523
8523
|
`)&&(t=t.slice(0,-1)),n.endsWith(`
|