shadow-claw 1.31.0 → 1.32.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.
Files changed (145) hide show
  1. package/.well-known/mcp/server-card.json +1 -1
  2. package/.well-known/mcp.json +1 -1
  3. package/dist/lib/components/index.js +21 -21
  4. package/dist/lib/components/settings/shadow-claw-channel-config.js +1 -1
  5. package/dist/lib/components/settings/shadow-claw-control-plane.js +1 -1
  6. package/dist/lib/components/settings/shadow-claw-git.js +1 -1
  7. package/dist/lib/components/settings/shadow-claw-llm.js +1 -1
  8. package/dist/lib/components/settings/shadow-claw-networking.js +1 -1
  9. package/dist/lib/components/settings/shadow-claw-notifications.js +1 -1
  10. package/dist/lib/components/settings/shadow-claw-peerjs.js +1 -1
  11. package/dist/lib/components/settings/shadow-claw-storage.js +1 -1
  12. package/dist/lib/components/settings/shadow-claw-task-server.js +1 -1
  13. package/dist/lib/components/settings/shadow-claw-webvm.js +1 -1
  14. package/dist/lib/components/shadow-claw-channel-config.js +1 -1
  15. package/dist/lib/components/shadow-claw-channels.js +1 -1
  16. package/dist/lib/components/shadow-claw-chat.js +1 -1
  17. package/dist/lib/components/shadow-claw-control-plane.js +1 -1
  18. package/dist/lib/components/shadow-claw-conversations.js +1 -1
  19. package/dist/lib/components/shadow-claw-file-viewer.js +1 -1
  20. package/dist/lib/components/shadow-claw-files.js +1 -1
  21. package/dist/lib/components/shadow-claw-git.js +1 -1
  22. package/dist/lib/components/shadow-claw-llm.js +1 -1
  23. package/dist/lib/components/shadow-claw-networking.js +1 -1
  24. package/dist/lib/components/shadow-claw-notifications.js +1 -1
  25. package/dist/lib/components/shadow-claw-pages.js +1 -1
  26. package/dist/lib/components/shadow-claw-peerjs.js +1 -1
  27. package/dist/lib/components/shadow-claw-settings.js +1 -1
  28. package/dist/lib/components/shadow-claw-storage.js +1 -1
  29. package/dist/lib/components/shadow-claw-task-server.js +1 -1
  30. package/dist/lib/components/shadow-claw-tasks.js +1 -1
  31. package/dist/lib/components/shadow-claw-terminal.js +1 -1
  32. package/dist/lib/components/shadow-claw-tools.js +1 -1
  33. package/dist/lib/components/shadow-claw-webvm.js +1 -1
  34. package/dist/lib/components/shadow-claw.js +1 -1
  35. package/dist/lib/{configurePeerJs-u7CYSquX.js → configurePeerJs-DD3G3Pms.js} +2 -2
  36. package/dist/lib/{configurePeerJs-u7CYSquX.js.map → configurePeerJs-DD3G3Pms.js.map} +1 -1
  37. package/dist/lib/{git-DAP_EV6R.js → git-Brr7JIbs.js} +25 -8
  38. package/dist/lib/{git-DAP_EV6R.js.map → git-Brr7JIbs.js.map} +1 -1
  39. package/dist/lib/index.js +21 -21
  40. package/dist/lib/{initControlPlane-DCK_SHeR.js → initControlPlane-3TUdhRBM.js} +7 -7
  41. package/dist/lib/{initControlPlane-DCK_SHeR.js.map → initControlPlane-3TUdhRBM.js.map} +1 -1
  42. package/dist/lib/{orchestrator-XygttQw2.js → orchestrator-DLnCmeTZ.js} +5 -5
  43. package/dist/lib/{orchestrator-XygttQw2.js.map → orchestrator-DLnCmeTZ.js.map} +1 -1
  44. package/dist/lib/{orchestrator-DNamnY-k.js → orchestrator-DW5l2bbW.js} +22 -4
  45. package/dist/lib/{orchestrator-DNamnY-k.js.map → orchestrator-DW5l2bbW.js.map} +1 -1
  46. package/dist/lib/{peerjs-BgkPSHKa.js → peerjs-BXlMuIQn.js} +3 -3
  47. package/dist/lib/{peerjs-BgkPSHKa.js.map → peerjs-BXlMuIQn.js.map} +1 -1
  48. package/dist/lib/{push-client-C09NQEk5.js → push-client-B419nn-i.js} +2 -2
  49. package/dist/lib/{push-client-C09NQEk5.js.map → push-client-B419nn-i.js.map} +1 -1
  50. package/dist/lib/{shadow-claw-vzcggiax.js → shadow-claw-DmMO4vVG.js} +4 -4
  51. package/dist/lib/{shadow-claw-vzcggiax.js.map → shadow-claw-DmMO4vVG.js.map} +1 -1
  52. package/dist/lib/{shadow-claw-channel-config-Cl3JvxIJ.js → shadow-claw-channel-config-BhxHf6wZ.js} +3 -3
  53. package/dist/lib/{shadow-claw-channel-config-Cl3JvxIJ.js.map → shadow-claw-channel-config-BhxHf6wZ.js.map} +1 -1
  54. package/dist/lib/{shadow-claw-channels-kv21lr_O.js → shadow-claw-channels-B5vzE9Z2.js} +2 -2
  55. package/dist/lib/{shadow-claw-channels-kv21lr_O.js.map → shadow-claw-channels-B5vzE9Z2.js.map} +1 -1
  56. package/dist/lib/{shadow-claw-chat-Cj1fHQIl.js → shadow-claw-chat-BsYnJ4-G.js} +3 -3
  57. package/dist/lib/{shadow-claw-chat-Cj1fHQIl.js.map → shadow-claw-chat-BsYnJ4-G.js.map} +1 -1
  58. package/dist/lib/{shadow-claw-control-plane-DySeKB36.js → shadow-claw-control-plane-DqcgQsun.js} +6 -6
  59. package/dist/lib/{shadow-claw-control-plane-DySeKB36.js.map → shadow-claw-control-plane-DqcgQsun.js.map} +1 -1
  60. package/dist/lib/{shadow-claw-conversations-DghueOOD.js → shadow-claw-conversations-B9Pn58g3.js} +2 -2
  61. package/dist/lib/{shadow-claw-conversations-DghueOOD.js.map → shadow-claw-conversations-B9Pn58g3.js.map} +1 -1
  62. package/dist/lib/{shadow-claw-file-viewer-C_ITv8T6.js → shadow-claw-file-viewer-DL6c4oPK.js} +2 -2
  63. package/dist/lib/{shadow-claw-file-viewer-C_ITv8T6.js.map → shadow-claw-file-viewer-DL6c4oPK.js.map} +1 -1
  64. package/dist/lib/{shadow-claw-files-CWBaYt9p.js → shadow-claw-files-C_ksPb8W.js} +2 -2
  65. package/dist/lib/{shadow-claw-files-CWBaYt9p.js.map → shadow-claw-files-C_ksPb8W.js.map} +1 -1
  66. package/dist/lib/{shadow-claw-git-XfPBpfXd.js → shadow-claw-git-jwsY7L1N.js} +3 -3
  67. package/dist/lib/{shadow-claw-git-XfPBpfXd.js.map → shadow-claw-git-jwsY7L1N.js.map} +1 -1
  68. package/dist/lib/{shadow-claw-llm-Gzx4ufL_.js → shadow-claw-llm-CEPJh1Jh.js} +2 -2
  69. package/dist/lib/{shadow-claw-llm-Gzx4ufL_.js.map → shadow-claw-llm-CEPJh1Jh.js.map} +1 -1
  70. package/dist/lib/{shadow-claw-networking-CYEbc5TR.js → shadow-claw-networking-Bi4yvc73.js} +2 -2
  71. package/dist/lib/{shadow-claw-networking-CYEbc5TR.js.map → shadow-claw-networking-Bi4yvc73.js.map} +1 -1
  72. package/dist/lib/{shadow-claw-notifications-DHvkTrgv.js → shadow-claw-notifications-C-JgGqQx.js} +2 -2
  73. package/dist/lib/{shadow-claw-notifications-DHvkTrgv.js.map → shadow-claw-notifications-C-JgGqQx.js.map} +1 -1
  74. package/dist/lib/{shadow-claw-pages-Bj3w3V6Y.js → shadow-claw-pages-OEOClgA8.js} +2 -2
  75. package/dist/lib/{shadow-claw-pages-Bj3w3V6Y.js.map → shadow-claw-pages-OEOClgA8.js.map} +1 -1
  76. package/dist/lib/{shadow-claw-peerjs-B3sx2xLA.js → shadow-claw-peerjs-DmC2CV-9.js} +3 -3
  77. package/dist/lib/{shadow-claw-peerjs-B3sx2xLA.js.map → shadow-claw-peerjs-DmC2CV-9.js.map} +1 -1
  78. package/dist/lib/{shadow-claw-settings-DK-0kp3A.js → shadow-claw-settings-xAtFog0T.js} +2 -2
  79. package/dist/lib/{shadow-claw-settings-DK-0kp3A.js.map → shadow-claw-settings-xAtFog0T.js.map} +1 -1
  80. package/dist/lib/{shadow-claw-storage-p9nVMQPF.js → shadow-claw-storage-B4UHl-po.js} +2 -2
  81. package/dist/lib/{shadow-claw-storage-p9nVMQPF.js.map → shadow-claw-storage-B4UHl-po.js.map} +1 -1
  82. package/dist/lib/{shadow-claw-task-server-BNKCWG2M.js → shadow-claw-task-server-B0eWzg57.js} +2 -2
  83. package/dist/lib/{shadow-claw-task-server-BNKCWG2M.js.map → shadow-claw-task-server-B0eWzg57.js.map} +1 -1
  84. package/dist/lib/{shadow-claw-tasks-Dbq9rUku.js → shadow-claw-tasks-HHU_8Gyg.js} +2 -2
  85. package/dist/lib/{shadow-claw-tasks-Dbq9rUku.js.map → shadow-claw-tasks-HHU_8Gyg.js.map} +1 -1
  86. package/dist/lib/{shadow-claw-terminal-Wk2qRWJ9.js → shadow-claw-terminal-CdC2G6Zz.js} +2 -2
  87. package/dist/lib/{shadow-claw-terminal-Wk2qRWJ9.js.map → shadow-claw-terminal-CdC2G6Zz.js.map} +1 -1
  88. package/dist/lib/{shadow-claw-tools-C9TEf2k7.js → shadow-claw-tools-2AICxVXA.js} +3 -3
  89. package/dist/lib/{shadow-claw-tools-C9TEf2k7.js.map → shadow-claw-tools-2AICxVXA.js.map} +1 -1
  90. package/dist/lib/{shadow-claw-webvm-VoKerWW8.js → shadow-claw-webvm-Cy-Ia2vs.js} +2 -2
  91. package/dist/lib/{shadow-claw-webvm-VoKerWW8.js.map → shadow-claw-webvm-Cy-Ia2vs.js.map} +1 -1
  92. package/dist/lib/subsystems/git/git.d.ts +8 -1
  93. package/dist/lib/subsystems/git/types.d.ts +7 -1
  94. package/dist/lib/{syncWebMcpRegistration-DEs4JjI_.js → syncWebMcpRegistration-CaAPPg2V.js} +2 -2
  95. package/dist/lib/{syncWebMcpRegistration-DEs4JjI_.js.map → syncWebMcpRegistration-CaAPPg2V.js.map} +1 -1
  96. package/dist/public/.well-known/mcp/server-card.json +1 -1
  97. package/dist/public/.well-known/mcp.json +1 -1
  98. package/dist/public/agent.worker.js +2 -2
  99. package/dist/public/{configurePeerJs-B68egTBd.js → configurePeerJs--JGpJVti.js} +1 -1
  100. package/dist/public/docs/example/article/index.html +1 -1
  101. package/dist/public/docs/publishing/index.html +1 -1
  102. package/dist/public/docs/skill-creator/index.html +1 -1
  103. package/dist/public/{e2e-bridge-DQ4Mb_eC.js → e2e-bridge-CbYqdMp-.js} +1 -1
  104. package/dist/public/{file-viewer-BqNHyqzy.js → file-viewer-vHJ5Zsgk.js} +1 -1
  105. package/dist/public/git-8F7wvoUB.js +100 -0
  106. package/dist/public/git-DgFF7xTW.js +100 -0
  107. package/dist/public/index.html +1 -1
  108. package/dist/public/index.js +1 -1
  109. package/dist/public/{initControlPlane-DG_LcLDy.js → initControlPlane-C5v0FtJE.js} +1 -1
  110. package/dist/public/main/index.html +1 -1
  111. package/dist/public/main/memory/index.html +1 -1
  112. package/dist/public/{orchestrator-DAJkyJmV.js → orchestrator-BeJfwtvz.js} +3 -3
  113. package/dist/public/{orchestrator-BXwxW4N2.js → orchestrator-DNr2HDI2.js} +1 -1
  114. package/dist/public/{peerjs-BaDbzfgl.js → peerjs-mG30TAJ_.js} +1 -1
  115. package/dist/public/{push-client-B1CCaldJ.js → push-client-C2zMT3Sf.js} +1 -1
  116. package/dist/public/service-worker.js +1 -1
  117. package/dist/public/{shadow-claw-CpBmveOh.js → shadow-claw-Ble6l0Iw.js} +2 -2
  118. package/dist/public/{shadow-claw-channels-7Oew09u0.js → shadow-claw-channels-D_xfBoWp.js} +1 -1
  119. package/dist/public/{shadow-claw-chat-CskwjDzZ.js → shadow-claw-chat-D_Lbi5oH.js} +1 -1
  120. package/dist/public/{shadow-claw-control-plane-BqjEyhx7.js → shadow-claw-control-plane-CrnA5lM0.js} +2 -2
  121. package/dist/public/{shadow-claw-conversations-ClGgBPVY.js → shadow-claw-conversations-BN-hFmN1.js} +1 -1
  122. package/dist/public/{shadow-claw-file-viewer-rDepUwFJ.js → shadow-claw-file-viewer-BKEpzpbx.js} +1 -1
  123. package/dist/public/{shadow-claw-files-C0r05PYf.js → shadow-claw-files-DDZMk5AA.js} +1 -1
  124. package/dist/public/{shadow-claw-git-CXrECHKy.js → shadow-claw-git-CqOO97Re.js} +2 -2
  125. package/dist/public/{shadow-claw-llm-jeGVNciG.js → shadow-claw-llm-DoGxEHQL.js} +1 -1
  126. package/dist/public/{shadow-claw-networking--q6MgEAT.js → shadow-claw-networking-DJeCdb7e.js} +1 -1
  127. package/dist/public/{shadow-claw-notifications-CrFUF0fl.js → shadow-claw-notifications-hSKJeMXb.js} +1 -1
  128. package/dist/public/{shadow-claw-pages-_n1wVXAV.js → shadow-claw-pages-DTS98Zbi.js} +1 -1
  129. package/dist/public/{shadow-claw-settings-5yIfa3ie.js → shadow-claw-settings-5w0ce8SP.js} +2 -2
  130. package/dist/public/{shadow-claw-storage-PLX9EFGn.js → shadow-claw-storage-DqlVt27X.js} +1 -1
  131. package/dist/public/{shadow-claw-task-server-BMps7aSr.js → shadow-claw-task-server-ByZwKI6S.js} +1 -1
  132. package/dist/public/{shadow-claw-tasks-CHO1xvsu.js → shadow-claw-tasks-Dc4G4zBu.js} +1 -1
  133. package/dist/public/{shadow-claw-terminal-BJnSXRsb.js → shadow-claw-terminal-DvusP7wg.js} +1 -1
  134. package/dist/public/{shadow-claw-tools-BHfxRckC.js → shadow-claw-tools-BEsid8q-.js} +1 -1
  135. package/dist/public/{shadow-claw-webvm-CyI23mQT.js → shadow-claw-webvm-BWlIeK78.js} +1 -1
  136. package/dist/public/{syncWebMcpRegistration-R0tha3kP.js → syncWebMcpRegistration-CqVCB6m8.js} +1 -1
  137. package/package.json +1 -1
  138. package/src/storage/staticMainSite.ts +16 -2
  139. package/src/stores/orchestrator.test.ts +33 -0
  140. package/src/stores/orchestrator.ts +36 -0
  141. package/src/subsystems/git/git.test.ts +99 -0
  142. package/src/subsystems/git/git.ts +92 -12
  143. package/src/subsystems/git/types.ts +7 -0
  144. package/dist/public/git-BDaM5VT5.js +0 -100
  145. package/dist/public/git-D4n46G9B.js +0 -100
@@ -2044,7 +2044,7 @@ t.exports=function(e){return typeof e==`string`&&e.charAt(0)===``?e.slice(1):
2044
2044
 
2045
2045
  ⚠️ This model has a small context window. Try clicking **'Compact'** in the header to summarize the conversation and reduce token usage.`),c===`llamafile`&&fX(i)&&(o=!0,e.events.emit(`provider-help`,{providerId:`llamafile`,reason:i})),c===`transformers_js_local`&&pX(i)&&(o=!0,e.events.emit(`provider-help`,{providerId:`transformers_js_local`,reason:i})),!o){let t=MG(c,i,l?.requiresApiKey!==!1);t&&e.events.emit(`provider-help`,{providerId:c,reason:i,helpType:t})}await dX(e,t,r,`⚠️ Error: ${a}`);break}case`typing`:{let{groupId:t}=n.payload;e.router?.setTyping(t,!0),e.events.emit(`typing`,{groupId:t,typing:!0});break}case`tool-activity`:e.events.emit(`tool-activity`,n.payload),(n.payload.tool===`write_file`&&n.payload.status===`done`||n.payload.tool===`bash`&&n.payload.status===`done`)&&e.events.emit(`file-change`,{groupId:n.payload.groupId});break;case`model-download-progress`:e.events.emit(`model-download-progress`,n.payload);break;case`thinking-log`:e.events.emit(`thinking-log`,n.payload);break;case`compact-done`:e.clearProviderRequest(n.payload.groupId),await e.handleCompactDone(t,n.payload.groupId,n.payload.summary);break;case`token-usage`:e.events.emit(`token-usage`,n.payload);break;case`task-list-request`:{let{groupId:r}=n.payload,i=(await hX(t)).filter(e=>e.groupId===r);e.agentWorker?.postMessage({type:`task-list-response`,payload:{groupId:r,tasks:i}});break}case`update-task`:{let{task:r}=n.payload;if(r.groupId&&e.schedulerTriggeredGroups.has(r.groupId)){EX(`⚠️ Task update blocked — scheduled tasks cannot modify tasks (recursion prevention).`,{type:`warning`,duration:8e3});break}try{if(!await FX(e,r,await _X(t))){EX(`Failed to sync task update to server — task was not updated.`,{type:`error`});break}await bX(t,r),e.events.emit(`task-change`,{type:`updated`,task:r})}catch(e){console.error(`Failed to update task from agent:`,e),EX(`Failed to update task.`,{type:`error`})}break}case`delete-task`:{let{id:r,groupId:i}=n.payload;if(i&&e.schedulerTriggeredGroups.has(i)){EX(`⚠️ Task deletion blocked — scheduled tasks cannot delete tasks (recursion prevention).`,{type:`warning`,duration:8e3});break}try{if(!await IX(e,r,await _X(t))){EX(`Failed to delete task from server — task kept in view.`,{type:`error`});break}await mX(t,r),e.events.emit(`task-change`,{type:`deleted`,id:r})}catch(e){console.error(`Failed to delete task from agent:`,e)}break}case`clear-chat`:{let{groupId:r}=n.payload;try{await e.newSession(t,r)}catch(e){console.error(`Failed to clear chat from agent:`,e)}break}case`show-toast`:{let{message:e,type:t,duration:r}=n.payload;EX(e,{type:t||`info`,duration:r});break}case`mcp-reauth-required`:{let{connectionId:r}=n.payload,i=await _r(t,r),a=i?.label||r;if(i?.autoReconnectOAuth){EX(`🔑 MCP connection "${a}" returned 401 — auto-reconnecting OAuth…`,{type:`info`,duration:5e3});let n=await CX(t,r,{silentOnly:!0});n.success?EX(`🔑 OAuth reconnected for "${a}"`,{type:`success`,duration:5e3}):EX(`🔑 OAuth auto-reconnect failed for "${a}": ${n.error}`,{action:{label:`Reconnect Now`,onClick:async()=>{let e=await CX(t,r);e.success?EX(`🔑 OAuth reconnected for "${a}"`,{type:`success`,duration:5e3}):EX(`🔑 OAuth reconnect failed for "${a}": ${e.error}`,{type:`error`,duration:1e4})}},duration:15e3,type:`error`}),e.agentWorker?.postMessage({payload:{connectionId:r,success:n.success},type:`mcp-reauth-result`})}else EX(`🔑 MCP connection "${a}" returned 401 — OAuth re-authentication required. Go to Settings → Remote MCP to reconnect.`,{type:`warning`,duration:1e4}),e.agentWorker?.postMessage({payload:{connectionId:r,success:!1},type:`mcp-reauth-result`});e.events.emit(`mcp-reauth-required`,{connectionId:r,label:a});break}case`manage-tools`:{let{action:r,toolNames:i,profileId:a}=n.payload;if(r===`activate_profile`&&a)await Hq.activateProfile(t,a);else if((r===`enable`||r===`disable`)&&i){let e=r===`enable`;for(let n of i)await Hq.setToolEnabled(t,n,e)}let o=n.payload.groupId||`br:main`;e.agentWorker?.postMessage({type:`update-tools`,payload:{enabledTools:Hq.enabledTools,groupId:o,systemPromptOverride:Hq.systemPromptOverride}});break}case`send-notification`:{let{title:t,body:r,groupId:i}=n.payload;if(i&&e.schedulerTriggeredGroups.has(i)){EX(`⚠️ Notification blocked — scheduled tasks triggered via push cannot send push notifications (recursion prevention).`,{type:`warning`,duration:8e3});break}wX(`/push/broadcast`).then(e=>{fetch(e,{body:JSON.stringify({title:t,body:r}),headers:{"Content-Type":`application/json`},method:`POST`}).catch(e=>console.error(`Failed to broadcast push notification:`,e))});break}case`vm-status`:e.vmStatus={...n.payload},e.events.emit(`vm-status`,e.vmStatus);break;case`vm-terminal-opened`:e.events.emit(`vm-terminal-opened`,n.payload);break;case`vm-terminal-output`:e.events.emit(`vm-terminal-output`,n.payload);break;case`vm-terminal-closed`:e.events.emit(`vm-terminal-closed`,n.payload);break;case`vm-workspace-synced`:e.events.emit(`file-change`,{groupId:n.payload?.groupId});break;case`vm-terminal-error`:e.events.emit(`vm-terminal-error`,n.payload);break;case`open-file`:e.events.emit(`open-file`,n.payload);break;case`send-file`:{let{groupId:t,path:r}=n.payload;(async()=>{e.router?.setTyping(t,!0);try{await e.router?.send(t,``,[{path:r,fileName:r.split(`/`).pop()||r,mimeType:`application/octet-stream`,size:0}])}catch(e){let t=e instanceof Error?e.message:String(e);console.error(`send-file: delivery failed:`,e),EX(`Failed to send file to peer: ${t}`,{type:`error`,duration:6e3})}finally{e.router?.setTyping(t,!1)}})();break}case`render-component`:{let{groupId:t,envelope:r}=n.payload;if(e.events.emit(`a2ui-surface`,{groupId:t,envelope:r}),t.startsWith(`peer:`)){let n=e.router?.findChannel(t);n&&`sendA2UI`in n&&n.sendA2UI(t,r).catch(e=>console.error(`render-component: peer delivery failed:`,e))}t.startsWith(`room:`)&&e.roomManager.broadcastA2UI(vX(t),r);break}case`request-native-ai-task`:{let{id:r,groupId:i,taskType:a,input:o}=n.payload;(async()=>{try{let n=await F(t,j.BUILTIN_AI_TOOLS_BACKEND)||`active_provider`,s;if(n!==`local`)s=await zX(e,a,o,i);else{let t=t=>{e.events.emit(`model-download-progress`,{groupId:i,status:t.status,progress:t.progress,message:t.message})};if(a===`summarize`)s=await $J(o.text,{...o,onProgress:t});else if(a===`write`)s=await eY(o.prompt,{...o,onProgress:t});else if(a===`rewrite`)s=await tY(o.text,{...o,onProgress:t});else if(a===`proofread`)s=await iY(o.text,{...o,onProgress:t});else if(a===`detect-language`)s=await nY(o.text,{onProgress:t});else if(a===`translate`)s=await rY(o.text,{...o,onProgress:t});else if(a===`semantic-embedder`)s=await aY(o.text,{...o,onProgress:t});else throw Error(`Unknown native AI task: ${a}`)}i&&e.events.emit(`model-download-progress`,{groupId:i,status:`done`,progress:1});let c=globalThis.pendingNativeAiResolvers;c&&c[r]&&(c[r].resolve(s),delete c[r]),e.agentWorker?.postMessage({type:`native-ai-task-response`,payload:{id:r,response:s}})}catch(t){i&&e.events.emit(`model-download-progress`,{groupId:i,status:`error`,progress:null,message:t?.message||String(t)});let n=globalThis.pendingNativeAiResolvers;n&&n[r]&&(n[r].reject(t instanceof Error?t:Error(String(t))),delete n[r]),e.agentWorker?.postMessage({type:`native-ai-task-response`,payload:{id:r,error:t?.message||String(t)}})}})();break}case`ask-user`:e.events.emit(`ask-user`,n.payload);break}}async function zX(e,t,n,r){let i=r?e.inFlightEffectiveProviderByGroup?.get(r):void 0,a=i?.providerId||e.provider,o=i?.model||i?.providerConfig?.defaultModel||e.model,s=``;if(t===`translate`)s=`Translate the following text from ${n.sourceLanguage||`auto`} to ${n.targetLanguage}. Provide ONLY the raw translated text without commentary or quotation marks:\n\n${n.text}`;else if(t===`summarize`)s=`Summarize the following text (type: ${n.type||`tldr`}, format: ${n.format||`plain-text`}, length: ${n.length||`medium`}). Provide ONLY the summary:\n\n${n.text}`;else if(t===`write`)s=`Draft content for the following request (context: ${n.context||`none`}):\n\n${n.prompt}`;else if(t===`rewrite`)s=`Rewrite the following text (tone: ${n.tone||`standard`}, length: ${n.length||`as-is`}):\n\n${n.text}`;else if(t===`proofread`)s=`Proofread and correct grammar, spelling, and style in the following text. Provide ONLY the corrected text:\n\n${n.text}`;else if(t===`detect-language`)s=`Detect the language of the following text. Return ONLY a JSON array of objects with "detectedLanguage" (BCP 47 code) and "confidence" (0.0 - 1.0), e.g. [{"detectedLanguage":"en","confidence":0.99}]:\n\n${n.text}`;else if(t===`semantic-embedder`)s=`Provide a concise semantic description/representation for the following content:\n\n${JSON.stringify(n.text)}`;else throw Error(`Unknown task type: ${t}`);if(a===`prompt_api`){await ZJ();let e=globalThis,n=e.LanguageModel||e.ai?.languageModel;if(n&&typeof n.create==`function`){let e;try{e=await n.create()}catch(e){console.warn(`Prompt API session creation failed in active provider task:`,e)}if(e)try{let n=await e.prompt(s),r=String(n||``).trim();if(t===`detect-language`)try{let e=JSON.parse(r);return Array.isArray(e)?e:[e]}catch{return[{detectedLanguage:`en`,confidence:.8}]}return r}finally{typeof e.destroy==`function`&&e.destroy()}}}let c=O(a);if(!c||!c.baseUrl||c.baseUrl.startsWith(`builtin://`)||c.baseUrl.startsWith(`local://`)||c.format===`prompt_api`||c.format===`transformers_js`){if(t===`summarize`)return await $J(n.text,n);if(t===`write`)return await eY(n.prompt,n);if(t===`rewrite`)return await tY(n.text,n);if(t===`proofread`)return await iY(n.text,n);if(t===`detect-language`)return await nY(n.text);if(t===`translate`)return await rY(n.text,{sourceLanguage:n.sourceLanguage||`auto`,targetLanguage:n.targetLanguage||`en`,...n});if(t===`semantic-embedder`)return await aY(n.text,n);throw Error(`Provider ${a} not found and no local fallback available`)}let l={...WY(c,await OX(e)||``),...kX(e,a,``)},u=tX(c,[{role:`user`,content:s}],[],{maxTokens:e.maxTokens||2048,model:o,system:`You are a specialized text task assistant. Fulfill the user request directly and accurately without conversational filler.`}),d=await fetch(c.baseUrl,{body:JSON.stringify(u),headers:l,method:`POST`});if(!d.ok){let e=await d.text();throw Error(`Active provider task API error ${d.status}: ${e}`)}let f=rX(c,await d.json()).content?.filter(e=>e.type===`text`)?.map(e=>e.text)?.join(``)?.trim()||``;if(t===`detect-language`)try{let e=JSON.parse(f);return Array.isArray(e)?e:[e]}catch{return[{detectedLanguage:`en`,confidence:.8}]}return f}async function BX(e,t,n=w){let r=(await nK(t)).find(e=>e.groupId===n),i=r?.pinnedProvider??e.provider,a=r?.pinnedModel??(r?.pinnedProvider?O(r.pinnedProvider)?.defaultModel??e.model:e.model),o=(O(i)??e.providerConfig)?.requiresApiKey!==!1,s=i===e.provider?await OX(e):await e.getApiKeyForSpecificProvider(t,i);if(o&&!s){let t=`API key not configured. Cannot compact context.`;e.events.emit(`provider-help`,{providerId:i,reason:t,helpType:MG(i,t,o)}),e.events.emit(`error`,{groupId:n,error:t});return}if(e.state!==`idle`){e.events.emit(`error`,{groupId:n,error:`Cannot compact while processing. Wait for the current response to finish.`});return}e.setState(`thinking`,n),e.events.emit(`typing`,{groupId:n,typing:!0});let c=``;try{c=await we(t,n,`MEMORY.md`)}catch{}let l=Hq.enabledTools,u=HZ.getPeerState(n)||void 0,d=oX(e.assistantName,c,l,Hq.systemPromptOverride,u,void 0,{groupId:n}),f=a;i===`prompt_api`&&(a===`browser-built-in`||!a)&&!cY()&&(f=await F(t,j.PROMPT_API_FALLBACK_MODEL)||`onnx-community/Qwen3-0.6B-ONNX`);let p=iX(f),m=IG(d),h=zG(await KG(n,200),{contextLimit:p,systemPromptTokens:m,maxOutputTokens:4096,skimTop:e.contextCompressionEnabled}).messages;if(await F(t,j.COMPACTION_ENGINE_PREFERENCE)===`builtin_task_api`)try{let r=await $J(h.map(e=>`${e.role.toUpperCase()}: ${typeof e.content==`string`?e.content:JSON.stringify(e.content)}`).join(`
2046
2046
 
2047
- `),{type:`key-points`,format:`markdown`,length:`medium`});await e.handleCompactDone(t,n,r);return}catch(r){await dX(e,t,n,`⚠️ Built-in Task API compaction failed, falling back to provider: ${r instanceof Error?r.message:String(r)}`)}if(i===`prompt_api`){if(cY()||await ZJ(),!cY()){e.events.emit(`error`,{groupId:n,error:`Prompt API is not available in this browser. Switch provider or enable experimental browser flags.`}),e.events.emit(`typing`,{groupId:n,typing:!1}),e.setState(`idle`,n);return}let r=new AbortController;e.promptControllers.set(n,r);try{let i=await MY(aX(d),h,r.signal,async n=>{await RX(e,t,n)},n);await e.handleCompactDone(t,n,i)}catch(r){if(r instanceof Error&&r.name===`AbortError`)return;await dX(e,t,n,`⚠️ Error: Compaction failed: ${r instanceof Error?r.message:String(r)}`)}finally{e.promptControllers.delete(n)}return}let g=e.createProviderRequestId(n);e.agentWorker?.postMessage({type:`compact`,payload:{apiKey:s,assistantName:e.assistantName,contextCompression:e.contextCompressionEnabled,contextLimit:iX(f),groupId:n,memory:c,messages:h,model:a,provider:i,providerHeaders:kX(e,i,g,r?.providerRuntimeOverrides),rateLimitAutoAdapt:e.rateLimitAutoAdapt,rateLimitCallsPerMinute:e.rateLimitCallsPerMinute,storageHandle:await F(t,j.STORAGE_HANDLE),systemPrompt:d}})}function VX(e,t=w){e.agentWorker?.postMessage({payload:{groupId:t},type:`vm-workspace-sync`})}function HX(e,t=w){e.agentWorker?.postMessage({payload:{groupId:t},type:`vm-workspace-flush`})}function UX(e){`serviceWorker`in navigator&&navigator.serviceWorker?.controller&&navigator.serviceWorker.controller.postMessage({type:`set-proxy-config`,payload:{useProxy:e.useProxy,proxyUrl:e.proxyUrl}})}async function WX(e,t,n,r=U){e.gitProxyUrl=n||`/git-proxy`,await r(t,j.GIT_PROXY_URL,e.gitProxyUrl)}async function GX(e,t,n,r=U){e.proxyUrl=n||`/proxy`,await r(t,j.PROXY_URL,e.proxyUrl),UX(e)}async function KX(e,t,n,r=U){e.useProxy=!!n,await r(t,j.USE_PROXY,e.useProxy?`true`:`false`),UX(e)}async function qX(e,t,n,r=U){e.vmBashFullInternetAccess=!!n,await r(t,j.VM_BASH_FULL_INTERNET_ACCESS,e.vmBashFullInternetAccess?`true`:`false`)}function JX(e,t){return new Promise((n,r)=>{try{let i=e?.transaction(`messages`,`readwrite`);if(!i)return r(Error(`failed to get transaction, cannot clear group messages.`));let a=i.objectStore(`messages`).index(`by-group`).openCursor(t);a.onsuccess=()=>{let e=a.result;e?(e.delete(),e.continue()):n(void 0)},a.onerror=()=>r(a.error)}catch(e){r(e)}})}function YX(e,t,n){return new Promise((r,i)=>{let a=e?.transaction(`messages`,`readwrite`);if(!a)throw Error(`failed to get transaction, cannot clone messages.`);let o=a.objectStore(`messages`),s=o.index(`by-group`).openCursor(t),c=0;s.onsuccess=()=>{let e=s.result;if(e){let t={...e.value,id:dr(),groupId:n};o.put(t),c++,e.continue()}else r(c)},s.onerror=()=>i(s.error)})}function XX(e,t,n){return new Promise((r,i)=>{let a=e?.transaction(`tasks`,`readwrite`);if(!a)throw Error(`failed to get transaction, cannot clone tasks.`);let o=a.objectStore(`tasks`),s=o.index(`by-group`).openCursor(t),c=0;s.onsuccess=()=>{let e=s.result;if(e){let t={...e.value,id:dr(),groupId:n};o.put(t),c++,e.continue()}else r(c)},s.onerror=()=>i(s.error)})}function ZX(e,t){return ae(e,`messages`,`readwrite`,e=>e.delete(t)).then(()=>void 0)}function QX(e,t){return new Promise(async(n,r)=>{try{let i=await ie();if(!i)return r(Error(`failed to get transaction, cannot update task last run.`));let a=i.transaction(`tasks`,`readwrite`);if(!a)return r(Error(`failed to get transaction`));let o=a.objectStore(`tasks`),s=o.get(e);s.onsuccess=()=>{let e=s.result;if(!e){n();return}e.lastRun=t;let i=o.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)},s.onerror=()=>r(s.error)}catch(e){r(e)}})}async function $X(e,t,n){let r=(await hX(e)).filter(e=>e.groupId===t),i=new Map(r.map(e=>[e.id,e])),a=[],o=0;for(let t of n){let n=i.get(t);n&&(n.order=o++,await bX(e,n),a.push(n),i.delete(t))}let s=Array.from(i.values()).sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?e.createdAt-t.createdAt:n-r});for(let t of s)t.order=o++,await bX(e,t),a.push(t);return a}async function eZ(e,t,n,r){let i=await z(e,t),a=await z(e,n),o=r.replace(/\\/g,`/`).replace(/^\/+/,``).split(`/`).filter(Boolean),s=i,c=a;for(let e of o)s=await s.getDirectoryHandle(e),c=await c.getDirectoryHandle(e,{create:!0});let l=n.replace(/:/g,`-`),u=[_e(),`groups`,l,...o];try{await tZ(e,n,s,c,u)}catch(e){throw o.length>0&&await a.removeEntry(o[0],{recursive:!0}).catch(()=>void 0),e}}async function tZ(e,t,n,r,i){for await(let[a,o]of n.entries()){if(o.kind===`directory`){await tZ(e,t,o,await r.getDirectoryHandle(a,{create:!0}),[...i,a]);continue}let n=await o.getFile(),s=await r.getFileHandle(a,{create:!0});try{await On(s,n)}catch(t){if(!((t instanceof Error?t.message:String(t)).includes(`Writable file streams are not supported`)&&(await R(e)).type===`opfs`))throw t;await kn([...i,a],n)}}}async function nZ(e,t,n=`.`){for(let r=0;r<2;r++)try{let r=await z(e,t);if(n&&n!==`.`){let e=n.replace(/\\/g,`/`).replace(/^\/home\/user\//,`/`).replace(/^\/+/,``).split(`/`).filter(Boolean);for(let t of e){let e=await r.getDirectoryHandle(t);if(typeof r.isSameEntry==`function`&&await r.isSameEntry(e))throw Error(`Directory navigation stuck at "${r.name}" for segment "${t}" — the stored directory handle may be stale.`);r=e}}let i=[];for await(let[e,t]of r.entries())i.push(t.kind===`directory`?`${e}/`:e);return i.sort()}catch(e){if(r===0&&Se(e)){L();continue}throw e}return[]}function rZ(e){if(!e||typeof e!=`object`)return!1;let t=globalThis.FileSystemDirectoryHandle;return t!==void 0&&e instanceof t||typeof e.getDirectoryHandle==`function`&&typeof e.getFileHandle==`function`&&typeof e.requestPermission==`function`}async function iZ(e){let t=await F(e,j.STORAGE_HANDLE);return!rZ(t)||await t.requestPermission({mode:`readwrite`})===`granted`}function aZ(e){let t=p();return t?`shadowclaw:${t}:${e}`:e}function oZ(e){if(typeof localStorage>`u`)return null;let t=aZ(e);try{let n=localStorage.getItem(t);if(n!==null)return n;if(t===e)return null;let r=localStorage.getItem(e);if(r!==null)return localStorage.setItem(t,r),r}catch(e){console.warn(`Unable to read from localStorage:`,e)}return null}function sZ(e,t){if(typeof localStorage>`u`)return;let n=aZ(e);try{localStorage.setItem(n,t)}catch(e){console.warn(`Unable to write to localStorage:`,e)}}async function cZ(e,t){let n=await z(e,t);for await(let[e]of n.entries())await n.removeEntry(e,{recursive:!0})}async function lZ(e,t,n){let r=await z(e,t),{dirs:i,filename:a}=Ce(n.replace(/\/$/,``)),o=r;for(let e of i)o=await o.getDirectoryHandle(e);await o.removeEntry(a,{recursive:!0})}function uZ(e,t){return`${e}:${t}`}async function dZ(e){let t=await F(e,j.SUPPRESSED_PAGES_LIST);if(!t||typeof t!=`string`)return[];try{let e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return[]}async function fZ(e,t,n){let r=await dZ(e),i=uZ(t,n);return r.some(e=>uZ(e.groupId,e.path)===i)}async function pZ(e,t,n){let r=await dZ(e),i=uZ(t,n);if(!r.some(e=>uZ(e.groupId,e.path)===i)){let i=[...r,{groupId:t,path:n}];await U(e,j.SUPPRESSED_PAGES_LIST,JSON.stringify(i))}}async function mZ(e,t,n){let r=await dZ(e),i=uZ(t,n),a=r.filter(e=>uZ(e.groupId,e.path)!==i);a.length!==r.length&&await U(e,j.SUPPRESSED_PAGES_LIST,JSON.stringify(a))}function hZ(e=w){return e===`br:main`?j.STATIC_MAIN_SITE_SEEDED:`${j.STATIC_MAIN_SITE_SEEDED}:${e}`}async function gZ(e,t=w){let n=await F(e,hZ(t));return n===!0||n===`true`}async function _Z(e,t=w,n=!0){await U(e,hZ(t),n)}function vZ(){let e=h(`/static-main-manifest.json`);if(typeof window<`u`&&window.location?.origin)try{return new URL(e,window.location.origin).toString()}catch{return e}return e}function yZ(e){let t=h(`/static-main/${e.replace(/^\/+/,``)}`);if(typeof window<`u`&&window.location?.origin)try{return new URL(t,window.location.origin).toString()}catch{return t}return t}async function bZ(){if(typeof fetch!=`function`)return null;try{let e=vZ(),t=await fetch(e);if(t.ok){let e=await t.json();if(e&&Array.isArray(e.pages))return e}}catch{}return null}async function xZ(e){if(typeof fetch!=`function`)return null;try{let t=yZ(e),n=await fetch(t);if(n.ok)return await n.text()}catch{}return null}async function SZ(e={}){let t=()=>{if(typeof document<`u`){let e=document.getElementById(`shadow-claw-static-manifest`);if(e&&e.textContent)try{let t=JSON.parse(e.textContent);if(t&&Array.isArray(t.pages))return t}catch(e){console.warn(`Failed to parse embedded static main manifest:`,e)}}return null};if(e.preferEmbedded!==!1){let e=t();if(e)return e}if(e.fetchFallback!==!1){let e=await bZ();if(e)return e}if(e.preferEmbedded===!1){let e=t();if(e)return e}return{pages:[{displayPath:`index.html`,content:FW},{displayPath:`MEMORY.md`,content:kW}]}}async function CZ(e,t,n=[]){for(let[r,i]of Object.entries(t))if(r===`purgePreRenderedStaticPages`&&i===!0){if(n.length>0){let t=n[0],r=n.slice(1).join(`/`);try{r?await lZ(e,t,r):await cZ(e,t)}catch(e){console.warn(`Failed to purge pre-rendered static pages for ${t}/${r}:`,e)}}}else typeof i==`object`&&i&&await CZ(e,i,[...n,r])}function wZ(){if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent);if(t?.pages?.sortOrder===`desc`)return`desc`;if(t?.pages?.sortOrder===`asc`)return`asc`}}catch{}return`desc`}function TZ(e,t){let n=t??wZ();return[...e].sort((e,t)=>{let r=e.path,i=t.path,a=r.split(`/`).pop()||``,o=i.split(`/`).pop()||``,s=/^index\.(html?|xhtml)$/iu.test(a),c=/^index\.(html?|xhtml)$/iu.test(o);if(s&&!c)return-1;if(!s&&c)return 1;let l=/^memory\.(md|markdown)$/iu.test(a),u=/^memory\.(md|markdown)$/iu.test(o);return l&&!u?1:!l&&u?-1:n===`asc`?r.localeCompare(i,void 0,{numeric:!0,sensitivity:`base`}):i.localeCompare(r,void 0,{numeric:!0,sensitivity:`base`})})}async function EZ(e,t,n=`sc:purge-id`,r=`static_main_site_purge_id`){let i=t??`__legacy_purge_pages__`;try{if(oZ(n)===i)return!0}catch{}try{if(await F(e,r)===i){try{sZ(n,i)}catch{}return!0}await U(e,r,i);try{sZ(n,i)}catch{}}catch{try{sZ(n,i)}catch{}}return!1}async function DZ(e,t=w,n=[],r={}){await zW(e,t);let i=await SZ(r),a=!1;i.preRenderedStaticPages&&(await EZ(e,i.purgeId)||(a=!0,await CZ(e,i.preRenderedStaticPages)));let o=!1;if(t===`br:main`&&i.skillsPurgeId!==void 0&&!await EZ(e,i.skillsPurgeId,`sc:skills-purge-id`,`static_main_skills_purge_id`)){o=!0;try{await lZ(e,t,`.agents/skills/main`)}catch(e){if(!(e&&typeof e==`object`&&`name`in e&&e.name===`NotFoundError`))throw e}}for(let n of i.pages)if(n.content?.includes(`slug: "shadow-claw--purge-pages"`)){!a&&!await EZ(e,i.purgeId)&&(a=!0,await cZ(e,t));break}let s=t===`br:main`&&await MW(e),c=new Set(i.pages.map(e=>uZ(t,e.displayPath))),l=a?n.filter(e=>e.groupId!==t||c.has(uZ(e.groupId,e.path))):[...n];for(let n of i.pages)if(!n.content?.includes(`slug: "shadow-claw--purge-pages"`)){if(/^memory\.(md|markdown)$/iu.test(n.displayPath)){if(s)continue;let r=n.content===kW?void 0:n.content;if(r===void 0?await PW(e,t):await PW(e,t,r)){let e=uZ(t,n.displayPath);l.some(t=>uZ(t.groupId,t.path)===e)||l.push({groupId:t,path:n.displayPath})}continue}if(!await fZ(e,t,n.displayPath))try{if(!await AW(e,t,n.displayPath)){let r=n.content;typeof r!=`string`&&(r=await xZ(n.displayPath)??``),await Nn(e,t,n.displayPath,r)}let r=uZ(t,n.displayPath);l.some(e=>uZ(e.groupId,e.path)===r)||l.push({groupId:t,path:n.displayPath})}catch(e){console.warn(`Failed to seed static page file ${n.displayPath}:`,e)}}if(t===`br:main`){for(let n of i.skills||[]){let r=`.agents/skills/main/${n.displayPath}`;try{await AW(e,t,r)||await Nn(e,t,r,n.content)}catch(e){console.warn(`Failed to seed skill file ${r}:`,e)}}for(let n of i.tools||[]){let r=`.agents/tools/main/${n.displayPath}`;try{await AW(e,t,r)||await Nn(e,t,r,n.content)}catch(e){console.warn(`Failed to seed tool file ${r}:`,e)}}}let u=typeof document<`u`&&document.getElementById(`shadow-claw-static-manifest`)!==null;return r.preferEmbedded!==!1&&u||await _Z(e,t,!0),Object.defineProperty(l,"didPurge",{value:a,enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(l,"didPurgeSkills",{value:o,enumerable:!1,writable:!0,configurable:!0}),TZ(l)}var OZ=class{_events;_handlers=[];_runs=new Map;constructor(e){this._events=e}start(){this._listen(`streaming-start`,this._onStreamingStart),this._listen(`streaming-chunk`,this._onStreamingChunk),this._listen(`streaming-end`,this._onStreamingEnd),this._listen(`streaming-done`,this._onStreamingDone),this._listen(`streaming-error`,this._onStreamingError),this._listen(`tool-activity`,this._onToolActivity)}stop(){for(let{event:e,handler:t}of this._handlers)this._events.off(e,t);this._handlers=[],this._runs.clear()}_emit(e,t){window.dispatchEvent(new CustomEvent(`shadow-claw-agui-event`,{detail:{groupId:e,event:t}}))}_listen(e,t){this._events.on(e,t),this._handlers.push({event:e,handler:t})}_onStreamingChunk=({groupId:e,text:t})=>{let n=this._runs.get(e);!n||!n.messageId||this._emit(e,{type:`TEXT_MESSAGE_CONTENT`,messageId:n.messageId,delta:t,timestamp:Date.now()})};_onStreamingDone=({groupId:e})=>{let t=this._runs.get(e);t&&(t.messageId&&this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:t.messageId,timestamp:Date.now()}),this._emit(e,{type:`RUN_FINISHED`,threadId:t.threadId,runId:t.runId,timestamp:Date.now()}),this._runs.delete(e))};_onStreamingEnd=({groupId:e})=>{let t=this._runs.get(e);!t||!t.messageId||(this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:t.messageId,timestamp:Date.now()}),t.messageId=null)};_onStreamingError=({groupId:e,error:t})=>{let n=this._runs.get(e);n&&(n.messageId&&this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:n.messageId,timestamp:Date.now()}),this._emit(e,{type:`RUN_ERROR`,message:t||`Unknown streaming error`,timestamp:Date.now()}),this._runs.delete(e))};_onStreamingStart=({groupId:e})=>{let t=dr(),n=e,r=dr();this._runs.set(e,{runId:t,threadId:n,messageId:r,activeToolCallIds:new Set}),this._emit(e,{type:`RUN_STARTED`,threadId:n,runId:t,timestamp:Date.now()}),this._emit(e,{type:`TEXT_MESSAGE_START`,messageId:r,role:`assistant`,timestamp:Date.now()})};_onToolActivity=({groupId:e,tool:t,status:n})=>{let r=this._runs.get(e);if(r){if(n===`running`){let n=dr();r.activeToolCallIds.add(n),this._emit(e,{type:`TOOL_CALL_START`,toolCallId:n,toolCallName:t,timestamp:Date.now()}),r._lastToolCallId=n}else if(n===`done`||n===`error`){let t=r._lastToolCallId;t&&(r.activeToolCallIds.delete(t),this._emit(e,{type:`TOOL_CALL_END`,toolCallId:t,timestamp:Date.now()}))}}}};function kZ(e,t){if(!e||typeof e!=`object`)return e;let n=JSON.parse(JSON.stringify(e));for(let e of t)AZ(n,e);return n}function AZ(e,t){let{op:n,path:r,value:i}=t;if(!r||!r.startsWith(`/`))return;let a=r.split(`/`).slice(1).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`)),o=a.pop();if(o===void 0)return;let s=e;for(let e of a){if(typeof s!=`object`||!s)return;s=s[e]}typeof s!=`object`||!s||(Array.isArray(s)?jZ(s,o,n,i):MZ(s,o,n,i))}function jZ(e,t,n,r){if(n===`add`)if(t===`-`)e.push(r);else{let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<=e.length&&e.splice(n,0,r)}else if(n===`replace`){let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<e.length&&(e[n]=r)}else if(n===`remove`){let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<e.length&&e.splice(n,1)}}function MZ(e,t,n,r){n===`add`||n===`replace`?e[t]=r:n===`remove`&&delete e[t]}var NZ=t({OrchestratorStore:()=>VZ,accumulateTokenUsage:()=>BZ,orchestratorStore:()=>HZ});function PZ(e){if(e){if(Array.isArray(e))return e;if(typeof e==`string`)try{let t=JSON.parse(e);return Array.isArray(t)?t:void 0}catch{return}}}function FZ(e){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();return t===`true`||t===`1`}return typeof e==`number`&&e===1}function IZ(e){return!!e}async function LZ(e,t,n,r){if(!IZ(r))return!0;if(!e.schedule)return await RZ(e.id,t,n,r)!==`failed`;try{let r=t.replace(/\/$/,``);return(await fetch(`${r}/tasks`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...e,subscriberId:n})})).ok}catch{return!1}}async function RZ(e,t,n,r){if(!IZ(r))return`missing`;try{let r=t.replace(/\/$/,``),i=`subscriberId=${encodeURIComponent(n)}`,a=await fetch(`${r}/tasks/${encodeURIComponent(e)}?${i}`,{method:`DELETE`});return a.ok?`deleted`:a.status===404||a.status===405?`missing`:`failed`}catch{return`failed`}}async function zZ(e,t,n,r){if(!IZ(r))return null;try{let r=t.replace(/\/$/,``),i=await fetch(`${r}/tasks?groupId=${encodeURIComponent(e)}&subscriberId=${encodeURIComponent(n)}`,{method:`GET`});if(!i.ok||typeof i.json!=`function`)return null;let a=await i.json();return Array.isArray(a)?a.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`string`&&typeof e.schedule==`string`&&typeof e.prompt==`string`).map(t=>({id:t.id,groupId:t.group_id||t.groupId||e,schedule:t.schedule,type:t.type,prompt:t.prompt,tools:PZ(t.tools),channel:typeof t.channel==`string`?t.channel:void 0,enabled:t.enabled===!0||t.enabled===1,lastRun:typeof t.lastRun==`number`?t.lastRun:typeof t.last_run==`number`?t.last_run:null,createdAt:typeof t.createdAt==`number`?t.createdAt:typeof t.created_at==`number`?t.created_at:Date.now(),name:typeof t.name==`string`?t.name:void 0,order:typeof t.order==`number`?t.order:typeof t.task_order==`number`?t.task_order:void 0})):null}catch{return null}}function BZ(e,t){let n=(e?.inputTokens??0)+(t.inputTokens??0),r=(e?.outputTokens??0)+(t.outputTokens??0),i=(e?.cacheReadTokens??0)+(t.cacheReadTokens??0),a=(e?.cacheCreationTokens??0)+(t.cacheCreationTokens??0);return{groupId:t.groupId||e?.groupId||``,inputTokens:n,outputTokens:r,cacheReadTokens:i,cacheCreationTokens:a,totalTokens:n+r+i+a,contextLimit:t.contextLimit||e?.contextLimit||0}}var VZ=class e{static DEFAULT_PAGE_PATH=`MEMORY.md`;orchestrator;_activeGroupId;_activePage;_activePinnedPage;_defaultPinnedPage;_activityLog;_activityLogSessionStartedAtByGroup;_aguiAdapter;_aguiEvent;_contextUsage;_currentPath;_db;_error;_files;_gitProxyUrl;_groups;_hadPersistedActivePage;_initResolve;_isTyping;_lastOrchestratorDisplayState=`idle`;_messages;_modelDownloadProgress;_onlineReplayHandler;_pages;_peerStateByGroup;_proxyUrl;_ready;_remoteAgentStatusByGroup;_remoteAgentTypingByGroup;_replayingTaskSyncOutbox;_subscriberId;_sidebarDefaultPage;_state;_storageStatus;_streamingText;_tasks;_taskSyncOutbox;_tokenUsage;_tokenUsageAccumulator=null;_toolActivity;_unreadGroupIds;_useProxy;_vmBashFullInternetAccess;_whenInitialized;_whenReady;_readyResolve;constructor(){this._messages=new jG.State([]),this._isTyping=new jG.State(!1),this._storageStatus=new jG.State(null),this._toolActivity=new jG.State(null),this._modelDownloadProgress=new jG.State(null),this._activityLog=new jG.State([]),this._state=new jG.State(`idle`),this._tokenUsage=new jG.State(null),this._error=new jG.State(null),this._activeGroupId=new jG.State(w),this._ready=new jG.State(!1),this._tasks=new jG.State([]),this._files=new jG.State([]),this._currentPath=new jG.State(`.`),this._groups=new jG.State([]),this._unreadGroupIds=new jG.State(new Set),this._streamingText=new jG.State(null),this._aguiEvent=new jG.State(null),this._contextUsage=new jG.State(null),this._useProxy=new jG.State(!1),this._proxyUrl=new jG.State(`/proxy`),this._gitProxyUrl=new jG.State(`/git-proxy`),this._vmBashFullInternetAccess=new jG.State(!1),this._activePage=new jG.State(`pages`),this._sidebarDefaultPage=new jG.State(`chat`),this._pages=new jG.State([]),this._activePinnedPage=new jG.State(null),this._defaultPinnedPage=new jG.State(null),this._remoteAgentStatusByGroup=new jG.State(new Map),this._remoteAgentTypingByGroup=new jG.State(new Map),this._peerStateByGroup=new jG.State(new Map),this._hadPersistedActivePage=!1,this._initResolve=null,this._whenInitialized=new Promise(e=>{this._initResolve=e}),this._readyResolve=null,this._whenReady=new Promise(e=>{this._readyResolve=e}),this.orchestrator=null,this._db=null,this._activityLogSessionStartedAtByGroup=new Map,this._taskSyncOutbox=[],this._replayingTaskSyncOutbox=!1,this._subscriberId=null,this._onlineReplayHandler=null,this._aguiAdapter=null}get activeGroupId(){return this._activeGroupId.get()}get activePage(){return this._activePage.get()}get activePinnedPage(){return this._activePinnedPage.get()}get defaultPinnedPage(){return this._defaultPinnedPage.get()}get effectiveDefaultPage(){return this._pages.get()[0]||null}get activityLog(){return this._activityLog.get()}get aguiEvent(){return this._aguiEvent.get()}clearError(){this._error.set(null),this._state.get()===`error`&&this._state.set(`idle`)}get contextUsage(){return this._contextUsage.get()}get tokenUsageAccumulator(){return this._tokenUsageAccumulator}get currentPath(){return this._currentPath.get()}get error(){return this._error.get()}get files(){return this._files.get()}getPeerState(e){return this._peerStateByGroup.get().get(e)||null}getRemoteAgentStatus(e){return this._remoteAgentStatusByGroup.get().get(e)||`idle`}getState(){return{messages:this.messages,isTyping:this.isTyping,toolActivity:this.toolActivity,activityLog:this.activityLog,state:this.state,tokenUsage:this.tokenUsage,modelDownloadProgress:this.modelDownloadProgress,error:this.error,activeGroupId:this.activeGroupId,pages:this.pages,ready:this.ready,files:this.files,currentPath:this.currentPath,streamingText:this.streamingText,contextUsage:this.contextUsage}}getTasksForBackup(){return this._tasks.get()}get gitProxyUrl(){return this._gitProxyUrl.get()}get groups(){return this._groups.get()}get hadPersistedActivePage(){return this._hadPersistedActivePage}isRemoteAgentTyping(e){return this._remoteAgentTypingByGroup.get().get(e)||!1}get isTyping(){return this._isTyping.get()}get messages(){return this._messages.get()}get modelDownloadProgress(){return this._modelDownloadProgress.get()}get pages(){return this._pages.get()}get proxyUrl(){return this._proxyUrl.get()}get ready(){return this._ready.get()}sendMessage(e,t=[],n){n===void 0?this.orchestrator?.browserChat?.submit(e,this._activeGroupId.get(),t):this.orchestrator?.browserChat?.submit(e,this._activeGroupId.get(),t,n)}setActiveGroup(e,t,n=this._activePage.get()===`chat`){if(this._activeGroupId.set(t),this._messages.set([]),this._activityLog.set([]),this._error.set(null),this._isTyping.set(!1),this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null),this._currentPath.set(`.`),n){let e=new Set(this._unreadGroupIds.get());e.delete(t)&&this._unreadGroupIds.set(e)}this.loadHistory(),this.loadTasks(e),this.loadFiles(e)}setReady(e=!0){this._ready.set(e),e&&this._readyResolve&&this._readyResolve()}setRemoteAgentStatus(e,t){let n=this._remoteAgentStatusByGroup.get(),r=new Map(n);r.set(e,t),this._remoteAgentStatusByGroup.set(r)}setRemoteAgentTyping(e,t){let n=this._remoteAgentTypingByGroup.get(),r=new Map(n);t?r.set(e,!0):r.delete(e),this._remoteAgentTypingByGroup.set(r)}get sidebarDefaultPage(){return this._sidebarDefaultPage.get()}get state(){return this._state.get()}stopCurrentRequest(){this.orchestrator?.stopCurrentRequest?.(this._activeGroupId.get())}get storageStatus(){return this._storageStatus.get()}get streamingText(){return this._streamingText.get()}syncHostWorkspaceToVM(){VX(this.orchestrator,this._activeGroupId.get())}syncVMWorkspaceToHost(){HX(this.orchestrator,this._activeGroupId.get())}get tasks(){return this._tasks.get()}get tokenUsage(){return this._tokenUsage.get()}get toolActivity(){return this._toolActivity.get()}get unreadGroupIds(){return this._unreadGroupIds.get()}get useProxy(){return this._useProxy.get()}get vmBashFullInternetAccess(){return this._vmBashFullInternetAccess.get()}get whenInitialized(){return this._whenInitialized}async resetSiteConfigSeed(e){await U(e,j.SITE_CONFIG_SEEDED,!1)}get whenReady(){return this._whenReady}async addPage(e,t,n=this._activeGroupId.get()){let r=n===`br:main`?this.normalizePagePath(t):t.trim();if(!r)return;let i=this._pages.get();i.some(e=>e.path===r&&e.groupId===n)||(this.setPages([...i,{groupId:n,path:r}]),await mZ(e,n,r),n===`br:main`&&r===`MEMORY.md`&&await NW(e,!1),await this.persistPages(e))}async clearAllTasks(e){let t=await hX(e),n=this._activeGroupId.get(),r=t.filter(e=>e.groupId===n),i=await this.getSubscriberId(e);for(let t of r){if(await RZ(t.id,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)===`failed`){console.warn(`Failed to delete task "${t.id}" from server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`delete`,id:t.id,queuedAt:Date.now()});continue}await mX(e,t.id)}await this.loadTasks(e)}async cloneConversation(e,t){let n=await iK(e,t);if(!n)return null;await YX(e,t,n.groupId),await XX(e,t,n.groupId);try{let r=await we(e,t,`MEMORY.md`);r&&await Nn(e,n.groupId,`MEMORY.md`,r)}catch{}try{await eZ(e,t,n.groupId,`attachments`)}catch{}return await this.loadGroups(e),this.setActiveGroup(e,n.groupId),n}async compactContext(e){if(this.orchestrator)return BX(this.orchestrator,e,this._activeGroupId.get())}async createConversation(e,t){let n=await QG(e,t);return await this.loadGroups(e),this.setActiveGroup(e,n.groupId),n}async deleteConversation(e,t){if(!(this._groups.get().length<=1)&&(await tK(e,t),await JX(e,t),await this.loadGroups(e),this._activeGroupId.get()===t)){let t=this._groups.get()[0]?.groupId||`br:main`;this.setActiveGroup(e,t)}}async deleteMessage(e,t){await ZX(e,t),await this.loadHistory(),this.orchestrator?.refreshContextUsage&&await this.orchestrator.refreshContextUsage(e,this._activeGroupId.get())}async deleteTask(e,t){let n=await this.getSubscriberId(e);if(await RZ(t,this.getTaskServerBaseUrl(),n,this.orchestrator?.taskServerEnabled??!1)===`failed`)throw console.warn(`Failed to delete task from server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`delete`,id:t,queuedAt:Date.now()}),Error(`Failed to delete scheduled task on server; task kept locally.`);await mX(e,t),await this.loadTasks(e)}async ensurePeerConversation(e,t){let n=`peer:${t}`,r=await nK(e);if(!r.find(e=>e.groupId===n)){let i=[...r],a=``;if(this.orchestrator?.peerjsPeerAliases){for(let[e,n]of Object.entries(this.orchestrator.peerjsPeerAliases))if(n===t){a=e;break}}i.push({groupId:n,name:`Peer: ${a||t.substring(0,8)}`,createdAt:Date.now()}),await ZG(e,i),await this.loadGroups(e)}return n}async grantStorageAccess(e){try{await iZ(e),await this.loadFiles(e)}catch(e){console.error(`Failed to grant storage access:`,e)}}async init(e,t){this._db=e,this.orchestrator=t,this._taskSyncOutbox=this.parseTaskSyncOutbox(await F(e,j.TASK_SYNC_OUTBOX)),await this.replayTaskSyncOutbox(e),typeof window<`u`&&!this._onlineReplayHandler&&(this._onlineReplayHandler=()=>{this._db&&this.replayTaskSyncOutbox(this._db)},window.addEventListener(`online`,this._onlineReplayHandler)),t.events.on(`a2ui-surface`,async({groupId:t,envelope:n})=>{t&&this.ensureGroupExists(e,t);let r=this._messages.get(),i=r.findIndex(e=>e.a2uiEnvelopes?.some(e=>e.surfaceId===n.surfaceId));if(i!==-1){let t=r[i],a=[...t.a2uiEnvelopes||[],n],o={...t,a2uiEnvelopes:a},s=[...r];s[i]=o,this._messages.set(s),await sX(e,o)}else{let i=!t.startsWith(`peer:`),a={id:dr(),groupId:t,sender:i?`agent`:t.replace(/^peer:/,``),content:``,timestamp:Date.now(),channel:t.startsWith(`peer:`)?`peerjs`:`browser`,isFromMe:i,isTrigger:!1,a2uiEnvelopes:[n]};t===this._activeGroupId.get()&&this._messages.set([...r,a]),await sX(e,a)}}),t.events.on(`message`,t=>{if(t.groupId&&this.ensureGroupExists(e,t.groupId,t.timestamp),t.groupId&&t.groupId!==this._activeGroupId.get()){let e=new Set(this._unreadGroupIds.get());e.add(t.groupId),this._unreadGroupIds.set(e);return}t.isFromMe&&this._streamingText.get()!==null&&this._streamingText.set(null),this._messages.set([...this._messages.get(),t])}),t.events.on(`typing`,({groupId:e,typing:t})=>{e&&e!==this._activeGroupId.get()||this._isTyping.set(t)}),t.events.on(`tool-activity`,({groupId:e,tool:t,status:n})=>{e&&e!==this._activeGroupId.get()||this._toolActivity.set(n===`running`?{tool:t,status:n}:null)}),t.events.on(`model-download-progress`,e=>{this._modelDownloadProgress.set(e.status===`done`?null:e)}),t.events.on(`thinking-log`,e=>{e.groupId&&e.groupId!==this._activeGroupId.get()||(e.level===`info`&&e.label===`Starting`?this._activityLog.set([e]):this._activityLog.set([...this._activityLog.get(),e]),this.forwardActivityLogEntryToServer(e))}),t.events.on(`state-change`,e=>{let t=typeof e==`string`?e:e.state,n=typeof e==`string`?void 0:e.groupId;if(n&&n!==this._activeGroupId.get())return;let r=this._lastOrchestratorDisplayState;this._lastOrchestratorDisplayState=t,this._state.set(t),t===`idle`&&(this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null)),t===`thinking`&&r!==`thinking`&&r!==`responding`&&(this._tokenUsageAccumulator=null)}),t.events.on(`error`,({error:e})=>{console.error(`[Orchestrator Error Event]`,e),this._error.set(e),this._state.set(`error`)}),t.events.on(`session-reset`,()=>{this._messages.set([]),this._activityLog.set([]),this._tokenUsageAccumulator=null,this._tokenUsage.set(null),this._contextUsage.set(null),this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null),this._isTyping.set(!1),this._state.set(`idle`)}),t.events.on(`context-compacted`,e=>{e?.groupId&&e.groupId!==this._activeGroupId.get()||(this._tokenUsage.set(null),this.loadHistory())}),t.events.on(`token-usage`,e=>{if(!e||e.groupId&&e.groupId!==this._activeGroupId.get())return;let t=BZ(this._tokenUsageAccumulator,e);this._tokenUsageAccumulator=t,this._tokenUsage.set(t),this.orchestrator?.refreshContextUsage&&this._db&&this.orchestrator.refreshContextUsage(this._db,this._activeGroupId.get())}),t.events.on(`context-usage`,e=>{this._contextUsage.set(e)}),t.events.on(`ready`,()=>{this._ready.set(!0)}),t.events.on(`task-change`,()=>{this.loadTasks(e)}),t.events.on(`file-change`,()=>{this.loadFiles(e)}),t.events.on(`streaming-start`,({groupId:e})=>{e===this._activeGroupId.get()&&this._streamingText.set(``)}),t.events.on(`streaming-chunk`,({groupId:e,text:t})=>{if(e!==this._activeGroupId.get())return;let n=this._streamingText.get();this._streamingText.set((n||``)+t)}),t.events.on(`streaming-end`,({groupId:e})=>{e===this._activeGroupId.get()&&this._streamingText.set(null)}),t.events.on(`streaming-done`,({groupId:e})=>{this._activeGroupId.get()}),t.events.on(`streaming-error`,({groupId:e})=>{this._activeGroupId.get()}),this._aguiAdapter=new OZ(t.events),this._aguiAdapter.start(),typeof window<`u`&&window.addEventListener(`shadow-claw-agui-event`,(e=>{e.detail.groupId===this._activeGroupId.get()&&this._aguiEvent.set(e.detail);let t=e.detail.event;if(t){if(t.type===`STATE_SNAPSHOT`){let n=new Map(this._peerStateByGroup.get());n.set(e.detail.groupId,t.snapshot||{}),this._peerStateByGroup.set(n)}else if(t.type===`STATE_DELTA`){let n=new Map(this._peerStateByGroup.get()),r=kZ(n.get(e.detail.groupId)||{},t.delta||[]);n.set(e.detail.groupId,r),this._peerStateByGroup.set(n)}}})),await hn(e),vn(),yn();let n=await F(e,j.PAGES_LIST),r=await DZ(e,w,n==null?[]:this.parsePagesList(n));r.length>0?(this.setPages(r),await this.persistPages(e)):await this.ensureDefaultPage(e),await this.applySiteConfigDefaults(e),await this.loadGroups(e);let i=await F(e,j.LAST_ACTIVE_GROUP);i&&i!==this._activeGroupId.get()&&this._activeGroupId.set(i);let a=await F(e,j.LAST_ACTIVE_PAGE);a&&(this._activePage.set(a),this._hadPersistedActivePage=!0);let o=await F(e,j.SIDEBAR_DEFAULT_PAGE);this._sidebarDefaultPage.set(this.normalizeSidebarDefaultPage(o));let s=await F(e,j.LAST_SELECTED_PINNED_PAGE);if(s)try{let e=JSON.parse(s);e&&typeof e.path==`string`&&typeof e.groupId==`string`&&this._activePinnedPage.set(e)}catch{}this.orchestrator&&(this._useProxy.set(this.orchestrator.useProxy),this._proxyUrl.set(this.orchestrator.proxyUrl),this._gitProxyUrl.set(this.orchestrator.gitProxyUrl),this._vmBashFullInternetAccess.set(this.orchestrator.vmBashFullInternetAccess)),await Promise.all([this.loadHistory(),this.loadTasks(e),this.loadFiles(e)]),this._initResolve?.(),this.scheduleBackgroundStaticMainSiteSeeding(e)}async loadFiles(e){let t=this._activeGroupId.get(),n=this._currentPath.get();try{this._storageStatus.set(await R(e));let r=await nZ(e,t,n);this._files.set(r)}catch(e){console.error(`Failed to load files in store:`,e)}}async loadGroups(e){let t=await nK(e);this._groups.set(t)}async loadHistory(){let e=this._activeGroupId.get(),t=await UG(e,200);this._activeGroupId.get()===e&&this._messages.set(t)}async loadTasks(e){let t=this._activeGroupId.get(),n=await hX(e),r=n.filter(e=>e.groupId===t);r.sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?e.createdAt-t.createdAt:n-r}),this._tasks.set(r);let i=await this.getSubscriberId(e),a=await zZ(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1);if(!a)return;let o=new Set(n.map(e=>e.id)),s=a.filter(e=>!o.has(e.id));if(s.length===0)return;for(let t of s)await bX(e,t);let c=[...r,...s];c.sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?e.createdAt-t.createdAt:n-r}),this._tasks.set(c)}async navigateBackFolder(e){let t=this._currentPath.get();if(t===`.`)return;let n=t.split(`/`).filter(Boolean);n.pop();let r=n.length===0?`.`:n.join(`/`);await this.setCurrentPath(e,r)}async navigateIntoFolder(e,t){let n=this._currentPath.get(),r=n===`.`?t.replace(/\/$/,``):`${n}/${t.replace(/\/$/,``)}`;try{await this.setCurrentPath(e,r)}catch(t){console.error(`Failed to navigate into folder in store:`,t),DX(`Folder not found: ${r}`,4500),await this.loadFiles(e)}}async newSession(e){await this.orchestrator?.newSession?.(e,this._activeGroupId.get()),await this.loadHistory()}async removePage(t,n,r=this._activeGroupId.get()){let i=this.normalizePagePath(n);if(!i)return;let a=this._pages.get();if(!a.some(e=>e.path===i&&e.groupId===r))return;let o=a.filter(e=>!(e.path===i&&e.groupId===r));await pZ(t,r,i);let s=r===`br:main`&&i===`MEMORY.md`;s&&await NW(t,!0);let c=s||await MW(t);if(o.length===0&&!c)if(await PW(t,`br:main`))o.push({groupId:w,path:e.DEFAULT_PAGE_PATH});else return;this.setPages(o);let l=this._defaultPinnedPage.get();l&&l.path===i&&l.groupId===r&&await this.setDefaultPinnedPage(t,null),await this.persistPages(t)}async removeAllPages(e){let t=[...this._pages.get()];for(let n of t)await pZ(e,n.groupId,n.path),n.groupId===`br:main`&&n.path===`MEMORY.md`&&await NW(e,!0);this.setPages([]),await this.setDefaultPinnedPage(e,null),await this.setActivePinnedPage(e,null),await this.persistPages(e)}async renameConversation(e,t,n){await $G(e,t,n),await this.loadGroups(e)}async reorderConversations(e,t){await rK(e,t),await this.loadGroups(e)}async reorderTasks(e,t,n){let r=await $X(e,t,n);await this.loadTasks(e);let i=await this.getSubscriberId(e);for(let t of r)await LZ(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to sync reordered task "${t.id}" to server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:t.id,task:t,queuedAt:Date.now()}))}async replayTaskSyncOutbox(e){if(!(this._replayingTaskSyncOutbox||this._taskSyncOutbox.length===0)){this._replayingTaskSyncOutbox=!0;try{let t=await this.getSubscriberId(e),n=[];for(let e of this._taskSyncOutbox){let r=this.getTaskServerBaseUrl();(e.type===`upsert`?await LZ(e.task,r,t,this.orchestrator?.taskServerEnabled??!1):await RZ(e.id,r,t,this.orchestrator?.taskServerEnabled??!1))||n.push(e)}this._taskSyncOutbox=this.compactTaskSyncOutbox(n),await this.persistTaskSyncOutbox(e)}finally{this._replayingTaskSyncOutbox=!1}}}async resetToRootFolder(e){await this.setCurrentPath(e,`.`)}async restartCurrentRequest(){return this.orchestrator?.restartCurrentRequest?this.orchestrator.restartCurrentRequest(this._activeGroupId.get()):!1}async restoreTasksFromBackup(e,t){await this.clearAllTasks(e);let n=this._activeGroupId.get();for(let r of t){let t={...r,groupId:n,id:crypto.randomUUID?crypto.randomUUID():`task-${Date.now()}-${Math.random()}`};await this.upsertTask(e,t,{reloadTasks:!1})}await this.loadTasks(e)}async runTask(e,t=!1){let n=this._db;if(t&&n&&(await QX(e.id,Date.now()),await this.loadTasks(n)),e.type===`tools`&&Array.isArray(e.tools)&&e.tools.length>0)if(this.orchestrator?.agentWorker){let n=e.subagent?`subagent:${dr()}`:e.groupId;this.orchestrator.agentWorker.postMessage({type:`execute-task-tools`,payload:{groupId:n,tools:e.tools,isManual:t}})}else console.error(`Agent worker not available to execute tool task.`);else{if(!e.groupId){console.error(`Task ${e.id} has no groupId - refusing to execute in active conversation to prevent context pollution.`);return}this.orchestrator?.browserChat?.submit(e.prompt,e.groupId,[],void 0,e.freshContext,e.subagent)}}async setActivePage(e,t){this._activePage.set(t),await U(e,j.LAST_ACTIVE_PAGE,t);let n=this.resolveSidebarDefaultPageForActivePage(t);n!==this._sidebarDefaultPage.get()&&(this._sidebarDefaultPage.set(n),await U(e,j.SIDEBAR_DEFAULT_PAGE,n))}async setActivePinnedPage(e,t){this._activePinnedPage.set(t),t?await U(e,j.LAST_SELECTED_PINNED_PAGE,JSON.stringify(t)):await U(e,j.LAST_SELECTED_PINNED_PAGE,null)}async setDefaultPinnedPage(e,t){let n=this._defaultPinnedPage.get(),r=n&&t&&n.path===t.path&&n.groupId===t.groupId?null:t;this._defaultPinnedPage.set(r),r?await U(e,j.DEFAULT_PINNED_PAGE,JSON.stringify(r)):await U(e,j.DEFAULT_PINNED_PAGE,null)}async reorderPages(e,t){this.setPages(t),await this.persistPages(e)}async setCurrentPath(e,t){let n=t.replace(/^\/+|\/+$/g,``)||`.`,r=this._activeGroupId.get();this._storageStatus.set(await R(e));let i=await nZ(e,r,n);this._currentPath.set(n),this._files.set(i)}async setGitProxyUrl(e,t){this.orchestrator&&(await WX(this.orchestrator,e,t),this._gitProxyUrl.set(this.orchestrator.gitProxyUrl))}async setProxyUrl(e,t){this.orchestrator&&(await GX(this.orchestrator,e,t),this._proxyUrl.set(this.orchestrator.proxyUrl))}async setUseProxy(e,t){this.orchestrator&&(await KX(this.orchestrator,e,t),this._useProxy.set(this.orchestrator.useProxy))}async setVMBashFullInternetAccess(e,t){this.orchestrator&&(await qX(this.orchestrator,e,t),this._vmBashFullInternetAccess.set(this.orchestrator.vmBashFullInternetAccess))}async switchConversation(e,t,n){this.setActiveGroup(e,t,n??this._activePage.get()===`chat`),await U(e,j.LAST_ACTIVE_GROUP,t)}async toggleTask(e,t,n){let r={...t,enabled:n};await bX(e,r),await this.loadTasks(e),await LZ(r,this.getTaskServerBaseUrl(),await this.getSubscriberId(e),this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to update task on server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:r.id,task:r,queuedAt:Date.now()}))}async updateConversationPinnedProvider(e,t,n,r,i){await aK(e,t,n,r,i),await this.loadGroups(e)}async updateConversationProviderRuntimeOverrides(e,t,n){await sK(e,t,n),await this.loadGroups(e)}async updateConversationSubagentSettings(e,t,n,r,i,a){await oK(e,t,n,r,i,a),await this.loadGroups(e)}async updateConversationToolTags(e,t,n){await eK(e,t,n),await this.loadGroups(e)}async upsertTask(e,t,n){let r=n?.reloadTasks!==!1;await bX(e,t),r&&await this.loadTasks(e);let i=await this.getSubscriberId(e);await LZ(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to sync task to server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:t.id,task:t,queuedAt:Date.now()}))}compactTaskSyncOutbox(e){let t=new Map;return e.forEach((e,n)=>{t.set(e.id,n)}),e.filter((e,n)=>t.get(e.id)===n)}deriveGroupName(e){return e.startsWith(`tg:`)?`Telegram ${e.slice(3)}`:e.startsWith(`im:`)?`iMessage ${e.slice(3)}`:e.startsWith(`br:`)?e===`br:main`?`Main`:`Browser Conversation`:`Conversation`}getActivityLogSessionStartedAt(e){let t=this._activityLogSessionStartedAtByGroup.get(e);if(t)return t;let n=new Date().toISOString();return this._activityLogSessionStartedAtByGroup.set(e,n),n}getTaskServerBaseUrl(){return this.orchestrator?.taskServerUrl??`/schedule`}async getSubscriberId(e){if(this._subscriberId)return this._subscriberId;let t=await _X(e);return this._subscriberId=t,t}normalizePagePath(t){let n=t.trim().replace(/^\/+/,``).replace(/\/+/g,`/`);return n===`main/memory.md`?e.DEFAULT_PAGE_PATH:n}normalizeSidebarDefaultPage(e){return e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:`chat`}parsePagesList(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.map(e=>{if(typeof e==`string`)return{groupId:w,path:this.normalizePagePath(e)};if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.path!=`string`)return null;let n=typeof t.groupId==`string`&&t.groupId.trim().length>0?t.groupId:w,r=n===`br:main`?this.normalizePagePath(t.path):t.path.trim();return r?{groupId:n,path:r}:null}).filter(e=>!!e).filter((e,t,n)=>{let r=`${e.groupId}\u0000${e.path}`;return t===n.findIndex(e=>`${e.groupId}\u0000${e.path}`===r)}):[]}catch{return[]}}parseTaskSyncOutbox(e){if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let n=t.filter(e=>!!e&&typeof e==`object`).filter(e=>e.type===`upsert`||e.type===`delete`).filter(e=>typeof e.id==`string`&&e.id.length>0).map(e=>({...e,queuedAt:typeof e.queuedAt==`number`?e.queuedAt:Date.now()}));return this.compactTaskSyncOutbox(n)}catch{return[]}}resolveSidebarDefaultPageForActivePage(e){return e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:this._sidebarDefaultPage.get()}setPages(e){let t=e.filter(e=>e.path.toLowerCase()===`memory.md`),n=e.filter(e=>e.path.toLowerCase()!==`memory.md`);this._pages.set([...n,...t])}async ensureDefaultPage(t){if(await MW(t))return;let n=await PW(t,w);await zW(t,w),!(!n||this._pages.get().length>0)&&(this.setPages([{groupId:w,path:e.DEFAULT_PAGE_PATH}]),await this.persistPages(t))}async ensureGroupExists(e,t,n){let r=this._groups.get();if(r.some(e=>e.groupId===t))return;let i=[...r,{groupId:t,name:this.deriveGroupName(t),createdAt:n||Date.now()}];this._groups.set(i);try{await ZG(e,i)}catch(e){console.error(`Failed to persist new conversation metadata:`,e)}}async forwardActivityLogEntryToServer(e){if(!this._db||!FZ(await F(this._db,j.ACTIVITY_LOG_DISK_LOGGING_ENABLED)))return;let t=typeof e.groupId==`string`&&e.groupId?e.groupId:this._activeGroupId.get();if(!t)return;let n=typeof e.message==`string`?e.message.trim():``;if(!n)return;e.level===`info`&&e.label===`Starting`&&this._activityLogSessionStartedAtByGroup.set(t,new Date().toISOString());let r=this.getActivityLogSessionStartedAt(t);try{await fetch(`/activity-log`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({groupId:t,level:e.level,label:e.label,message:n,timestamp:new Date().toISOString(),sessionStartedAt:r})})}catch(e){console.warn(`Failed to persist activity log entry to server:`,e)}}scheduleBackgroundStaticMainSiteSeeding(e){if(typeof window>`u`)return;let t=async()=>{try{if(await gZ(e,`br:main`))return;let t=await F(e,j.PAGES_LIST),n=await DZ(e,w,t==null?[]:this.parsePagesList(t),{preferEmbedded:!1});n&&n.length>0&&(this.setPages(n),await this.persistPages(e))}catch(e){console.warn(`Background static main site seeding failed:`,e)}};typeof window.requestIdleCallback==`function`?window.requestIdleCallback(()=>void t(),{timeout:3e3}):setTimeout(()=>void t(),100)}async persistPages(e){await U(e,j.PAGES_LIST,JSON.stringify(this._pages.get()))}async persistTaskSyncOutbox(e){await U(e,j.TASK_SYNC_OUTBOX,JSON.stringify(this._taskSyncOutbox))}async queueTaskSyncOutboxOperation(e,t){this._taskSyncOutbox=this.compactTaskSyncOutbox([...this._taskSyncOutbox,t]),await this.persistTaskSyncOutbox(e)}async applySiteConfigDefaults(e){if(!(typeof document>`u`))try{let t=document.getElementById(`shadow-claw-site-config`);if(!t?.textContent)return;let n=JSON.parse(t.textContent);if(!n||typeof n!=`object`)return;pn(n),vn(),yn();let r=n.customElements;if((await nK(e)).find(e=>e.groupId===`br:main`)?.toolTags&&await eK(e,w,void 0),await F(e,j.SITE_CONFIG_SEEDED))return;let i=n.allowedCustomElements||(typeof r==`object`&&!Array.isArray(r)?r.allowedElements:void 0);i!==void 0&&await U(e,j.ALLOWED_CUSTOM_ELEMENTS,JSON.stringify(i));let a=n.allowedCustomElementDomains||(typeof r==`object`&&!Array.isArray(r)?r.allowedDomains:void 0);if(a!==void 0&&await U(e,j.ALLOWED_CUSTOM_ELEMENT_HOST_PATTERNS,JSON.stringify(a)),n.sidebar&&typeof n.sidebar==`object`){let{pagesHidden:t,chatHidden:r,tasksHidden:i,filesHidden:a,defaultPage:o}=n.sidebar;t!==void 0&&await U(e,j.SIDEBAR_PAGES_HIDDEN,String(!!t)),r!==void 0&&await U(e,j.SIDEBAR_CHAT_HIDDEN,String(!!r)),i!==void 0&&await U(e,j.SIDEBAR_TASKS_HIDDEN,String(!!i)),a!==void 0&&await U(e,j.SIDEBAR_FILES_HIDDEN,String(!!a)),o&&typeof o==`string`&&await U(e,j.SIDEBAR_DEFAULT_PAGE,o)}if(n.settings&&typeof n.settings==`object`){let{assistantName:t}=n.settings;t&&typeof t==`string`&&await U(e,j.ASSISTANT_NAME,t)}let o=(n.settings&&typeof n.settings==`object`?n.settings.defaultToolsProfile:void 0)??n.defaultToolsProfile;if(typeof o==`string`&&o.trim().length>0){let t=o.trim();if(t.toLowerCase()===`none`)await Hq.deactivateProfile(e);else{let n=Hq.profiles.find(e=>e.id.toLowerCase()===t.toLowerCase()||e.name.toLowerCase()===t.toLowerCase());n?await Hq.activateProfile(e,n.id):console.warn(`Default tools profile "${t}" specified in site-config was not found.`)}}if(n.pages&&typeof n.pages==`object`){let{defaultPinnedPage:t}=n.pages;t&&typeof t==`string`&&await U(e,j.DEFAULT_PINNED_PAGE,t)}if(Array.isArray(n.enabledTools)){let t=n.enabledTools.filter(e=>typeof e==`string`&&e.trim().length>0);await Hq.setAllEnabled(e,t),await Hq.setAllDeclarativeEnabled(e,t)}await U(e,j.SITE_CONFIG_SEEDED,`true`)}catch(e){console.warn(`Failed to apply site-config defaults:`,e)}}};const HZ=new VZ;async function UZ(e,t,n){let r=await z(e,t),{dirs:i,filename:a}=Ce(n),o=r;for(let e of i)o=await o.getDirectoryHandle(e);await o.removeEntry(a),t===`br:main`&&i.length===0&&(a===`MEMORY.md`?await NW(e,!0):a===`index.html`&&await RW(e,!0));try{await pZ(e,t,n)}catch{}try{await HZ.removePage(e,n,t)}catch{}}async function WZ(e,t,n){let r=n.replace(/\\/g,`/`).replace(/^\/home\/user\//,`/`).replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean);if(r.length===0)throw Error(`Empty directory path`);for(let n=0;n<2;n++)try{let n=await z(e,t);for(let e of r)n=await n.getDirectoryHandle(e,{create:!0});return}catch(e){if(n===0&&Se(e)){L();continue}throw e}}var GZ=class extends jR{db;groupId;workspacePrefix;constructor(e,t,n,r=`/home/user`){super(n),this.db=e,this.groupId=t,this.workspacePrefix=r}async appendFile(e,t){await super.appendFile(e,t);let n=this._toDbPath(e);if(n!==null){let t=await this._readPathContent(e);await Nn(this.db,this.groupId,n,t)}}async cp(e,t,n){await super.cp(e,t,n);let r=this._toDbPath(t);if(r!==null)try{let e=await super.stat(t);if(!this._isDirectoryStat(e)){let e=await this._readPathContent(t);await Nn(this.db,this.groupId,r,e)}}catch{}}async mkdir(e,t){await super.mkdir(e,t);let n=this._toDbPath(e);n!==null&&n!==``&&await WZ(this.db,this.groupId,n)}async mv(e,t){await super.mv(e,t);let n=!1,r=t,i=this._toDbPath(t);if(i!==null)try{let i=await super.stat(t);if(this._isDirectoryStat(i)){let n=this._basename(e);n&&(r=this._joinPath(t,n))}let a=await super.stat(r);if(!this._isDirectoryStat(a)){let e=this._toDbPath(r);if(e!==null){let t=await this._readPathContent(r);await Nn(this.db,this.groupId,e,t),n=!0}}}catch{}let a=this._toDbPath(e);if(a!==null)try{(i===null||n)&&await UZ(this.db,this.groupId,a)}catch{}}async rm(e,t){await super.rm(e,t);let n=this._toDbPath(e);if(n!==null)try{await UZ(this.db,this.groupId,n)}catch{}}async writeFile(e,t,n){await super.writeFile(e,t,n);let r=this._toDbPath(e);if(r!==null){let t=await this._readPathContent(e);await Nn(this.db,this.groupId,r,t)}}_basename(e){let t=e.split(`/`).filter(Boolean);return t[t.length-1]||``}_isDirectoryStat(e){return e&&typeof e.isDirectory==`function`?!!e.isDirectory():!!e?.isDirectory}_joinPath(e,t){let n=e.replace(/\/+$/,``);return n?`${n}/${t}`:`/${t}`}_toDbPath(e){return e.startsWith(this.workspacePrefix+`/`)?e.slice(this.workspacePrefix.length+1):e===this.workspacePrefix?``:null}async _readPathContent(e){try{return await super.readFileBuffer(e)}catch{return await super.readFile(e)}}};async function KZ(e,t){let n={},r=new Set,i=`/home/user`;async function a(o){let s=await nZ(e,t,o);for(let c of s)if(c.endsWith(`/`)){let e=c.slice(0,-1),t=o===`.`?e:`${o}/${e}`;r.add(t),await a(t)}else{let r=o===`.`?c:`${o}/${c}`,a=`${i}/${r}`;n[a]=async()=>{try{return await OW(e,t,r)}catch{return``}}}}await a(`.`);let o=new GZ(e,t,n,i);for(let e of[...r].sort((e,t)=>e.split(`/`).length-t.split(`/`).length))try{o.mkdirSync(`${i}/${e}`,{recursive:!0})}catch{}return o}async function qZ(e,t,n,r={},i=30,a=!1){try{let i=await new wW({fs:await KZ(e,n),network:{dangerouslyAllowFullInternetAccess:a,denyPrivateRanges:!a}}).exec(t,{env:{HOME:`/home/user`,PATH:`/usr/bin`,PWD:`/home/user`,...r}});return{stdout:i.stdout||``,stderr:i.stderr||``,exitCode:i.exitCode??0}}catch(e){return{stdout:``,stderr:e instanceof Error?e.message:String(e),exitCode:1}}}function JZ(e){let t=e.stdout||``;return e.stderr&&(t+=(t?`
2047
+ `),{type:`key-points`,format:`markdown`,length:`medium`});await e.handleCompactDone(t,n,r);return}catch(r){await dX(e,t,n,`⚠️ Built-in Task API compaction failed, falling back to provider: ${r instanceof Error?r.message:String(r)}`)}if(i===`prompt_api`){if(cY()||await ZJ(),!cY()){e.events.emit(`error`,{groupId:n,error:`Prompt API is not available in this browser. Switch provider or enable experimental browser flags.`}),e.events.emit(`typing`,{groupId:n,typing:!1}),e.setState(`idle`,n);return}let r=new AbortController;e.promptControllers.set(n,r);try{let i=await MY(aX(d),h,r.signal,async n=>{await RX(e,t,n)},n);await e.handleCompactDone(t,n,i)}catch(r){if(r instanceof Error&&r.name===`AbortError`)return;await dX(e,t,n,`⚠️ Error: Compaction failed: ${r instanceof Error?r.message:String(r)}`)}finally{e.promptControllers.delete(n)}return}let g=e.createProviderRequestId(n);e.agentWorker?.postMessage({type:`compact`,payload:{apiKey:s,assistantName:e.assistantName,contextCompression:e.contextCompressionEnabled,contextLimit:iX(f),groupId:n,memory:c,messages:h,model:a,provider:i,providerHeaders:kX(e,i,g,r?.providerRuntimeOverrides),rateLimitAutoAdapt:e.rateLimitAutoAdapt,rateLimitCallsPerMinute:e.rateLimitCallsPerMinute,storageHandle:await F(t,j.STORAGE_HANDLE),systemPrompt:d}})}function VX(e,t=w){e.agentWorker?.postMessage({payload:{groupId:t},type:`vm-workspace-sync`})}function HX(e,t=w){e.agentWorker?.postMessage({payload:{groupId:t},type:`vm-workspace-flush`})}function UX(e){`serviceWorker`in navigator&&navigator.serviceWorker?.controller&&navigator.serviceWorker.controller.postMessage({type:`set-proxy-config`,payload:{useProxy:e.useProxy,proxyUrl:e.proxyUrl}})}async function WX(e,t,n,r=U){e.gitProxyUrl=n||`/git-proxy`,await r(t,j.GIT_PROXY_URL,e.gitProxyUrl)}async function GX(e,t,n,r=U){e.proxyUrl=n||`/proxy`,await r(t,j.PROXY_URL,e.proxyUrl),UX(e)}async function KX(e,t,n,r=U){e.useProxy=!!n,await r(t,j.USE_PROXY,e.useProxy?`true`:`false`),UX(e)}async function qX(e,t,n,r=U){e.vmBashFullInternetAccess=!!n,await r(t,j.VM_BASH_FULL_INTERNET_ACCESS,e.vmBashFullInternetAccess?`true`:`false`)}function JX(e,t){return new Promise((n,r)=>{try{let i=e?.transaction(`messages`,`readwrite`);if(!i)return r(Error(`failed to get transaction, cannot clear group messages.`));let a=i.objectStore(`messages`).index(`by-group`).openCursor(t);a.onsuccess=()=>{let e=a.result;e?(e.delete(),e.continue()):n(void 0)},a.onerror=()=>r(a.error)}catch(e){r(e)}})}function YX(e,t,n){return new Promise((r,i)=>{let a=e?.transaction(`messages`,`readwrite`);if(!a)throw Error(`failed to get transaction, cannot clone messages.`);let o=a.objectStore(`messages`),s=o.index(`by-group`).openCursor(t),c=0;s.onsuccess=()=>{let e=s.result;if(e){let t={...e.value,id:dr(),groupId:n};o.put(t),c++,e.continue()}else r(c)},s.onerror=()=>i(s.error)})}function XX(e,t,n){return new Promise((r,i)=>{let a=e?.transaction(`tasks`,`readwrite`);if(!a)throw Error(`failed to get transaction, cannot clone tasks.`);let o=a.objectStore(`tasks`),s=o.index(`by-group`).openCursor(t),c=0;s.onsuccess=()=>{let e=s.result;if(e){let t={...e.value,id:dr(),groupId:n};o.put(t),c++,e.continue()}else r(c)},s.onerror=()=>i(s.error)})}function ZX(e,t){return ae(e,`messages`,`readwrite`,e=>e.delete(t)).then(()=>void 0)}function QX(e,t){return new Promise(async(n,r)=>{try{let i=await ie();if(!i)return r(Error(`failed to get transaction, cannot update task last run.`));let a=i.transaction(`tasks`,`readwrite`);if(!a)return r(Error(`failed to get transaction`));let o=a.objectStore(`tasks`),s=o.get(e);s.onsuccess=()=>{let e=s.result;if(!e){n();return}e.lastRun=t;let i=o.put(e);i.onsuccess=()=>n(),i.onerror=()=>r(i.error)},s.onerror=()=>r(s.error)}catch(e){r(e)}})}async function $X(e,t,n){let r=(await hX(e)).filter(e=>e.groupId===t),i=new Map(r.map(e=>[e.id,e])),a=[],o=0;for(let t of n){let n=i.get(t);n&&(n.order=o++,await bX(e,n),a.push(n),i.delete(t))}let s=Array.from(i.values()).sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?e.createdAt-t.createdAt:n-r});for(let t of s)t.order=o++,await bX(e,t),a.push(t);return a}async function eZ(e,t,n,r){let i=await z(e,t),a=await z(e,n),o=r.replace(/\\/g,`/`).replace(/^\/+/,``).split(`/`).filter(Boolean),s=i,c=a;for(let e of o)s=await s.getDirectoryHandle(e),c=await c.getDirectoryHandle(e,{create:!0});let l=n.replace(/:/g,`-`),u=[_e(),`groups`,l,...o];try{await tZ(e,n,s,c,u)}catch(e){throw o.length>0&&await a.removeEntry(o[0],{recursive:!0}).catch(()=>void 0),e}}async function tZ(e,t,n,r,i){for await(let[a,o]of n.entries()){if(o.kind===`directory`){await tZ(e,t,o,await r.getDirectoryHandle(a,{create:!0}),[...i,a]);continue}let n=await o.getFile(),s=await r.getFileHandle(a,{create:!0});try{await On(s,n)}catch(t){if(!((t instanceof Error?t.message:String(t)).includes(`Writable file streams are not supported`)&&(await R(e)).type===`opfs`))throw t;await kn([...i,a],n)}}}async function nZ(e,t,n=`.`){for(let r=0;r<2;r++)try{let r=await z(e,t);if(n&&n!==`.`){let e=n.replace(/\\/g,`/`).replace(/^\/home\/user\//,`/`).replace(/^\/+/,``).split(`/`).filter(Boolean);for(let t of e){let e=await r.getDirectoryHandle(t);if(typeof r.isSameEntry==`function`&&await r.isSameEntry(e))throw Error(`Directory navigation stuck at "${r.name}" for segment "${t}" — the stored directory handle may be stale.`);r=e}}let i=[];for await(let[e,t]of r.entries())i.push(t.kind===`directory`?`${e}/`:e);return i.sort()}catch(e){if(r===0&&Se(e)){L();continue}throw e}return[]}function rZ(e){if(!e||typeof e!=`object`)return!1;let t=globalThis.FileSystemDirectoryHandle;return t!==void 0&&e instanceof t||typeof e.getDirectoryHandle==`function`&&typeof e.getFileHandle==`function`&&typeof e.requestPermission==`function`}async function iZ(e){let t=await F(e,j.STORAGE_HANDLE);return!rZ(t)||await t.requestPermission({mode:`readwrite`})===`granted`}function aZ(e){let t=p();return t?`shadowclaw:${t}:${e}`:e}function oZ(e){if(typeof localStorage>`u`)return null;let t=aZ(e);try{let n=localStorage.getItem(t);if(n!==null)return n;if(t===e)return null;let r=localStorage.getItem(e);if(r!==null)return localStorage.setItem(t,r),r}catch(e){console.warn(`Unable to read from localStorage:`,e)}return null}function sZ(e,t){if(typeof localStorage>`u`)return;let n=aZ(e);try{localStorage.setItem(n,t)}catch(e){console.warn(`Unable to write to localStorage:`,e)}}async function cZ(e,t){let n=await z(e,t);for await(let[e]of n.entries())await n.removeEntry(e,{recursive:!0})}async function lZ(e,t,n){let r=await z(e,t),{dirs:i,filename:a}=Ce(n.replace(/\/$/,``)),o=r;for(let e of i)o=await o.getDirectoryHandle(e);await o.removeEntry(a,{recursive:!0})}function uZ(e,t){return`${e}:${t}`}async function dZ(e){let t=await F(e,j.SUPPRESSED_PAGES_LIST);if(!t||typeof t!=`string`)return[];try{let e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return[]}async function fZ(e,t,n){let r=await dZ(e),i=uZ(t,n);return r.some(e=>uZ(e.groupId,e.path)===i)}async function pZ(e,t,n){let r=await dZ(e),i=uZ(t,n);if(!r.some(e=>uZ(e.groupId,e.path)===i)){let i=[...r,{groupId:t,path:n}];await U(e,j.SUPPRESSED_PAGES_LIST,JSON.stringify(i))}}async function mZ(e,t,n){let r=await dZ(e),i=uZ(t,n),a=r.filter(e=>uZ(e.groupId,e.path)!==i);a.length!==r.length&&await U(e,j.SUPPRESSED_PAGES_LIST,JSON.stringify(a))}function hZ(e=w){return e===`br:main`?j.STATIC_MAIN_SITE_SEEDED:`${j.STATIC_MAIN_SITE_SEEDED}:${e}`}async function gZ(e,t=w){let n=await F(e,hZ(t));return n===!0||n===`true`}async function _Z(e,t=w,n=!0){await U(e,hZ(t),n)}function vZ(){let e=h(`/static-main-manifest.json`);if(typeof window<`u`&&window.location?.origin)try{return new URL(e,window.location.origin).toString()}catch{return e}return e}function yZ(e){let t=h(`/static-main/${e.replace(/^\/+/,``)}`);if(typeof window<`u`&&window.location?.origin)try{return new URL(t,window.location.origin).toString()}catch{return t}return t}async function bZ(){if(typeof fetch!=`function`)return null;try{let e=vZ(),t=await fetch(e);if(t.ok){let e=await t.json();if(e&&Array.isArray(e.pages))return e}}catch{}return null}async function xZ(e){if(typeof fetch!=`function`)return null;try{let t=yZ(e),n=await fetch(t);if(n.ok)return await n.text()}catch{}return null}async function SZ(e={}){let t=()=>{if(typeof document<`u`){let e=document.getElementById(`shadow-claw-static-manifest`);if(e&&e.textContent)try{let t=JSON.parse(e.textContent);if(t&&Array.isArray(t.pages))return t}catch(e){console.warn(`Failed to parse embedded static main manifest:`,e)}}return null};if(e.preferEmbedded!==!1){let e=t();if(e)return e}if(e.fetchFallback!==!1){let e=await bZ();if(e)return e}if(e.preferEmbedded===!1){let e=t();if(e)return e}return{pages:[{displayPath:`index.html`,content:FW},{displayPath:`MEMORY.md`,content:kW}]}}async function CZ(e,t,n=[]){for(let[r,i]of Object.entries(t))if(r===`purgePreRenderedStaticPages`&&i===!0){if(n.length>0){let t=n[0],r=n.slice(1).join(`/`);try{r?await lZ(e,t,r):await cZ(e,t)}catch(e){console.warn(`Failed to purge pre-rendered static pages for ${t}/${r}:`,e)}}}else typeof i==`object`&&i&&await CZ(e,i,[...n,r])}function wZ(){if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent);if(t?.pages?.sortOrder===`desc`)return`desc`;if(t?.pages?.sortOrder===`asc`)return`asc`}}catch{}return`desc`}function TZ(e,t){let n=t??wZ();return[...e].sort((e,t)=>{let r=e.path,i=t.path,a=r.split(`/`).pop()||``,o=i.split(`/`).pop()||``,s=/^index\.(html?|xhtml)$/iu.test(a),c=/^index\.(html?|xhtml)$/iu.test(o);if(s&&!c)return-1;if(!s&&c)return 1;let l=/^memory\.(md|markdown)$/iu.test(a),u=/^memory\.(md|markdown)$/iu.test(o);return l&&!u?1:!l&&u?-1:n===`asc`?r.localeCompare(i,void 0,{numeric:!0,sensitivity:`base`}):i.localeCompare(r,void 0,{numeric:!0,sensitivity:`base`})})}async function EZ(e,t,n=`sc:purge-id`,r=`static_main_site_purge_id`){let i=t??`__legacy_purge_pages__`;try{if(oZ(n)===i)return!0}catch{}try{if(await F(e,r)===i){try{sZ(n,i)}catch{}return!0}await U(e,r,i);try{sZ(n,i)}catch{}}catch{try{sZ(n,i)}catch{}}return!1}async function DZ(e,t=w,n=[],r={}){await zW(e,t);let i=await SZ(r),a=!1;i.preRenderedStaticPages&&(await EZ(e,i.purgeId)||(a=!0,await CZ(e,i.preRenderedStaticPages)));let o=!1;if(t===`br:main`&&i.skillsPurgeId!==void 0&&!await EZ(e,i.skillsPurgeId,`sc:skills-purge-id`,`static_main_skills_purge_id`)){o=!0;try{await lZ(e,t,`.agents/skills/main`)}catch(e){if(!(e&&typeof e==`object`&&`name`in e&&e.name===`NotFoundError`))throw e}try{await lZ(e,t,`.agents/tools/main`)}catch(e){if(!(e&&typeof e==`object`&&`name`in e&&e.name===`NotFoundError`))throw e}}for(let n of i.pages)if(n.content?.includes(`slug: "shadow-claw--purge-pages"`)){!a&&!await EZ(e,i.purgeId)&&(a=!0,await cZ(e,t));break}let s=t===`br:main`&&await MW(e),c=new Set(i.pages.map(e=>uZ(t,e.displayPath))),l=a?n.filter(e=>e.groupId!==t||c.has(uZ(e.groupId,e.path))):[...n];for(let n of i.pages)if(!n.content?.includes(`slug: "shadow-claw--purge-pages"`)){if(/^memory\.(md|markdown)$/iu.test(n.displayPath)){if(s)continue;let r=n.content===kW?void 0:n.content;if(r===void 0?await PW(e,t):await PW(e,t,r)){let e=uZ(t,n.displayPath);l.some(t=>uZ(t.groupId,t.path)===e)||l.push({groupId:t,path:n.displayPath})}continue}if(!await fZ(e,t,n.displayPath))try{if(!await AW(e,t,n.displayPath)){let r=n.content;typeof r!=`string`&&(r=await xZ(n.displayPath)??``),await Nn(e,t,n.displayPath,r)}let r=uZ(t,n.displayPath);l.some(e=>uZ(e.groupId,e.path)===r)||l.push({groupId:t,path:n.displayPath})}catch(e){console.warn(`Failed to seed static page file ${n.displayPath}:`,e)}}if(t===`br:main`){for(let n of i.skills||[]){let r=`.agents/skills/main/${n.displayPath}`;try{await AW(e,t,r)||await Nn(e,t,r,n.content)}catch(e){console.warn(`Failed to seed skill file ${r}:`,e)}}for(let n of i.tools||[]){let r=`.agents/tools/main/${n.displayPath}`;try{(o||!await AW(e,t,r))&&await Nn(e,t,r,n.content)}catch(e){console.warn(`Failed to seed tool file ${r}:`,e)}}}let u=typeof document<`u`&&document.getElementById(`shadow-claw-static-manifest`)!==null;return r.preferEmbedded!==!1&&u||await _Z(e,t,!0),Object.defineProperty(l,"didPurge",{value:a,enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(l,"didPurgeSkills",{value:o,enumerable:!1,writable:!0,configurable:!0}),TZ(l)}var OZ=class{_events;_handlers=[];_runs=new Map;constructor(e){this._events=e}start(){this._listen(`streaming-start`,this._onStreamingStart),this._listen(`streaming-chunk`,this._onStreamingChunk),this._listen(`streaming-end`,this._onStreamingEnd),this._listen(`streaming-done`,this._onStreamingDone),this._listen(`streaming-error`,this._onStreamingError),this._listen(`tool-activity`,this._onToolActivity)}stop(){for(let{event:e,handler:t}of this._handlers)this._events.off(e,t);this._handlers=[],this._runs.clear()}_emit(e,t){window.dispatchEvent(new CustomEvent(`shadow-claw-agui-event`,{detail:{groupId:e,event:t}}))}_listen(e,t){this._events.on(e,t),this._handlers.push({event:e,handler:t})}_onStreamingChunk=({groupId:e,text:t})=>{let n=this._runs.get(e);!n||!n.messageId||this._emit(e,{type:`TEXT_MESSAGE_CONTENT`,messageId:n.messageId,delta:t,timestamp:Date.now()})};_onStreamingDone=({groupId:e})=>{let t=this._runs.get(e);t&&(t.messageId&&this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:t.messageId,timestamp:Date.now()}),this._emit(e,{type:`RUN_FINISHED`,threadId:t.threadId,runId:t.runId,timestamp:Date.now()}),this._runs.delete(e))};_onStreamingEnd=({groupId:e})=>{let t=this._runs.get(e);!t||!t.messageId||(this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:t.messageId,timestamp:Date.now()}),t.messageId=null)};_onStreamingError=({groupId:e,error:t})=>{let n=this._runs.get(e);n&&(n.messageId&&this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:n.messageId,timestamp:Date.now()}),this._emit(e,{type:`RUN_ERROR`,message:t||`Unknown streaming error`,timestamp:Date.now()}),this._runs.delete(e))};_onStreamingStart=({groupId:e})=>{let t=dr(),n=e,r=dr();this._runs.set(e,{runId:t,threadId:n,messageId:r,activeToolCallIds:new Set}),this._emit(e,{type:`RUN_STARTED`,threadId:n,runId:t,timestamp:Date.now()}),this._emit(e,{type:`TEXT_MESSAGE_START`,messageId:r,role:`assistant`,timestamp:Date.now()})};_onToolActivity=({groupId:e,tool:t,status:n})=>{let r=this._runs.get(e);if(r){if(n===`running`){let n=dr();r.activeToolCallIds.add(n),this._emit(e,{type:`TOOL_CALL_START`,toolCallId:n,toolCallName:t,timestamp:Date.now()}),r._lastToolCallId=n}else if(n===`done`||n===`error`){let t=r._lastToolCallId;t&&(r.activeToolCallIds.delete(t),this._emit(e,{type:`TOOL_CALL_END`,toolCallId:t,timestamp:Date.now()}))}}}};function kZ(e,t){if(!e||typeof e!=`object`)return e;let n=JSON.parse(JSON.stringify(e));for(let e of t)AZ(n,e);return n}function AZ(e,t){let{op:n,path:r,value:i}=t;if(!r||!r.startsWith(`/`))return;let a=r.split(`/`).slice(1).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`)),o=a.pop();if(o===void 0)return;let s=e;for(let e of a){if(typeof s!=`object`||!s)return;s=s[e]}typeof s!=`object`||!s||(Array.isArray(s)?jZ(s,o,n,i):MZ(s,o,n,i))}function jZ(e,t,n,r){if(n===`add`)if(t===`-`)e.push(r);else{let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<=e.length&&e.splice(n,0,r)}else if(n===`replace`){let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<e.length&&(e[n]=r)}else if(n===`remove`){let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<e.length&&e.splice(n,1)}}function MZ(e,t,n,r){n===`add`||n===`replace`?e[t]=r:n===`remove`&&delete e[t]}var NZ=t({OrchestratorStore:()=>VZ,accumulateTokenUsage:()=>BZ,orchestratorStore:()=>HZ});function PZ(e){if(e){if(Array.isArray(e))return e;if(typeof e==`string`)try{let t=JSON.parse(e);return Array.isArray(t)?t:void 0}catch{return}}}function FZ(e){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();return t===`true`||t===`1`}return typeof e==`number`&&e===1}function IZ(e){return!!e}async function LZ(e,t,n,r){if(!IZ(r))return!0;if(!e.schedule)return await RZ(e.id,t,n,r)!==`failed`;try{let r=t.replace(/\/$/,``);return(await fetch(`${r}/tasks`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...e,subscriberId:n})})).ok}catch{return!1}}async function RZ(e,t,n,r){if(!IZ(r))return`missing`;try{let r=t.replace(/\/$/,``),i=`subscriberId=${encodeURIComponent(n)}`,a=await fetch(`${r}/tasks/${encodeURIComponent(e)}?${i}`,{method:`DELETE`});return a.ok?`deleted`:a.status===404||a.status===405?`missing`:`failed`}catch{return`failed`}}async function zZ(e,t,n,r){if(!IZ(r))return null;try{let r=t.replace(/\/$/,``),i=await fetch(`${r}/tasks?groupId=${encodeURIComponent(e)}&subscriberId=${encodeURIComponent(n)}`,{method:`GET`});if(!i.ok||typeof i.json!=`function`)return null;let a=await i.json();return Array.isArray(a)?a.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`string`&&typeof e.schedule==`string`&&typeof e.prompt==`string`).map(t=>({id:t.id,groupId:t.group_id||t.groupId||e,schedule:t.schedule,type:t.type,prompt:t.prompt,tools:PZ(t.tools),channel:typeof t.channel==`string`?t.channel:void 0,enabled:t.enabled===!0||t.enabled===1,lastRun:typeof t.lastRun==`number`?t.lastRun:typeof t.last_run==`number`?t.last_run:null,createdAt:typeof t.createdAt==`number`?t.createdAt:typeof t.created_at==`number`?t.created_at:Date.now(),name:typeof t.name==`string`?t.name:void 0,order:typeof t.order==`number`?t.order:typeof t.task_order==`number`?t.task_order:void 0})):null}catch{return null}}function BZ(e,t){let n=(e?.inputTokens??0)+(t.inputTokens??0),r=(e?.outputTokens??0)+(t.outputTokens??0),i=(e?.cacheReadTokens??0)+(t.cacheReadTokens??0),a=(e?.cacheCreationTokens??0)+(t.cacheCreationTokens??0);return{groupId:t.groupId||e?.groupId||``,inputTokens:n,outputTokens:r,cacheReadTokens:i,cacheCreationTokens:a,totalTokens:n+r+i+a,contextLimit:t.contextLimit||e?.contextLimit||0}}var VZ=class e{static DEFAULT_PAGE_PATH=`MEMORY.md`;orchestrator;_activeGroupId;_activePage;_activePinnedPage;_defaultPinnedPage;_activityLog;_activityLogSessionStartedAtByGroup;_aguiAdapter;_aguiEvent;_contextUsage;_currentPath;_db;_error;_files;_gitProxyUrl;_groups;_hadPersistedActivePage;_initResolve;_isTyping;_lastOrchestratorDisplayState=`idle`;_messages;_modelDownloadProgress;_onlineReplayHandler;_pages;_peerStateByGroup;_proxyUrl;_ready;_remoteAgentStatusByGroup;_remoteAgentTypingByGroup;_replayingTaskSyncOutbox;_subscriberId;_sidebarDefaultPage;_state;_storageStatus;_streamingText;_tasks;_taskSyncOutbox;_tokenUsage;_tokenUsageAccumulator=null;_toolActivity;_unreadGroupIds;_useProxy;_vmBashFullInternetAccess;_whenInitialized;_whenReady;_readyResolve;constructor(){this._messages=new jG.State([]),this._isTyping=new jG.State(!1),this._storageStatus=new jG.State(null),this._toolActivity=new jG.State(null),this._modelDownloadProgress=new jG.State(null),this._activityLog=new jG.State([]),this._state=new jG.State(`idle`),this._tokenUsage=new jG.State(null),this._error=new jG.State(null),this._activeGroupId=new jG.State(w),this._ready=new jG.State(!1),this._tasks=new jG.State([]),this._files=new jG.State([]),this._currentPath=new jG.State(`.`),this._groups=new jG.State([]),this._unreadGroupIds=new jG.State(new Set),this._streamingText=new jG.State(null),this._aguiEvent=new jG.State(null),this._contextUsage=new jG.State(null),this._useProxy=new jG.State(!1),this._proxyUrl=new jG.State(`/proxy`),this._gitProxyUrl=new jG.State(`/git-proxy`),this._vmBashFullInternetAccess=new jG.State(!1),this._activePage=new jG.State(`pages`),this._sidebarDefaultPage=new jG.State(`chat`),this._pages=new jG.State([]),this._activePinnedPage=new jG.State(null),this._defaultPinnedPage=new jG.State(null),this._remoteAgentStatusByGroup=new jG.State(new Map),this._remoteAgentTypingByGroup=new jG.State(new Map),this._peerStateByGroup=new jG.State(new Map),this._hadPersistedActivePage=!1,this._initResolve=null,this._whenInitialized=new Promise(e=>{this._initResolve=e}),this._readyResolve=null,this._whenReady=new Promise(e=>{this._readyResolve=e}),this.orchestrator=null,this._db=null,this._activityLogSessionStartedAtByGroup=new Map,this._taskSyncOutbox=[],this._replayingTaskSyncOutbox=!1,this._subscriberId=null,this._onlineReplayHandler=null,this._aguiAdapter=null}get activeGroupId(){return this._activeGroupId.get()}get activePage(){return this._activePage.get()}get activePinnedPage(){return this._activePinnedPage.get()}get defaultPinnedPage(){return this._defaultPinnedPage.get()}get effectiveDefaultPage(){return this._pages.get()[0]||null}get activityLog(){return this._activityLog.get()}get aguiEvent(){return this._aguiEvent.get()}clearError(){this._error.set(null),this._state.get()===`error`&&this._state.set(`idle`)}get contextUsage(){return this._contextUsage.get()}get tokenUsageAccumulator(){return this._tokenUsageAccumulator}get currentPath(){return this._currentPath.get()}get error(){return this._error.get()}get files(){return this._files.get()}getPeerState(e){return this._peerStateByGroup.get().get(e)||null}getRemoteAgentStatus(e){return this._remoteAgentStatusByGroup.get().get(e)||`idle`}getState(){return{messages:this.messages,isTyping:this.isTyping,toolActivity:this.toolActivity,activityLog:this.activityLog,state:this.state,tokenUsage:this.tokenUsage,modelDownloadProgress:this.modelDownloadProgress,error:this.error,activeGroupId:this.activeGroupId,pages:this.pages,ready:this.ready,files:this.files,currentPath:this.currentPath,streamingText:this.streamingText,contextUsage:this.contextUsage}}getTasksForBackup(){return this._tasks.get()}get gitProxyUrl(){return this._gitProxyUrl.get()}get groups(){return this._groups.get()}get hadPersistedActivePage(){return this._hadPersistedActivePage}isRemoteAgentTyping(e){return this._remoteAgentTypingByGroup.get().get(e)||!1}get isTyping(){return this._isTyping.get()}get messages(){return this._messages.get()}get modelDownloadProgress(){return this._modelDownloadProgress.get()}get pages(){return this._pages.get()}get proxyUrl(){return this._proxyUrl.get()}get ready(){return this._ready.get()}sendMessage(e,t=[],n){n===void 0?this.orchestrator?.browserChat?.submit(e,this._activeGroupId.get(),t):this.orchestrator?.browserChat?.submit(e,this._activeGroupId.get(),t,n)}setActiveGroup(e,t,n=this._activePage.get()===`chat`){if(this._activeGroupId.set(t),this._messages.set([]),this._activityLog.set([]),this._error.set(null),this._isTyping.set(!1),this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null),this._currentPath.set(`.`),n){let e=new Set(this._unreadGroupIds.get());e.delete(t)&&this._unreadGroupIds.set(e)}this.loadHistory(),this.loadTasks(e),this.loadFiles(e)}setReady(e=!0){this._ready.set(e),e&&this._readyResolve&&this._readyResolve()}setRemoteAgentStatus(e,t){let n=this._remoteAgentStatusByGroup.get(),r=new Map(n);r.set(e,t),this._remoteAgentStatusByGroup.set(r)}setRemoteAgentTyping(e,t){let n=this._remoteAgentTypingByGroup.get(),r=new Map(n);t?r.set(e,!0):r.delete(e),this._remoteAgentTypingByGroup.set(r)}get sidebarDefaultPage(){return this._sidebarDefaultPage.get()}get state(){return this._state.get()}stopCurrentRequest(){this.orchestrator?.stopCurrentRequest?.(this._activeGroupId.get())}get storageStatus(){return this._storageStatus.get()}get streamingText(){return this._streamingText.get()}syncHostWorkspaceToVM(){VX(this.orchestrator,this._activeGroupId.get())}syncVMWorkspaceToHost(){HX(this.orchestrator,this._activeGroupId.get())}get tasks(){return this._tasks.get()}get tokenUsage(){return this._tokenUsage.get()}get toolActivity(){return this._toolActivity.get()}get unreadGroupIds(){return this._unreadGroupIds.get()}get useProxy(){return this._useProxy.get()}get vmBashFullInternetAccess(){return this._vmBashFullInternetAccess.get()}get whenInitialized(){return this._whenInitialized}async resetSiteConfigSeed(e){await U(e,j.SITE_CONFIG_SEEDED,!1)}get whenReady(){return this._whenReady}async addPage(e,t,n=this._activeGroupId.get()){let r=n===`br:main`?this.normalizePagePath(t):t.trim();if(!r)return;let i=this._pages.get();i.some(e=>e.path===r&&e.groupId===n)||(this.setPages([...i,{groupId:n,path:r}]),await mZ(e,n,r),n===`br:main`&&r===`MEMORY.md`&&await NW(e,!1),await this.persistPages(e))}async clearAllTasks(e){let t=await hX(e),n=this._activeGroupId.get(),r=t.filter(e=>e.groupId===n),i=await this.getSubscriberId(e);for(let t of r){if(await RZ(t.id,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)===`failed`){console.warn(`Failed to delete task "${t.id}" from server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`delete`,id:t.id,queuedAt:Date.now()});continue}await mX(e,t.id)}await this.loadTasks(e)}async cloneConversation(e,t){let n=await iK(e,t);if(!n)return null;await YX(e,t,n.groupId),await XX(e,t,n.groupId);try{let r=await we(e,t,`MEMORY.md`);r&&await Nn(e,n.groupId,`MEMORY.md`,r)}catch{}try{await eZ(e,t,n.groupId,`attachments`)}catch{}return await this.loadGroups(e),this.setActiveGroup(e,n.groupId),n}async compactContext(e){if(this.orchestrator)return BX(this.orchestrator,e,this._activeGroupId.get())}async createConversation(e,t){let n=await QG(e,t);return await this.loadGroups(e),this.setActiveGroup(e,n.groupId),n}async deleteConversation(e,t){if(!(this._groups.get().length<=1)&&(await tK(e,t),await JX(e,t),await this.loadGroups(e),this._activeGroupId.get()===t)){let t=this._groups.get()[0]?.groupId||`br:main`;this.setActiveGroup(e,t)}}async deleteMessage(e,t){await ZX(e,t),await this.loadHistory(),this.orchestrator?.refreshContextUsage&&await this.orchestrator.refreshContextUsage(e,this._activeGroupId.get())}async deleteTask(e,t){let n=await this.getSubscriberId(e);if(await RZ(t,this.getTaskServerBaseUrl(),n,this.orchestrator?.taskServerEnabled??!1)===`failed`)throw console.warn(`Failed to delete task from server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`delete`,id:t,queuedAt:Date.now()}),Error(`Failed to delete scheduled task on server; task kept locally.`);await mX(e,t),await this.loadTasks(e)}async ensurePeerConversation(e,t){let n=`peer:${t}`,r=await nK(e);if(!r.find(e=>e.groupId===n)){let i=[...r],a=``;if(this.orchestrator?.peerjsPeerAliases){for(let[e,n]of Object.entries(this.orchestrator.peerjsPeerAliases))if(n===t){a=e;break}}i.push({groupId:n,name:`Peer: ${a||t.substring(0,8)}`,createdAt:Date.now()}),await ZG(e,i),await this.loadGroups(e)}return n}async grantStorageAccess(e){try{await iZ(e),await this.loadFiles(e)}catch(e){console.error(`Failed to grant storage access:`,e)}}async init(e,t){this._db=e,this.orchestrator=t,this._taskSyncOutbox=this.parseTaskSyncOutbox(await F(e,j.TASK_SYNC_OUTBOX)),await this.replayTaskSyncOutbox(e),typeof window<`u`&&!this._onlineReplayHandler&&(this._onlineReplayHandler=()=>{this._db&&this.replayTaskSyncOutbox(this._db)},window.addEventListener(`online`,this._onlineReplayHandler)),t.events.on(`a2ui-surface`,async({groupId:t,envelope:n})=>{t&&this.ensureGroupExists(e,t);let r=this._messages.get(),i=r.findIndex(e=>e.a2uiEnvelopes?.some(e=>e.surfaceId===n.surfaceId));if(i!==-1){let t=r[i],a=[...t.a2uiEnvelopes||[],n],o={...t,a2uiEnvelopes:a},s=[...r];s[i]=o,this._messages.set(s),await sX(e,o)}else{let i=!t.startsWith(`peer:`),a={id:dr(),groupId:t,sender:i?`agent`:t.replace(/^peer:/,``),content:``,timestamp:Date.now(),channel:t.startsWith(`peer:`)?`peerjs`:`browser`,isFromMe:i,isTrigger:!1,a2uiEnvelopes:[n]};t===this._activeGroupId.get()&&this._messages.set([...r,a]),await sX(e,a)}}),t.events.on(`message`,t=>{if(t.groupId&&this.ensureGroupExists(e,t.groupId,t.timestamp),t.groupId&&t.groupId!==this._activeGroupId.get()){let e=new Set(this._unreadGroupIds.get());e.add(t.groupId),this._unreadGroupIds.set(e);return}t.isFromMe&&this._streamingText.get()!==null&&this._streamingText.set(null),this._messages.set([...this._messages.get(),t])}),t.events.on(`typing`,({groupId:e,typing:t})=>{e&&e!==this._activeGroupId.get()||this._isTyping.set(t)}),t.events.on(`tool-activity`,({groupId:e,tool:t,status:n})=>{e&&e!==this._activeGroupId.get()||this._toolActivity.set(n===`running`?{tool:t,status:n}:null)}),t.events.on(`model-download-progress`,e=>{this._modelDownloadProgress.set(e.status===`done`?null:e)}),t.events.on(`thinking-log`,e=>{e.groupId&&e.groupId!==this._activeGroupId.get()||(e.level===`info`&&e.label===`Starting`?this._activityLog.set([e]):this._activityLog.set([...this._activityLog.get(),e]),this.forwardActivityLogEntryToServer(e))}),t.events.on(`state-change`,e=>{let t=typeof e==`string`?e:e.state,n=typeof e==`string`?void 0:e.groupId;if(n&&n!==this._activeGroupId.get())return;let r=this._lastOrchestratorDisplayState;this._lastOrchestratorDisplayState=t,this._state.set(t),t===`idle`&&(this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null)),t===`thinking`&&r!==`thinking`&&r!==`responding`&&(this._tokenUsageAccumulator=null)}),t.events.on(`error`,({error:e})=>{console.error(`[Orchestrator Error Event]`,e),this._error.set(e),this._state.set(`error`)}),t.events.on(`session-reset`,()=>{this._messages.set([]),this._activityLog.set([]),this._tokenUsageAccumulator=null,this._tokenUsage.set(null),this._contextUsage.set(null),this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null),this._isTyping.set(!1),this._state.set(`idle`)}),t.events.on(`context-compacted`,e=>{e?.groupId&&e.groupId!==this._activeGroupId.get()||(this._tokenUsage.set(null),this.loadHistory())}),t.events.on(`token-usage`,e=>{if(!e||e.groupId&&e.groupId!==this._activeGroupId.get())return;let t=BZ(this._tokenUsageAccumulator,e);this._tokenUsageAccumulator=t,this._tokenUsage.set(t),this.orchestrator?.refreshContextUsage&&this._db&&this.orchestrator.refreshContextUsage(this._db,this._activeGroupId.get())}),t.events.on(`context-usage`,e=>{this._contextUsage.set(e)}),t.events.on(`ready`,()=>{this._ready.set(!0)}),t.events.on(`task-change`,()=>{this.loadTasks(e)}),t.events.on(`file-change`,()=>{this.loadFiles(e)}),t.events.on(`streaming-start`,({groupId:e})=>{e===this._activeGroupId.get()&&this._streamingText.set(``)}),t.events.on(`streaming-chunk`,({groupId:e,text:t})=>{if(e!==this._activeGroupId.get())return;let n=this._streamingText.get();this._streamingText.set((n||``)+t)}),t.events.on(`streaming-end`,({groupId:e})=>{e===this._activeGroupId.get()&&this._streamingText.set(null)}),t.events.on(`streaming-done`,({groupId:e})=>{this._activeGroupId.get()}),t.events.on(`streaming-error`,({groupId:e})=>{this._activeGroupId.get()}),this._aguiAdapter=new OZ(t.events),this._aguiAdapter.start(),typeof window<`u`&&window.addEventListener(`shadow-claw-agui-event`,(e=>{e.detail.groupId===this._activeGroupId.get()&&this._aguiEvent.set(e.detail);let t=e.detail.event;if(t){if(t.type===`STATE_SNAPSHOT`){let n=new Map(this._peerStateByGroup.get());n.set(e.detail.groupId,t.snapshot||{}),this._peerStateByGroup.set(n)}else if(t.type===`STATE_DELTA`){let n=new Map(this._peerStateByGroup.get()),r=kZ(n.get(e.detail.groupId)||{},t.delta||[]);n.set(e.detail.groupId,r),this._peerStateByGroup.set(n)}}})),await hn(e),vn(),yn();let n=await F(e,j.PAGES_LIST),r=await DZ(e,w,n==null?[]:this.parsePagesList(n));r.length>0?(this.setPages(r),await this.persistPages(e)):await this.ensureDefaultPage(e),await this.applySiteConfigDefaults(e),await this.loadGroups(e);let i=await F(e,j.LAST_ACTIVE_GROUP);i&&i!==this._activeGroupId.get()&&this._activeGroupId.set(i);let a=await F(e,j.LAST_ACTIVE_PAGE);a&&(this._activePage.set(a),this._hadPersistedActivePage=!0);let o=await F(e,j.SIDEBAR_DEFAULT_PAGE);this._sidebarDefaultPage.set(this.normalizeSidebarDefaultPage(o));let s=await F(e,j.LAST_SELECTED_PINNED_PAGE);if(s)try{let e=JSON.parse(s);e&&typeof e.path==`string`&&typeof e.groupId==`string`&&this._activePinnedPage.set(e)}catch{}this.orchestrator&&(this._useProxy.set(this.orchestrator.useProxy),this._proxyUrl.set(this.orchestrator.proxyUrl),this._gitProxyUrl.set(this.orchestrator.gitProxyUrl),this._vmBashFullInternetAccess.set(this.orchestrator.vmBashFullInternetAccess)),await Promise.all([this.loadHistory(),this.loadTasks(e),this.loadFiles(e)]),this._initResolve?.(),this.scheduleBackgroundStaticMainSiteSeeding(e)}async loadFiles(e){let t=this._activeGroupId.get(),n=this._currentPath.get();try{this._storageStatus.set(await R(e));let r=await nZ(e,t,n);this._files.set(r)}catch(e){console.error(`Failed to load files in store:`,e)}}async loadGroups(e){let t=await nK(e);this._groups.set(t)}async loadHistory(){let e=this._activeGroupId.get(),t=await UG(e,200);this._activeGroupId.get()===e&&this._messages.set(t)}async loadTasks(e){let t=this._activeGroupId.get(),n=await hX(e),r=n.filter(e=>e.groupId===t);r.sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?e.createdAt-t.createdAt:n-r}),this._tasks.set(r);let i=await this.getSubscriberId(e),a=await zZ(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1);if(!a)return;let o=new Set(n.map(e=>e.id)),s=a.filter(e=>!o.has(e.id));if(s.length===0)return;for(let t of s)await bX(e,t);let c=[...r,...s];c.sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?e.createdAt-t.createdAt:n-r}),this._tasks.set(c)}async navigateBackFolder(e){let t=this._currentPath.get();if(t===`.`)return;let n=t.split(`/`).filter(Boolean);n.pop();let r=n.length===0?`.`:n.join(`/`);await this.setCurrentPath(e,r)}async navigateIntoFolder(e,t){let n=this._currentPath.get(),r=n===`.`?t.replace(/\/$/,``):`${n}/${t.replace(/\/$/,``)}`;try{await this.setCurrentPath(e,r)}catch(t){console.error(`Failed to navigate into folder in store:`,t),DX(`Folder not found: ${r}`,4500),await this.loadFiles(e)}}async newSession(e){await this.orchestrator?.newSession?.(e,this._activeGroupId.get()),await this.loadHistory()}async removePage(t,n,r=this._activeGroupId.get()){let i=this.normalizePagePath(n);if(!i)return;let a=this._pages.get();if(!a.some(e=>e.path===i&&e.groupId===r))return;let o=a.filter(e=>!(e.path===i&&e.groupId===r));await pZ(t,r,i);let s=r===`br:main`&&i===`MEMORY.md`;s&&await NW(t,!0);let c=s||await MW(t);if(o.length===0&&!c)if(await PW(t,`br:main`))o.push({groupId:w,path:e.DEFAULT_PAGE_PATH});else return;this.setPages(o);let l=this._defaultPinnedPage.get();l&&l.path===i&&l.groupId===r&&await this.setDefaultPinnedPage(t,null),await this.persistPages(t)}async removeAllPages(e){let t=[...this._pages.get()];for(let n of t)await pZ(e,n.groupId,n.path),n.groupId===`br:main`&&n.path===`MEMORY.md`&&await NW(e,!0);this.setPages([]),await this.setDefaultPinnedPage(e,null),await this.setActivePinnedPage(e,null),await this.persistPages(e)}async renameConversation(e,t,n){await $G(e,t,n),await this.loadGroups(e)}async reorderConversations(e,t){await rK(e,t),await this.loadGroups(e)}async reorderTasks(e,t,n){let r=await $X(e,t,n);await this.loadTasks(e);let i=await this.getSubscriberId(e);for(let t of r)await LZ(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to sync reordered task "${t.id}" to server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:t.id,task:t,queuedAt:Date.now()}))}async replayTaskSyncOutbox(e){if(!(this._replayingTaskSyncOutbox||this._taskSyncOutbox.length===0)){this._replayingTaskSyncOutbox=!0;try{let t=await this.getSubscriberId(e),n=[];for(let e of this._taskSyncOutbox){let r=this.getTaskServerBaseUrl();(e.type===`upsert`?await LZ(e.task,r,t,this.orchestrator?.taskServerEnabled??!1):await RZ(e.id,r,t,this.orchestrator?.taskServerEnabled??!1))||n.push(e)}this._taskSyncOutbox=this.compactTaskSyncOutbox(n),await this.persistTaskSyncOutbox(e)}finally{this._replayingTaskSyncOutbox=!1}}}async resetToRootFolder(e){await this.setCurrentPath(e,`.`)}async restartCurrentRequest(){return this.orchestrator?.restartCurrentRequest?this.orchestrator.restartCurrentRequest(this._activeGroupId.get()):!1}async restoreTasksFromBackup(e,t){await this.clearAllTasks(e);let n=this._activeGroupId.get();for(let r of t){let t={...r,groupId:n,id:crypto.randomUUID?crypto.randomUUID():`task-${Date.now()}-${Math.random()}`};await this.upsertTask(e,t,{reloadTasks:!1})}await this.loadTasks(e)}async runTask(e,t=!1){let n=this._db;if(t&&n&&(await QX(e.id,Date.now()),await this.loadTasks(n)),e.type===`tools`&&Array.isArray(e.tools)&&e.tools.length>0)if(this.orchestrator?.agentWorker){let n=e.subagent?`subagent:${dr()}`:e.groupId;this.orchestrator.agentWorker.postMessage({type:`execute-task-tools`,payload:{groupId:n,tools:e.tools,isManual:t}})}else console.error(`Agent worker not available to execute tool task.`);else{if(!e.groupId){console.error(`Task ${e.id} has no groupId - refusing to execute in active conversation to prevent context pollution.`);return}this.orchestrator?.browserChat?.submit(e.prompt,e.groupId,[],void 0,e.freshContext,e.subagent)}}async setActivePage(e,t){this._activePage.set(t),await U(e,j.LAST_ACTIVE_PAGE,t);let n=this.resolveSidebarDefaultPageForActivePage(t);n!==this._sidebarDefaultPage.get()&&(this._sidebarDefaultPage.set(n),await U(e,j.SIDEBAR_DEFAULT_PAGE,n))}async setActivePinnedPage(e,t){this._activePinnedPage.set(t),t?await U(e,j.LAST_SELECTED_PINNED_PAGE,JSON.stringify(t)):await U(e,j.LAST_SELECTED_PINNED_PAGE,null)}async setDefaultPinnedPage(e,t){let n=this._defaultPinnedPage.get(),r=n&&t&&n.path===t.path&&n.groupId===t.groupId?null:t;this._defaultPinnedPage.set(r),r?await U(e,j.DEFAULT_PINNED_PAGE,JSON.stringify(r)):await U(e,j.DEFAULT_PINNED_PAGE,null)}async reorderPages(e,t){this.setPages(t),await this.persistPages(e)}async setCurrentPath(e,t){let n=t.replace(/^\/+|\/+$/g,``)||`.`,r=this._activeGroupId.get();this._storageStatus.set(await R(e));let i=await nZ(e,r,n);this._currentPath.set(n),this._files.set(i)}async setGitProxyUrl(e,t){this.orchestrator&&(await WX(this.orchestrator,e,t),this._gitProxyUrl.set(this.orchestrator.gitProxyUrl))}async setProxyUrl(e,t){this.orchestrator&&(await GX(this.orchestrator,e,t),this._proxyUrl.set(this.orchestrator.proxyUrl))}async setUseProxy(e,t){this.orchestrator&&(await KX(this.orchestrator,e,t),this._useProxy.set(this.orchestrator.useProxy))}async setVMBashFullInternetAccess(e,t){this.orchestrator&&(await qX(this.orchestrator,e,t),this._vmBashFullInternetAccess.set(this.orchestrator.vmBashFullInternetAccess))}async switchConversation(e,t,n){this.setActiveGroup(e,t,n??this._activePage.get()===`chat`),await U(e,j.LAST_ACTIVE_GROUP,t)}async toggleTask(e,t,n){let r={...t,enabled:n};await bX(e,r),await this.loadTasks(e),await LZ(r,this.getTaskServerBaseUrl(),await this.getSubscriberId(e),this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to update task on server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:r.id,task:r,queuedAt:Date.now()}))}async updateConversationPinnedProvider(e,t,n,r,i){await aK(e,t,n,r,i),await this.loadGroups(e)}async updateConversationProviderRuntimeOverrides(e,t,n){await sK(e,t,n),await this.loadGroups(e)}async updateConversationSubagentSettings(e,t,n,r,i,a){await oK(e,t,n,r,i,a),await this.loadGroups(e)}async updateConversationToolTags(e,t,n){await eK(e,t,n),await this.loadGroups(e)}async upsertTask(e,t,n){let r=n?.reloadTasks!==!1;await bX(e,t),r&&await this.loadTasks(e);let i=await this.getSubscriberId(e);await LZ(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to sync task to server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:t.id,task:t,queuedAt:Date.now()}))}compactTaskSyncOutbox(e){let t=new Map;return e.forEach((e,n)=>{t.set(e.id,n)}),e.filter((e,n)=>t.get(e.id)===n)}deriveGroupName(e){return e.startsWith(`tg:`)?`Telegram ${e.slice(3)}`:e.startsWith(`im:`)?`iMessage ${e.slice(3)}`:e.startsWith(`br:`)?e===`br:main`?`Main`:`Browser Conversation`:`Conversation`}getActivityLogSessionStartedAt(e){let t=this._activityLogSessionStartedAtByGroup.get(e);if(t)return t;let n=new Date().toISOString();return this._activityLogSessionStartedAtByGroup.set(e,n),n}getTaskServerBaseUrl(){return this.orchestrator?.taskServerUrl??`/schedule`}async getSubscriberId(e){if(this._subscriberId)return this._subscriberId;let t=await _X(e);return this._subscriberId=t,t}normalizePagePath(t){let n=t.trim().replace(/^\/+/,``).replace(/\/+/g,`/`);return n===`main/memory.md`?e.DEFAULT_PAGE_PATH:n}normalizeSidebarDefaultPage(e){return e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:`chat`}parsePagesList(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.map(e=>{if(typeof e==`string`)return{groupId:w,path:this.normalizePagePath(e)};if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.path!=`string`)return null;let n=typeof t.groupId==`string`&&t.groupId.trim().length>0?t.groupId:w,r=n===`br:main`?this.normalizePagePath(t.path):t.path.trim();return r?{groupId:n,path:r}:null}).filter(e=>!!e).filter((e,t,n)=>{let r=`${e.groupId}\u0000${e.path}`;return t===n.findIndex(e=>`${e.groupId}\u0000${e.path}`===r)}):[]}catch{return[]}}parseTaskSyncOutbox(e){if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let n=t.filter(e=>!!e&&typeof e==`object`).filter(e=>e.type===`upsert`||e.type===`delete`).filter(e=>typeof e.id==`string`&&e.id.length>0).map(e=>({...e,queuedAt:typeof e.queuedAt==`number`?e.queuedAt:Date.now()}));return this.compactTaskSyncOutbox(n)}catch{return[]}}resolveSidebarDefaultPageForActivePage(e){return e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:this._sidebarDefaultPage.get()}setPages(e){let t=e.filter(e=>e.path.toLowerCase()===`memory.md`),n=e.filter(e=>e.path.toLowerCase()!==`memory.md`);this._pages.set([...n,...t])}async ensureDefaultPage(t){if(await MW(t))return;let n=await PW(t,w);await zW(t,w),!(!n||this._pages.get().length>0)&&(this.setPages([{groupId:w,path:e.DEFAULT_PAGE_PATH}]),await this.persistPages(t))}async ensureGroupExists(e,t,n){let r=this._groups.get();if(r.some(e=>e.groupId===t))return;let i=[...r,{groupId:t,name:this.deriveGroupName(t),createdAt:n||Date.now()}];this._groups.set(i);try{await ZG(e,i)}catch(e){console.error(`Failed to persist new conversation metadata:`,e)}}async forwardActivityLogEntryToServer(e){if(!this._db||!FZ(await F(this._db,j.ACTIVITY_LOG_DISK_LOGGING_ENABLED)))return;let t=typeof e.groupId==`string`&&e.groupId?e.groupId:this._activeGroupId.get();if(!t)return;let n=typeof e.message==`string`?e.message.trim():``;if(!n)return;e.level===`info`&&e.label===`Starting`&&this._activityLogSessionStartedAtByGroup.set(t,new Date().toISOString());let r=this.getActivityLogSessionStartedAt(t);try{await fetch(`/activity-log`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({groupId:t,level:e.level,label:e.label,message:n,timestamp:new Date().toISOString(),sessionStartedAt:r})})}catch(e){console.warn(`Failed to persist activity log entry to server:`,e)}}scheduleBackgroundStaticMainSiteSeeding(e){if(typeof window>`u`)return;let t=async()=>{try{if(await gZ(e,`br:main`))return;let t=await F(e,j.PAGES_LIST),n=await DZ(e,w,t==null?[]:this.parsePagesList(t),{preferEmbedded:!1});n&&n.length>0&&(this.setPages(n),await this.persistPages(e))}catch(e){console.warn(`Background static main site seeding failed:`,e)}};typeof window.requestIdleCallback==`function`?window.requestIdleCallback(()=>void t(),{timeout:3e3}):setTimeout(()=>void t(),100)}async persistPages(e){await U(e,j.PAGES_LIST,JSON.stringify(this._pages.get()))}async persistTaskSyncOutbox(e){await U(e,j.TASK_SYNC_OUTBOX,JSON.stringify(this._taskSyncOutbox))}async queueTaskSyncOutboxOperation(e,t){this._taskSyncOutbox=this.compactTaskSyncOutbox([...this._taskSyncOutbox,t]),await this.persistTaskSyncOutbox(e)}async applySiteConfigDefaults(e){if(!(typeof document>`u`))try{let t=document.getElementById(`shadow-claw-site-config`);if(!t?.textContent)return;let n=JSON.parse(t.textContent);if(!n||typeof n!=`object`)return;pn(n),vn(),yn();let r=n.customElements;if((await nK(e)).find(e=>e.groupId===`br:main`)?.toolTags&&await eK(e,w,void 0),(n.settings?.internetAccess??n.settings?.vm_bash_full_internet_access??n.settings?.fullInternetAccess??n.internetAccess)===!0&&await F(e,j.VM_BASH_FULL_INTERNET_ACCESS)!==`true`&&(await U(e,j.VM_BASH_FULL_INTERNET_ACCESS,`true`),this.orchestrator&&(this.orchestrator.vmBashFullInternetAccess=!0),this._vmBashFullInternetAccess.set(!0)),await F(e,j.SITE_CONFIG_SEEDED))return;let i=n.allowedCustomElements||(typeof r==`object`&&!Array.isArray(r)?r.allowedElements:void 0);i!==void 0&&await U(e,j.ALLOWED_CUSTOM_ELEMENTS,JSON.stringify(i));let a=n.allowedCustomElementDomains||(typeof r==`object`&&!Array.isArray(r)?r.allowedDomains:void 0);if(a!==void 0&&await U(e,j.ALLOWED_CUSTOM_ELEMENT_HOST_PATTERNS,JSON.stringify(a)),n.sidebar&&typeof n.sidebar==`object`){let{pagesHidden:t,chatHidden:r,tasksHidden:i,filesHidden:a,defaultPage:o}=n.sidebar;t!==void 0&&await U(e,j.SIDEBAR_PAGES_HIDDEN,String(!!t)),r!==void 0&&await U(e,j.SIDEBAR_CHAT_HIDDEN,String(!!r)),i!==void 0&&await U(e,j.SIDEBAR_TASKS_HIDDEN,String(!!i)),a!==void 0&&await U(e,j.SIDEBAR_FILES_HIDDEN,String(!!a)),o&&typeof o==`string`&&await U(e,j.SIDEBAR_DEFAULT_PAGE,o)}if(n.settings&&typeof n.settings==`object`){let{assistantName:t}=n.settings;t&&typeof t==`string`&&await U(e,j.ASSISTANT_NAME,t);let r=n.settings.internetAccess??n.settings.vm_bash_full_internet_access??n.settings.fullInternetAccess??n.internetAccess;typeof r==`boolean`&&(await U(e,j.VM_BASH_FULL_INTERNET_ACCESS,String(r)),this.orchestrator&&(this.orchestrator.vmBashFullInternetAccess=r),this._vmBashFullInternetAccess.set(r))}let o=(n.settings&&typeof n.settings==`object`?n.settings.defaultToolsProfile:void 0)??n.defaultToolsProfile;if(typeof o==`string`&&o.trim().length>0){let t=o.trim();if(t.toLowerCase()===`none`)await Hq.deactivateProfile(e);else{let n=Hq.profiles.find(e=>e.id.toLowerCase()===t.toLowerCase()||e.name.toLowerCase()===t.toLowerCase());n?await Hq.activateProfile(e,n.id):console.warn(`Default tools profile "${t}" specified in site-config was not found.`)}}if(n.pages&&typeof n.pages==`object`){let{defaultPinnedPage:t}=n.pages;t&&typeof t==`string`&&await U(e,j.DEFAULT_PINNED_PAGE,t)}if(Array.isArray(n.enabledTools)){let t=n.enabledTools.filter(e=>typeof e==`string`&&e.trim().length>0);await Hq.setAllEnabled(e,t),await Hq.setAllDeclarativeEnabled(e,t)}await U(e,j.SITE_CONFIG_SEEDED,`true`)}catch(e){console.warn(`Failed to apply site-config defaults:`,e)}}};const HZ=new VZ;async function UZ(e,t,n){let r=await z(e,t),{dirs:i,filename:a}=Ce(n),o=r;for(let e of i)o=await o.getDirectoryHandle(e);await o.removeEntry(a),t===`br:main`&&i.length===0&&(a===`MEMORY.md`?await NW(e,!0):a===`index.html`&&await RW(e,!0));try{await pZ(e,t,n)}catch{}try{await HZ.removePage(e,n,t)}catch{}}async function WZ(e,t,n){let r=n.replace(/\\/g,`/`).replace(/^\/home\/user\//,`/`).replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean);if(r.length===0)throw Error(`Empty directory path`);for(let n=0;n<2;n++)try{let n=await z(e,t);for(let e of r)n=await n.getDirectoryHandle(e,{create:!0});return}catch(e){if(n===0&&Se(e)){L();continue}throw e}}var GZ=class extends jR{db;groupId;workspacePrefix;constructor(e,t,n,r=`/home/user`){super(n),this.db=e,this.groupId=t,this.workspacePrefix=r}async appendFile(e,t){await super.appendFile(e,t);let n=this._toDbPath(e);if(n!==null){let t=await this._readPathContent(e);await Nn(this.db,this.groupId,n,t)}}async cp(e,t,n){await super.cp(e,t,n);let r=this._toDbPath(t);if(r!==null)try{let e=await super.stat(t);if(!this._isDirectoryStat(e)){let e=await this._readPathContent(t);await Nn(this.db,this.groupId,r,e)}}catch{}}async mkdir(e,t){await super.mkdir(e,t);let n=this._toDbPath(e);n!==null&&n!==``&&await WZ(this.db,this.groupId,n)}async mv(e,t){await super.mv(e,t);let n=!1,r=t,i=this._toDbPath(t);if(i!==null)try{let i=await super.stat(t);if(this._isDirectoryStat(i)){let n=this._basename(e);n&&(r=this._joinPath(t,n))}let a=await super.stat(r);if(!this._isDirectoryStat(a)){let e=this._toDbPath(r);if(e!==null){let t=await this._readPathContent(r);await Nn(this.db,this.groupId,e,t),n=!0}}}catch{}let a=this._toDbPath(e);if(a!==null)try{(i===null||n)&&await UZ(this.db,this.groupId,a)}catch{}}async rm(e,t){await super.rm(e,t);let n=this._toDbPath(e);if(n!==null)try{await UZ(this.db,this.groupId,n)}catch{}}async writeFile(e,t,n){await super.writeFile(e,t,n);let r=this._toDbPath(e);if(r!==null){let t=await this._readPathContent(e);await Nn(this.db,this.groupId,r,t)}}_basename(e){let t=e.split(`/`).filter(Boolean);return t[t.length-1]||``}_isDirectoryStat(e){return e&&typeof e.isDirectory==`function`?!!e.isDirectory():!!e?.isDirectory}_joinPath(e,t){let n=e.replace(/\/+$/,``);return n?`${n}/${t}`:`/${t}`}_toDbPath(e){return e.startsWith(this.workspacePrefix+`/`)?e.slice(this.workspacePrefix.length+1):e===this.workspacePrefix?``:null}async _readPathContent(e){try{return await super.readFileBuffer(e)}catch{return await super.readFile(e)}}};async function KZ(e,t){let n={},r=new Set,i=`/home/user`;async function a(o){let s=await nZ(e,t,o);for(let c of s)if(c.endsWith(`/`)){let e=c.slice(0,-1),t=o===`.`?e:`${o}/${e}`;r.add(t),await a(t)}else{let r=o===`.`?c:`${o}/${c}`,a=`${i}/${r}`;n[a]=async()=>{try{return await OW(e,t,r)}catch{return``}}}}await a(`.`);let o=new GZ(e,t,n,i);for(let e of[...r].sort((e,t)=>e.split(`/`).length-t.split(`/`).length))try{o.mkdirSync(`${i}/${e}`,{recursive:!0})}catch{}return o}async function qZ(e,t,n,r={},i=30,a=!1){try{let i=await new wW({fs:await KZ(e,n),network:{dangerouslyAllowFullInternetAccess:a,denyPrivateRanges:!a}}).exec(t,{env:{HOME:`/home/user`,PATH:`/usr/bin`,PWD:`/home/user`,...r}});return{stdout:i.stdout||``,stderr:i.stderr||``,exitCode:i.exitCode??0}}catch(e){return{stdout:``,stderr:e instanceof Error?e.message:String(e),exitCode:1}}}function JZ(e){let t=e.stdout||``;return e.stderr&&(t+=(t?`
2048
2048
  `:``)+e.stderr),e.exitCode!==0&&!t&&(t=`[exit code: ${e.exitCode}]`),t||`(no output)`}async function YZ(e,t,n,r,i){return JZ(await qZ(e,t,n,{},r,i))}function XZ(e){if(e==null)return null;let t=String(e).trim().toLowerCase();return[`1`,`true`,`yes`,`on`].includes(t)?!0:![`0`,`false`,`no`,`off`].includes(t)&&null}async function ZZ(e){return XZ(await F(e,j.VM_BASH_FULL_INTERNET_ACCESS))??!1}async function QZ(e){if(Mi())return!0;let t=Date.now()+e;for(;Date.now()<t;)if(await new Promise(e=>{setTimeout(e,50)}),Mi())return!0;return Mi()}async function $Z(e,t,n){let r=await F(e,j.VM_BASH_TIMEOUT_SEC),i=Number(r),a=Number.isFinite(i)?Math.min(Math.max(i,1),b):900,o=Number(t.timeout),s=Number.isFinite(o)?Math.min(Math.max(o,1),b):a,c=await ZZ(e),l=Fi(),u=t.stdin?String(t.stdin):``,d=u.length>0,f=`.shadowclaw_stdin`,p=t.command;if(d)if(l===`ext2`){let e=`EOF_SC_${Date.now()}`;p=`(cat << '${e}'\n${u}\n${e}\n) | (${p})`}else p=`{\n${p}\n} < /home/user/${f}; _code=$?; rm -f /home/user/${f}; exit $_code`;try{if(d&&l!==`ext2`&&await Nn(e,n,f,u),l===`disabled`)return await YZ(e,p,n,s,c);if(!Mi()){await ki();let e=Ni();!Mi()&&e.booting&&await QZ(Math.min(s*1e3,3e4))}if(Mi())return await Ai(p,s,{db:e,groupId:n});let t=Ni();return Wr({type:`show-toast`,payload:{duration:7e3,message:`WebVM unavailable for this bash command. ${t.error?`Reason: ${t.error}`:t.booting?`Reason: WebVM is still booting.`:`Reason: WebVM is unavailable.`} Falling back to JavaScript Bash Emulator and retrying WebVM on the next command.`,type:`warning`}}),await YZ(e,p,n,s,c)}finally{d&&l!==`ext2`&&await UZ(e,n,f).catch(()=>{})}}async function eQ(e,t,n,r){let{dirs:i,filename:a}=Ce(n);for(let n=0;n<2;n++)try{let n=await z(e,t);for(let e of i)n=await n.getDirectoryHandle(e,{create:!0});let o=await n.getFileHandle(a,{create:!0});try{await On(o,r);return}catch(t){if(!((t instanceof Error?t.message:String(t)).includes(`Writable file streams are not supported`)&&(await R(e)).type===`opfs`))throw t}let s=t.replace(/:/g,`-`);await kn([_e(),`groups`,s,...i,a],r);return}catch(e){if(n===0&&Se(e)){L();continue}throw e}}const tQ=[{id:`imap`,name:`IMAP Mail`,protocol:`imap`,description:`Read mailboxes and fetch message metadata/content.`,version:`0.1.0`,actions:[`messages.read`,`messages.send`],authTypes:[`basic_userpass`,`oauth`],serviceTypes:[`http_api`],configurableFields:[`host`,`port`,`secure`,`mailboxPath`,`smtpHost`,`smtpPort`,`smtpSecure`,`fromAddress`,`executionMode`,`pollIntervalSec`]}];function nQ(){return[...tQ].sort((e,t)=>e.id.localeCompare(t.id))}function rQ(e){return e&&tQ.find(t=>t.id===e)||null}function iQ(e){if(!e||typeof e!=`object`)return null;let t=e;return!t.serviceType||!t.authType?null:{serviceType:t.serviceType,authType:t.authType,providerId:t.providerId||void 0,accountId:t.accountId||void 0,username:t.username||void 0,headerName:t.headerName||void 0,encryptedSecret:t.encryptedSecret||void 0}}function aQ(e){if(!e||typeof e!=`object`)return null;let t=e;return!t.id||!t.label||!t.pluginId||typeof t.enabled!=`boolean`||typeof t.createdAt!=`number`||typeof t.updatedAt!=`number`||!rQ(t.pluginId)?null:{id:t.id,label:t.label,pluginId:t.pluginId,enabled:t.enabled,config:t.config&&typeof t.config==`object`?{...t.config}:{},credentialRef:iQ(t.credentialRef),createdAt:t.createdAt,updatedAt:t.updatedAt}}async function oQ(e){let t=await F(e,j.INTEGRATION_CONNECTIONS);if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=aQ(e);t&&n.push(t)}return n}async function sQ(e,t){await U(e,j.INTEGRATION_CONNECTIONS,t)}async function cQ(e){return oQ(e)}async function lQ(e,t){if(!t)return null;let n=await oQ(e);return n.find(e=>e.id===t)||n.find(e=>e.label.toLowerCase()===t.toLowerCase())||null}async function uQ(e,t){if(!t.label?.trim())throw Error(`Email connection label is required`);let n=rQ(t.pluginId);if(!n)throw Error(`Unknown email plugin: ${t.pluginId}`);let r=await oQ(e),i=Date.now();if(t.id){let a=r.findIndex(e=>e.id===t.id);if(a!==-1){let o=r[a],s={...o,label:t.label.trim(),pluginId:n.id,enabled:t.enabled??o.enabled,config:t.config?{...t.config}:o.config,updatedAt:i};return r[a]=s,await sQ(e,r),s}}let a={id:t.id||dr(),label:t.label.trim(),pluginId:n.id,enabled:t.enabled??!0,config:t.config?{...t.config}:{},credentialRef:null,createdAt:i,updatedAt:i};return r.push(a),await sQ(e,r),a}async function dQ(e,t,n){if(!t)return null;let r=await oQ(e),i=r.findIndex(e=>e.id===t);if(i===-1)return null;let a={...r[i],credentialRef:n?iQ(n):null,updatedAt:Date.now()};return r[i]=a,await sQ(e,r),a}async function fQ(e,t){if(!t)return!1;let n=await oQ(e),r=n.filter(e=>e.id!==t);return r.length===n.length?!1:(await sQ(e,r),!0)}function pQ(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n==`string`){let e=n.trim();e&&t.push({path:e});continue}if(!n||typeof n!=`object`)continue;let e=typeof n.path==`string`?n.path.trim():``;if(!e)continue;let r=typeof n.filename==`string`?n.filename.trim():``,i=typeof n.content_type==`string`?n.content_type.trim():``;t.push({path:e,filename:r||void 0,contentType:i||void 0})}return t}function mQ(e,t,n){let r=typeof e==`number`?e:Number(e);if(!Number.isFinite(r))return t;let i=r;return typeof n?.min==`number`&&(i=Math.max(n.min,i)),typeof n?.max==`number`&&(i=Math.min(n.max,i)),i}function hQ(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function gQ(e){if(!Array.isArray(e))return[];let t=e.map(e=>typeof e==`number`?e:Number(e)).filter(e=>Number.isFinite(e)&&e>0).map(e=>Math.floor(e));return Array.from(new Set(t))}function _Q(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function vQ(e){let t=e.replace(/\\/g,`/`).split(`/`).filter(Boolean);return t[t.length-1]||`attachment.bin`}function yQ(e){let t=``,n=32768;for(let r=0;r<e.length;r+=n){let i=e.subarray(r,r+n);t+=String.fromCharCode(...i)}return btoa(t)}function bQ(e){let t=e.toLowerCase();if(t.endsWith(`.png`))return`image/png`;if(t.endsWith(`.jpg`)||t.endsWith(`.jpeg`))return`image/jpeg`;if(t.endsWith(`.gif`))return`image/gif`;if(t.endsWith(`.webp`))return`image/webp`;if(t.endsWith(`.pdf`))return`application/pdf`;if(t.endsWith(`.txt`)||t.endsWith(`.md`))return`text/plain`}async function xQ(e,t,n,r=!1){let i=(typeof n.username==`string`?n.username.trim():``)||t.credentialRef?.username||(typeof t.config.username==`string`?t.config.username:``);if(!i)return`Error: Integration connection ${t.id} is missing username credentials.`;if(t.credentialRef?.authType===`oauth`){let n=t.credentialRef.accountId;if(!n)return`Error: Integration connection ${t.id} is missing linked OAuth account.`;let a=await Jn(e,void 0,{accountId:n,authMode:`oauth`,forceRefresh:r});if(!a||a.reauthRequired||!a.token){let e=t.credentialRef?.providerId||`the configured`;return`Error: OAuth account reconnect required for integration ${t.id}.\nOpen Settings -> Integrations, edit this email connection, and click Connect OAuth for ${e} to re-authorize.`}return{authType:`oauth`,username:i,accessToken:a.token}}let a=(typeof n.password==`string`?n.password.trim():``)||t.credentialRef?.encryptedSecret&&await zn(t.credentialRef.encryptedSecret)||``;return a?{authType:`basic_userpass`,username:i,password:a}:`Error: Integration connection ${t.id} is missing password credentials.`}function SQ(e){return e.replace(/[\\/:*?"<>|\x00-\x1f]/g,`_`).trim()||`attachment.bin`}async function CQ(e,t,n,r){let i=SQ(r),a=i.lastIndexOf(`.`),o=a>0?i.slice(0,a):i,s=a>0?i.slice(a):``,c=n.trim().replace(/^\/+|\/+$/g,``);for(let n=0;n<1e3;n++){let r=n===0?i:`${o}-${n+1}${s}`,a=c?`${c}/${r}`:r;if(!await AW(e,t,a))return a}return c?`${c}/${dr()}-${i}`:`${dr()}-${i}`}async function wQ(e,t,n){let r=typeof t.action==`string`?t.action.trim():``;if(!r)return`Error: manage_email requires action.`;if(r===`list_plugins`){let e=nQ();return e.length?e.map(e=>`- ${e.id} (${e.protocol})\n Name: ${e.name}\n Actions: ${e.actions.join(`, `)}\n Auth: ${e.authTypes.join(`, `)}\n Fields: ${e.configurableFields.join(`, `)||`(none)`}`).join(`
2049
2049
 
2050
2050
  `):`No integration plugins are available.`}if(r===`list_connections`){let t=await cQ(e);return t.length?t.map(e=>{let t=rQ(e.pluginId),n=Object.keys(e.config||{});return`- ${e.id} (${e.label})\n Plugin: ${e.pluginId}${t?` (${t.name})`:``}\n Enabled: ${e.enabled}\n Config keys: ${n.join(`, `)||`(none)`}`}).join(`
@@ -2223,7 +2223,7 @@ const restoreGlobals = applyGlobalShadows();
2223
2223
  `);for(let e=0;e<o.length;e++){let t=o[e],n;if(d){let e=t.length>t1?t.slice(0,t1):t;n=d.test(e)}else n=t.includes(i);if(n){let n=t.length>500?t.slice(0,500)+`…`:t;if(p.push(`${r}:${e+1}: ${n}`),p.length>=500){p.push(`... (results truncated at 500 matches)`),g=!0;return}}}}}}return await _(a||`.`),h&&p.push(`... (file visit limit of ${l} reached; narrow your search with path or file_glob)`),p.length===0?`No matches found.`:p.join(`
2224
2224
  `)}async function i1(e,t,n){if(!t.path||typeof t.path!=`string`)return`Error: send_file requires a valid path string.`;let r=n.startsWith(`peer:`),i=n.startsWith(`room:`);if(!r&&!i)return`Error: send_file only works in peer or room conversations (groupId must start with 'peer:' or 'room:'). The current conversation is not a peer session.`;let a=EQ(t.path);return a?TQ(a)?`Error: send_file path cannot contain '..' segments.`:await AW(e,n,a)?(Wr({payload:{groupId:n,path:a},type:`send-file`}),`Sending file to ${i?`room`:`peer`}: ${a}. The transfer will proceed in the background — you can continue chatting.`):`Error: send_file could not find ${a} in the workspace.`:`Error: send_file received an empty file path.`}async function a1(e,t,n){return await Nn(e,n,`MEMORY.md`,t.content),`Memory updated successfully.`}async function o1(e,t,n){return await Nn(e,n,t.path,t.content),`Written ${t.content.length} bytes to ${t.path}`}const s1=2e3;async function c1(e,t=w){let n=[],r=[],i=t===`br:main`?[w]:[t,w];for(let a of i)try{let i=await z(e,a),o=[],s=0;async function c(e,t){if(s+=1,s>s1){r.push({path:`.agents/skills`,message:`Skill discovery stopped after ${s1} directories`});return}for await(let[n,r]of e.entries()){let e=t?`${t}/${n}`:n;r.kind===`directory`?await c(r,e):n===`SKILL.md`&&e.startsWith(`.agents/skills/`)&&o.push(e)}}try{await c(await(await i.getDirectoryHandle(`.agents`)).getDirectoryHandle(`skills`),`.agents/skills`)}catch{continue}for(let i of o.sort())try{let o=Pq(i,await we(e,a,i));if(n.some(e=>e.name===o.name)){a===t&&r.push({path:i,message:`Duplicate skill name: ${o.name}`});continue}o.groupId=a,n.push(o)}catch(e){r.push({path:i,message:e instanceof Error?e.message:String(e)})}}catch{}return{skills:n,diagnostics:r}}async function l1(e,t=w,n){let r=(await c1(e,t)).skills.find(e=>e.name===n);if(!r)return null;let i=r.groupId||t,a=Pq(r.path,await we(e,i,r.path));return a.groupId=i,a.resources=await u1(e,i,a.basePath),a}async function u1(e,t,n){let r=await z(e,t),i=n.split(`/`).filter(Boolean),a=r;for(let e of i)a=await a.getDirectoryHandle(e);let o=[];async function s(e,t){for await(let[r,i]of e.entries()){let e=`${t}/${r}`;i.kind===`directory`?await s(i,e):e!==`${n}/SKILL.md`&&o.push(e)}}return await s(a,n),o.sort()}async function d1(e,t,n){let r=typeof t.name==`string`?t.name.trim():``,i=await c1(e,n),a=i.skills.map(e=>e.name),o=a.length>0?a.join(`, `):`(none)`;if(!r){let e=`Error: activate_skill requires a skill name. Available skills: ${o}.`;return i.diagnostics.length>0&&(e+=` (Note: ${i.diagnostics.length} skill file(s) had errors: ${i.diagnostics.map(e=>`${e.path}: ${e.message}`).join(`; `)})`),e}let s=await l1(e,n,r);if(!s){let e=i.diagnostics.find(e=>e.path.toLowerCase().includes(r.toLowerCase())||e.message.toLowerCase().includes(r.toLowerCase()));if(e)return`Error: skill "${r}" was found at "${e.path}" but failed to load: ${e.message}. Please fix the frontmatter in SKILL.md. Available skills: ${o}.`;let t=`Error: skill "${r}" was not found in this conversation workspace. Available skills: ${o}.`;return i.diagnostics.length>0&&(t+=` (Note: ${i.diagnostics.length} skill file(s) had errors: ${i.diagnostics.map(e=>`${e.path}: ${e.message}`).join(`; `)})`),t}return s.disableModelInvocation?`Error: skill "${r}" is not available for model-driven activation.`:[`<skill_content name="${s.name}">`,s.body||`(This skill has no instructions.)`,`Skill directory: ${s.basePath}`,`Resolve all relative paths against the skill directory.`,s.resources&&s.resources.length>0?[`<skill_resources>`,...s.resources.map(e=>` <file>${e}</file>`),`</skill_resources>`].join(`
2225
2225
  `):``,`</skill_content>`].filter(Boolean).join(`
2226
- `)}async function f1(e,t,n){let r=dr();return Wr({type:`request-native-ai-task`,payload:{id:r,groupId:e,taskType:t,input:n}}),await new Promise((e,t)=>{globalThis.pendingNativeAiResolvers=globalThis.pendingNativeAiResolvers||{},globalThis.pendingNativeAiResolvers[r]={resolve:e,reject:t}})}async function p1(e,t){let n=String(e.text||``).trim();if(!n)return`Error: text is required for summarize_text`;try{return await f1(t,`summarize`,{text:n,type:e.type,format:e.format,length:e.length,preference:e.preference,context:e.context})}catch(e){return`Error summarizing text: ${e instanceof Error?e.message:String(e)}`}}async function m1(e,t){let n=String(e.prompt||``).trim();if(!n)return`Error: prompt is required for write_text`;try{return await f1(t,`write`,{prompt:n,context:e.context})}catch(e){return`Error writing text: ${e instanceof Error?e.message:String(e)}`}}async function h1(e,t){let n=String(e.text||``).trim();if(!n)return`Error: text is required for rewrite_text`;try{return await f1(t,`rewrite`,{text:n,tone:e.tone,length:e.length,context:e.context})}catch(e){return`Error rewriting text: ${e instanceof Error?e.message:String(e)}`}}async function g1(e,t){let n=String(e.text||``).trim();if(!n)return`Error: text is required for proofread_text`;try{return await f1(t,`proofread`,{text:n,context:e.context})}catch(e){return`Error proofreading text: ${e instanceof Error?e.message:String(e)}`}}async function _1(e,t){let n=String(e.text||``).trim();if(!n)return`Error: text is required for detect_language`;try{let e=await f1(t,`detect-language`,{text:n});return JSON.stringify(e,null,2)}catch(e){return`Error detecting language: ${e instanceof Error?e.message:String(e)}`}}async function v1(e,t){let n=String(e.text||``).trim(),r=String(e.sourceLanguage||``).trim(),i=String(e.targetLanguage||``).trim();if(!n||!r||!i)return`Error: text, sourceLanguage, and targetLanguage are required for translate_text`;try{return await f1(t,`translate`,{text:n,sourceLanguage:r,targetLanguage:i})}catch(e){return`Error translating text: ${e instanceof Error?e.message:String(e)}`}}function y1(e,t,n,r){let i=t*2**e,a=Math.min(i,n),o=a*r*Math.random();return Math.max(0,a-o)}function b1(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason??new DOMException(`Aborted`,`AbortError`));return}let i=setTimeout(n,e);if(t){let e=()=>{clearTimeout(i),r(t.reason??new DOMException(`Aborted`,`AbortError`))};t.addEventListener(`abort`,e,{once:!0});let a=n;n=(n=>{t.removeEventListener(`abort`,e),a(n)})}})}async function x1(e,t={}){let{maxRetries:n=3,baseDelayMs:r=1e3,maxDelayMs:i=3e4,jitterFactor:a=.5,shouldRetry:o=()=>!0,onRetry:s,signal:c}=t,l;for(let t=0;t<=n;t++){if(c?.aborted)throw c.reason??new DOMException(`Aborted`,`AbortError`);try{return await e()}catch(e){if(l=e,e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&e.name===`AbortError`)throw e;if(t>=n||!o(e,t+1))break;let u=y1(t,r,i,a);s&&s(t+1,n,u,e),await b1(u,c)}}throw l}const S1=new Set([408,429,500,502,503,504]);function C1(e){if(e instanceof TypeError)return!0;if(typeof e?.status==`number`)return S1.has(e.status);if(e instanceof Error){let t=e.message,n=t.match(/\b(4\d{2}|5\d{2})\b/);if(n)return S1.has(Number(n[1]));if(/network|ECONNRESET|ECONNREFUSED|ETIMEDOUT|fetch failed|EAI_AGAIN|EAI_NONAME|getaddrinfo/i.test(t))return!0}return!1}function w1(e){return e instanceof TypeError?!0:e&&typeof e.status==`number`?S1.has(e.status):e instanceof Error&&/network|ECONNRESET|ECONNREFUSED|ETIMEDOUT|fetch failed|EAI_AGAIN|EAI_NONAME|getaddrinfo/i.test(e.message)}let T1=null;async function E1(){return T1||=import(`./git-D4n46G9B.js`),T1}function D1(e){if(!Array.isArray(e))return null;let t=e.map(e=>typeof e==`string`?e:typeof e?.name==`string`?e.name:null).filter(Boolean);return new Set(t)}async function O1(e,t,n,r,i={}){try{let a=D1(i.allowedTools);if(a&&!a.has(t))return`Tool "${t}" is not allowed in the current context. Do not call it again. Use one of the available tools or ask for help.`;if((i.isScheduledTask||i.isTaskExecution)&&t===`run_task`)return`Tool "run_task" cannot be called from within a task execution to prevent infinite loops.`;if(i.isScheduledTask&&new Set([`create_task`,`update_task`,`delete_task`,`enable_task`,`disable_task`,`send_notification`,`create_room`,`invite_to_room`,`leave_room`]).has(t))return`Tool "${t}" is not allowed during scheduled task execution to prevent recursion.`;switch(t){case`bash`:return await $Z(e,n,r);case`read_file`:return await e1(e,n,r);case`open_file`:return await Y$(e,n,r);case`attach_file_to_chat`:return await L$(e,n,r);case`send_file`:return await i1(e,n,r);case`write_file`:return await o1(e,n,r);case`delete_file`:return await W$(e,n,r);case`move_file`:return await J$(e,n,r);case`copy_file`:return await H$(e,n,r);case`create_directory`:return await U$(e,n,r);case`patch_file`:return await X$(e,n,r);case`list_files`:return await K$(e,n,r);case`manage_tools`:return k$(n,r);case`list_tool_profiles`:return await O$(e);case`fetch_url`:return await PQ(e,n,r,{buildAuthHeaders:Qn,fetchImpl:fetch,fetchMaxResponse:102400,isRetryableFetchError:w1,post:Wr,resolveGitCredentials:ar,resolveServiceCredentials:Jn,retryableStatusCodes:S1,stripHtml:Jr,uploadGroupFile:Mn,withRetry:x1});case`fetch_file`:return await AQ(e,n,r,{buildAuthHeaders:Qn,fetchImpl:fetch,isRetryableFetchError:w1,post:Wr,resolveGitCredentials:ar,resolveServiceCredentials:Jn,retryableStatusCodes:S1,uploadGroupFile:Mn,withRetry:x1,writeGroupFile:Nn});case`update_memory`:return await a1(e,n,r);case`create_task`:return c$(n,r);case`javascript`:return await E$(e,n);case`activate_skill`:return await d1(e,n,r);case`list_tasks`:return await p$(e,r);case`update_task`:return await h$(e,n,r);case`enable_task`:return await f$(e,n,r);case`disable_task`:return await d$(e,n,r);case`delete_task`:return l$(n,r);case`run_task`:return await m$(e,n,r);case`clear_chat`:return _$(r);case`show_toast`:return N$(n);case`send_notification`:return M$(n,r);case`create_room`:return XQ(n);case`invite_to_room`:return ZQ(n,r);case`leave_room`:return QQ(n,r);case`list_room_members`:return await $Q(e,n,r);case`manage_email`:case`manage_integration`:return wQ(e,n,r);case`email_read_messages`:case`integration_read_messages`:return O1(e,`manage_email`,{...n,action:`read_messages`},r);case`email_send_message`:case`integration_send_message`:return O1(e,`manage_email`,{...n,action:`send_message`},r);case`remote_mcp_list_tools`:return await JQ(e,n,r,{callRemoteMcpTool:Rr,listRemoteMcpTools:Lr,McpReauthRequiredError:Tr,post:Wr});case`remote_mcp_call_tool`:return await YQ(e,n,r,{callRemoteMcpTool:Rr,listRemoteMcpTools:Lr,McpReauthRequiredError:Tr,post:Wr});case`git_clone`:case`git_checkout`:case`git_branch`:case`git_status`:case`git_add`:case`git_log`:case`git_diff`:case`git_branches`:case`git_list_repos`:case`git_delete_repo`:case`git_commit`:case`git_pull`:case`git_push`:case`git_merge`:case`git_reset`:case`git_fetch`:case`git_read_file_at_ref`:case`git_show`:case`git_delete_branch`:case`git_init`:case`git_tag`:case`git_remote`:case`git_config`:case`git_unstage`:{let i=await E1();return await BQ(e,t,n,r,{configKeys:{GIT_CORS_PROXY:j.GIT_CORS_PROXY,GIT_PROXY_URL:j.GIT_PROXY_URL,GIT_AUTHOR_NAME:j.GIT_AUTHOR_NAME,GIT_AUTHOR_EMAIL:j.GIT_AUTHOR_EMAIL},getConfig:F,getGroupDir:z,getProxyUrl:i.getProxyUrl,getRemoteUrl:i.getRemoteUrl,gitAdd:i.gitAdd,gitBranch:i.gitBranch,gitCheckout:i.gitCheckout,gitClone:i.gitClone,gitCommit:i.gitCommit,gitConfig:i.gitConfig,gitDeleteBranch:i.gitDeleteBranch,gitDeleteRepo:i.gitDeleteRepo,gitDiff:i.gitDiff,gitFetch:i.gitFetch,gitInit:i.gitInit,gitListBranches:i.gitListBranches,gitListRepos:i.gitListRepos,gitListTags:i.gitListTags,gitLog:i.gitLog,gitMerge:i.gitMerge,gitPull:i.gitPull,gitPush:i.gitPush,gitReadFileAtRef:i.gitReadFileAtRef,gitRemote:i.gitRemote,gitReset:i.gitReset,gitShow:i.gitShow,gitStatus:i.gitStatus,gitTag:i.gitTag,gitUnstage:i.gitUnstage,readGroupFile:we,resolveGitCredentials:ar})}case`list_components`:return D$();case`render_component`:return j$(n,r);case`spawn_subagent`:return i.invokeContext?await s$(n,r,i.invokeContext):`Error: spawn_subagent requires an active agent invocation context. This tool cannot be called directly.`;case`get_current_time`:return v$(n);case`search_files`:return await r1(e,n,r,{maxFileBytes:Hq.searchFilesMaxFileBytes,maxFilesVisited:Hq.searchFilesMaxFilesVisited,skipDirs:Hq.searchFilesSkipDirsSet});case`diff_files`:return await G$(e,n,r);case`ask_user`:return await g$(n,r);case`web_search`:return await P$(n);case`summarize_text`:return await p1(n,r);case`write_text`:return await m1(n,r);case`rewrite_text`:return await h1(n,r);case`proofread_text`:return await g1(n,r);case`detect_language`:return await _1(n,r);case`translate_text`:return await v1(n,r);default:{let a=await MK(e,r,t);if(!a)return`Unknown tool: ${t}`;let o=i.declarativeDepth||0;if(o>=8)return`Tool error (${t}): declarative tool nesting limit exceeded.`;if(a.execution.type===`tool`){let s=a.execution.name;return s?await O1(e,s,a.execution.input?{...n,...a.execution.input}:n,r,{...i,declarativeDepth:o+1}):`Tool error (${t}): declarative tool target is missing.`}return a.execution.type===`bash`?await $Z(e,{command:a.execution.command,stdin:JSON.stringify(n)},r):await E$(e,{code:a.execution.code,data:JSON.stringify(n)})}}}catch(e){return`Tool error (${t}): ${e instanceof Error?e.message:String(e)}`}}function k1(e){return[...e,{role:`user`,content:`Please provide a concise summary of our entire conversation so far. Include all key facts, decisions, code discussed, and important context. This summary will replace the full history.`}]}function A1(e,t,n,r){Wr(qq(e,t,n,r))}const j1=6e4,M1=new Map;function N1(e){let t=M1.get(e);if(t)return t;let n={recentCalls:[],nextAllowedAt:0,remoteLimit:null,remoteRemaining:null,remoteResetAt:null};return M1.set(e,n),n}function P1(){return Date.now()}function F1(e){if(!e)return null;let t=Number(e.trim());return Number.isFinite(t)?t:null}function I1(e){if(!e)return null;let t=e.trim(),n=Number(t);if(Number.isFinite(n))return n<=0?null:Math.round(n*1e3);let r=Date.parse(t);if(!Number.isFinite(r))return null;let i=r-P1();return i>0?i:null}function L1(e){let t=F1(e);return t===null||t<=0?null:t>=0xe8d4a51000?Math.round(t):t>=1e9?Math.round(t*1e3):P1()+Math.round(t*1e3)}async function R1(e,t){e<=0||await new Promise((n,r)=>{let i=setTimeout(()=>{o(),n()},e),a=()=>{o(),r(new DOMException(`Aborted`,`AbortError`))},o=()=>{i&&=(clearTimeout(i),null),t?.removeEventListener(`abort`,a)};if(t?.aborted){a();return}t?.addEventListener(`abort`,a)})}function z1(e,t){if(!Number.isFinite(t)||t<=0)return 0;let n=P1();if(e.recentCalls=e.recentCalls.filter(e=>n-e<j1),e.recentCalls.length<t)return 0;let r=e.recentCalls[0]||n;return Math.max(0,j1-(n-r))}function B1(e){let t=P1(),n=0;return e.nextAllowedAt>t&&(n=Math.max(n,e.nextAllowedAt-t)),e.remoteRemaining!==null&&e.remoteRemaining<=0&&e.remoteResetAt!==null&&e.remoteResetAt>t&&(n=Math.max(n,e.remoteResetAt-t)),n}async function V1(e,t,n,r){let i=N1(e);for(;;){let e=z1(i,n.callsPerMinute),a=n.autoAdapt?B1(i):0,o=Math.max(e,a);if(o<=0){let e=P1();if(n.callsPerMinute>0&&i.recentCalls.push(e),n.autoAdapt&&i.remoteRemaining!==null&&i.remoteRemaining>0&&i.remoteResetAt!==null&&i.remoteResetAt>e){let t=i.remoteResetAt-e,n=Math.max(1,i.remoteRemaining),r=Math.ceil(t/n);i.nextAllowedAt=Math.max(i.nextAllowedAt,e+r)}return}o>=1e3&&Wr({type:`thinking-log`,payload:{groupId:t,level:`info`,label:`Rate limiter`,message:`Waiting ${Math.ceil(o/1e3)}s before next provider call to avoid 429s.`,timestamp:Date.now()}}),await R1(o,r)}}function H1(e,t,n){if(!n.autoAdapt||!t||typeof t.get!=`function`)return;let r=N1(e),i=P1(),a=F1(t.get(`x-ratelimit-limit`)),o=F1(t.get(`x-ratelimit-remaining`)),s=L1(t.get(`x-ratelimit-reset`));a!==null&&(r.remoteLimit=Math.max(0,Math.floor(a))),o!==null&&(r.remoteRemaining=Math.max(0,Math.floor(o))),s!==null&&(r.remoteResetAt=s);let c=I1(t.get(`retry-after`));c!==null&&(r.nextAllowedAt=Math.max(r.nextAllowedAt,i+c)),r.remoteRemaining!==null&&r.remoteRemaining<=0&&r.remoteResetAt!==null&&r.remoteResetAt>i&&(r.nextAllowedAt=Math.max(r.nextAllowedAt,r.remoteResetAt))}async function U1(e,t,n){let{groupId:r,messages:i,systemPrompt:a,apiKey:o,model:s,maxTokens:c=4096,provider:l,storageHandle:u,providerHeaders:d={},contextCompression:f=!1,rateLimitCallsPerMinute:p=0,rateLimitAutoAdapt:m=!0}=t,h={callsPerMinute:Number.isFinite(p)?Math.max(0,Math.floor(p)):0,autoAdapt:m!==!1};u&&xe(u);let g=O(l);if(!g){Wr({type:`error`,payload:{groupId:r,error:`Unknown provider: ${l}`}});return}let _=g;Wr({type:`typing`,payload:{groupId:r}}),A1(r,`info`,`Compacting context`,`Summarizing ${i.length} messages`);try{let e=tX(_,k1(i),[],{model:s,maxTokens:Math.min(c,4096),system:aX(a),contextCompression:f}),t={...WY(_,o),...d};await V1(l,r,h,n);let u=await fetch(_.baseUrl,{method:`POST`,headers:t,body:JSON.stringify(e),signal:n});if(H1(l,u.headers,h),!u.ok){let e=await u.text();throw Error(`${_.name} API error ${u.status}: ${e}`)}let p=rX(_,await u.json()).content.filter(e=>e.type===`text`).map(e=>e.text).join(``);A1(r,`info`,`Compaction complete`,`Summary: ${p.length} chars`),Wr({type:`compact-done`,payload:{groupId:r,summary:p}})}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;Wr({type:`error`,payload:{groupId:r,error:`Compaction failed: ${e instanceof Error?e.message:String(e)}`}})}}function W1(e,t,n){let r=t.input_tokens||0,i=t.output_tokens||0,a=t.cache_read_input_tokens||0,o=t.cache_creation_input_tokens||0;return{type:`token-usage`,payload:{groupId:e,inputTokens:r,outputTokens:i,cacheReadTokens:a,cacheCreationTokens:o,totalTokens:r+i+a+o,contextLimit:n}}}async function*G1(e,t){let n=e.getReader(),r=new TextDecoder,i=``;try{for(;!t?.aborted;){let{done:e,value:t}=await n.read();if(e)break;i+=r.decode(t,{stream:!0});let a=i.split(`
2226
+ `)}async function f1(e,t,n){let r=dr();return Wr({type:`request-native-ai-task`,payload:{id:r,groupId:e,taskType:t,input:n}}),await new Promise((e,t)=>{globalThis.pendingNativeAiResolvers=globalThis.pendingNativeAiResolvers||{},globalThis.pendingNativeAiResolvers[r]={resolve:e,reject:t}})}async function p1(e,t){let n=String(e.text||``).trim();if(!n)return`Error: text is required for summarize_text`;try{return await f1(t,`summarize`,{text:n,type:e.type,format:e.format,length:e.length,preference:e.preference,context:e.context})}catch(e){return`Error summarizing text: ${e instanceof Error?e.message:String(e)}`}}async function m1(e,t){let n=String(e.prompt||``).trim();if(!n)return`Error: prompt is required for write_text`;try{return await f1(t,`write`,{prompt:n,context:e.context})}catch(e){return`Error writing text: ${e instanceof Error?e.message:String(e)}`}}async function h1(e,t){let n=String(e.text||``).trim();if(!n)return`Error: text is required for rewrite_text`;try{return await f1(t,`rewrite`,{text:n,tone:e.tone,length:e.length,context:e.context})}catch(e){return`Error rewriting text: ${e instanceof Error?e.message:String(e)}`}}async function g1(e,t){let n=String(e.text||``).trim();if(!n)return`Error: text is required for proofread_text`;try{return await f1(t,`proofread`,{text:n,context:e.context})}catch(e){return`Error proofreading text: ${e instanceof Error?e.message:String(e)}`}}async function _1(e,t){let n=String(e.text||``).trim();if(!n)return`Error: text is required for detect_language`;try{let e=await f1(t,`detect-language`,{text:n});return JSON.stringify(e,null,2)}catch(e){return`Error detecting language: ${e instanceof Error?e.message:String(e)}`}}async function v1(e,t){let n=String(e.text||``).trim(),r=String(e.sourceLanguage||``).trim(),i=String(e.targetLanguage||``).trim();if(!n||!r||!i)return`Error: text, sourceLanguage, and targetLanguage are required for translate_text`;try{return await f1(t,`translate`,{text:n,sourceLanguage:r,targetLanguage:i})}catch(e){return`Error translating text: ${e instanceof Error?e.message:String(e)}`}}function y1(e,t,n,r){let i=t*2**e,a=Math.min(i,n),o=a*r*Math.random();return Math.max(0,a-o)}function b1(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason??new DOMException(`Aborted`,`AbortError`));return}let i=setTimeout(n,e);if(t){let e=()=>{clearTimeout(i),r(t.reason??new DOMException(`Aborted`,`AbortError`))};t.addEventListener(`abort`,e,{once:!0});let a=n;n=(n=>{t.removeEventListener(`abort`,e),a(n)})}})}async function x1(e,t={}){let{maxRetries:n=3,baseDelayMs:r=1e3,maxDelayMs:i=3e4,jitterFactor:a=.5,shouldRetry:o=()=>!0,onRetry:s,signal:c}=t,l;for(let t=0;t<=n;t++){if(c?.aborted)throw c.reason??new DOMException(`Aborted`,`AbortError`);try{return await e()}catch(e){if(l=e,e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&e.name===`AbortError`)throw e;if(t>=n||!o(e,t+1))break;let u=y1(t,r,i,a);s&&s(t+1,n,u,e),await b1(u,c)}}throw l}const S1=new Set([408,429,500,502,503,504]);function C1(e){if(e instanceof TypeError)return!0;if(typeof e?.status==`number`)return S1.has(e.status);if(e instanceof Error){let t=e.message,n=t.match(/\b(4\d{2}|5\d{2})\b/);if(n)return S1.has(Number(n[1]));if(/network|ECONNRESET|ECONNREFUSED|ETIMEDOUT|fetch failed|EAI_AGAIN|EAI_NONAME|getaddrinfo/i.test(t))return!0}return!1}function w1(e){return e instanceof TypeError?!0:e&&typeof e.status==`number`?S1.has(e.status):e instanceof Error&&/network|ECONNRESET|ECONNREFUSED|ETIMEDOUT|fetch failed|EAI_AGAIN|EAI_NONAME|getaddrinfo/i.test(e.message)}let T1=null;async function E1(){return T1||=import(`./git-DgFF7xTW.js`),T1}function D1(e){if(!Array.isArray(e))return null;let t=e.map(e=>typeof e==`string`?e:typeof e?.name==`string`?e.name:null).filter(Boolean);return new Set(t)}async function O1(e,t,n,r,i={}){try{let a=D1(i.allowedTools);if(a&&!a.has(t))return`Tool "${t}" is not allowed in the current context. Do not call it again. Use one of the available tools or ask for help.`;if((i.isScheduledTask||i.isTaskExecution)&&t===`run_task`)return`Tool "run_task" cannot be called from within a task execution to prevent infinite loops.`;if(i.isScheduledTask&&new Set([`create_task`,`update_task`,`delete_task`,`enable_task`,`disable_task`,`send_notification`,`create_room`,`invite_to_room`,`leave_room`]).has(t))return`Tool "${t}" is not allowed during scheduled task execution to prevent recursion.`;switch(t){case`bash`:return await $Z(e,n,r);case`read_file`:return await e1(e,n,r);case`open_file`:return await Y$(e,n,r);case`attach_file_to_chat`:return await L$(e,n,r);case`send_file`:return await i1(e,n,r);case`write_file`:return await o1(e,n,r);case`delete_file`:return await W$(e,n,r);case`move_file`:return await J$(e,n,r);case`copy_file`:return await H$(e,n,r);case`create_directory`:return await U$(e,n,r);case`patch_file`:return await X$(e,n,r);case`list_files`:return await K$(e,n,r);case`manage_tools`:return k$(n,r);case`list_tool_profiles`:return await O$(e);case`fetch_url`:return await PQ(e,n,r,{buildAuthHeaders:Qn,fetchImpl:fetch,fetchMaxResponse:102400,isRetryableFetchError:w1,post:Wr,resolveGitCredentials:ar,resolveServiceCredentials:Jn,retryableStatusCodes:S1,stripHtml:Jr,uploadGroupFile:Mn,withRetry:x1});case`fetch_file`:return await AQ(e,n,r,{buildAuthHeaders:Qn,fetchImpl:fetch,isRetryableFetchError:w1,post:Wr,resolveGitCredentials:ar,resolveServiceCredentials:Jn,retryableStatusCodes:S1,uploadGroupFile:Mn,withRetry:x1,writeGroupFile:Nn});case`update_memory`:return await a1(e,n,r);case`create_task`:return c$(n,r);case`javascript`:return await E$(e,n);case`activate_skill`:return await d1(e,n,r);case`list_tasks`:return await p$(e,r);case`update_task`:return await h$(e,n,r);case`enable_task`:return await f$(e,n,r);case`disable_task`:return await d$(e,n,r);case`delete_task`:return l$(n,r);case`run_task`:return await m$(e,n,r);case`clear_chat`:return _$(r);case`show_toast`:return N$(n);case`send_notification`:return M$(n,r);case`create_room`:return XQ(n);case`invite_to_room`:return ZQ(n,r);case`leave_room`:return QQ(n,r);case`list_room_members`:return await $Q(e,n,r);case`manage_email`:case`manage_integration`:return wQ(e,n,r);case`email_read_messages`:case`integration_read_messages`:return O1(e,`manage_email`,{...n,action:`read_messages`},r);case`email_send_message`:case`integration_send_message`:return O1(e,`manage_email`,{...n,action:`send_message`},r);case`remote_mcp_list_tools`:return await JQ(e,n,r,{callRemoteMcpTool:Rr,listRemoteMcpTools:Lr,McpReauthRequiredError:Tr,post:Wr});case`remote_mcp_call_tool`:return await YQ(e,n,r,{callRemoteMcpTool:Rr,listRemoteMcpTools:Lr,McpReauthRequiredError:Tr,post:Wr});case`git_clone`:case`git_checkout`:case`git_branch`:case`git_status`:case`git_add`:case`git_log`:case`git_diff`:case`git_branches`:case`git_list_repos`:case`git_delete_repo`:case`git_commit`:case`git_pull`:case`git_push`:case`git_merge`:case`git_reset`:case`git_fetch`:case`git_read_file_at_ref`:case`git_show`:case`git_delete_branch`:case`git_init`:case`git_tag`:case`git_remote`:case`git_config`:case`git_unstage`:{let i=await E1();return await BQ(e,t,n,r,{configKeys:{GIT_CORS_PROXY:j.GIT_CORS_PROXY,GIT_PROXY_URL:j.GIT_PROXY_URL,GIT_AUTHOR_NAME:j.GIT_AUTHOR_NAME,GIT_AUTHOR_EMAIL:j.GIT_AUTHOR_EMAIL},getConfig:F,getGroupDir:z,getProxyUrl:i.getProxyUrl,getRemoteUrl:i.getRemoteUrl,gitAdd:i.gitAdd,gitBranch:i.gitBranch,gitCheckout:i.gitCheckout,gitClone:i.gitClone,gitCommit:i.gitCommit,gitConfig:i.gitConfig,gitDeleteBranch:i.gitDeleteBranch,gitDeleteRepo:i.gitDeleteRepo,gitDiff:i.gitDiff,gitFetch:i.gitFetch,gitInit:i.gitInit,gitListBranches:i.gitListBranches,gitListRepos:i.gitListRepos,gitListTags:i.gitListTags,gitLog:i.gitLog,gitMerge:i.gitMerge,gitPull:i.gitPull,gitPush:i.gitPush,gitReadFileAtRef:i.gitReadFileAtRef,gitRemote:i.gitRemote,gitReset:i.gitReset,gitShow:i.gitShow,gitStatus:i.gitStatus,gitTag:i.gitTag,gitUnstage:i.gitUnstage,readGroupFile:we,resolveGitCredentials:ar})}case`list_components`:return D$();case`render_component`:return j$(n,r);case`spawn_subagent`:return i.invokeContext?await s$(n,r,i.invokeContext):`Error: spawn_subagent requires an active agent invocation context. This tool cannot be called directly.`;case`get_current_time`:return v$(n);case`search_files`:return await r1(e,n,r,{maxFileBytes:Hq.searchFilesMaxFileBytes,maxFilesVisited:Hq.searchFilesMaxFilesVisited,skipDirs:Hq.searchFilesSkipDirsSet});case`diff_files`:return await G$(e,n,r);case`ask_user`:return await g$(n,r);case`web_search`:return await P$(n);case`summarize_text`:return await p1(n,r);case`write_text`:return await m1(n,r);case`rewrite_text`:return await h1(n,r);case`proofread_text`:return await g1(n,r);case`detect_language`:return await _1(n,r);case`translate_text`:return await v1(n,r);default:{let a=await MK(e,r,t);if(!a)return`Unknown tool: ${t}`;let o=i.declarativeDepth||0;if(o>=8)return`Tool error (${t}): declarative tool nesting limit exceeded.`;if(a.execution.type===`tool`){let s=a.execution.name;return s?await O1(e,s,a.execution.input?{...n,...a.execution.input}:n,r,{...i,declarativeDepth:o+1}):`Tool error (${t}): declarative tool target is missing.`}return a.execution.type===`bash`?await $Z(e,{command:a.execution.command,stdin:JSON.stringify(n)},r):await E$(e,{code:a.execution.code,data:JSON.stringify(n)})}}}catch(e){return`Tool error (${t}): ${e instanceof Error?e.message:String(e)}`}}function k1(e){return[...e,{role:`user`,content:`Please provide a concise summary of our entire conversation so far. Include all key facts, decisions, code discussed, and important context. This summary will replace the full history.`}]}function A1(e,t,n,r){Wr(qq(e,t,n,r))}const j1=6e4,M1=new Map;function N1(e){let t=M1.get(e);if(t)return t;let n={recentCalls:[],nextAllowedAt:0,remoteLimit:null,remoteRemaining:null,remoteResetAt:null};return M1.set(e,n),n}function P1(){return Date.now()}function F1(e){if(!e)return null;let t=Number(e.trim());return Number.isFinite(t)?t:null}function I1(e){if(!e)return null;let t=e.trim(),n=Number(t);if(Number.isFinite(n))return n<=0?null:Math.round(n*1e3);let r=Date.parse(t);if(!Number.isFinite(r))return null;let i=r-P1();return i>0?i:null}function L1(e){let t=F1(e);return t===null||t<=0?null:t>=0xe8d4a51000?Math.round(t):t>=1e9?Math.round(t*1e3):P1()+Math.round(t*1e3)}async function R1(e,t){e<=0||await new Promise((n,r)=>{let i=setTimeout(()=>{o(),n()},e),a=()=>{o(),r(new DOMException(`Aborted`,`AbortError`))},o=()=>{i&&=(clearTimeout(i),null),t?.removeEventListener(`abort`,a)};if(t?.aborted){a();return}t?.addEventListener(`abort`,a)})}function z1(e,t){if(!Number.isFinite(t)||t<=0)return 0;let n=P1();if(e.recentCalls=e.recentCalls.filter(e=>n-e<j1),e.recentCalls.length<t)return 0;let r=e.recentCalls[0]||n;return Math.max(0,j1-(n-r))}function B1(e){let t=P1(),n=0;return e.nextAllowedAt>t&&(n=Math.max(n,e.nextAllowedAt-t)),e.remoteRemaining!==null&&e.remoteRemaining<=0&&e.remoteResetAt!==null&&e.remoteResetAt>t&&(n=Math.max(n,e.remoteResetAt-t)),n}async function V1(e,t,n,r){let i=N1(e);for(;;){let e=z1(i,n.callsPerMinute),a=n.autoAdapt?B1(i):0,o=Math.max(e,a);if(o<=0){let e=P1();if(n.callsPerMinute>0&&i.recentCalls.push(e),n.autoAdapt&&i.remoteRemaining!==null&&i.remoteRemaining>0&&i.remoteResetAt!==null&&i.remoteResetAt>e){let t=i.remoteResetAt-e,n=Math.max(1,i.remoteRemaining),r=Math.ceil(t/n);i.nextAllowedAt=Math.max(i.nextAllowedAt,e+r)}return}o>=1e3&&Wr({type:`thinking-log`,payload:{groupId:t,level:`info`,label:`Rate limiter`,message:`Waiting ${Math.ceil(o/1e3)}s before next provider call to avoid 429s.`,timestamp:Date.now()}}),await R1(o,r)}}function H1(e,t,n){if(!n.autoAdapt||!t||typeof t.get!=`function`)return;let r=N1(e),i=P1(),a=F1(t.get(`x-ratelimit-limit`)),o=F1(t.get(`x-ratelimit-remaining`)),s=L1(t.get(`x-ratelimit-reset`));a!==null&&(r.remoteLimit=Math.max(0,Math.floor(a))),o!==null&&(r.remoteRemaining=Math.max(0,Math.floor(o))),s!==null&&(r.remoteResetAt=s);let c=I1(t.get(`retry-after`));c!==null&&(r.nextAllowedAt=Math.max(r.nextAllowedAt,i+c)),r.remoteRemaining!==null&&r.remoteRemaining<=0&&r.remoteResetAt!==null&&r.remoteResetAt>i&&(r.nextAllowedAt=Math.max(r.nextAllowedAt,r.remoteResetAt))}async function U1(e,t,n){let{groupId:r,messages:i,systemPrompt:a,apiKey:o,model:s,maxTokens:c=4096,provider:l,storageHandle:u,providerHeaders:d={},contextCompression:f=!1,rateLimitCallsPerMinute:p=0,rateLimitAutoAdapt:m=!0}=t,h={callsPerMinute:Number.isFinite(p)?Math.max(0,Math.floor(p)):0,autoAdapt:m!==!1};u&&xe(u);let g=O(l);if(!g){Wr({type:`error`,payload:{groupId:r,error:`Unknown provider: ${l}`}});return}let _=g;Wr({type:`typing`,payload:{groupId:r}}),A1(r,`info`,`Compacting context`,`Summarizing ${i.length} messages`);try{let e=tX(_,k1(i),[],{model:s,maxTokens:Math.min(c,4096),system:aX(a),contextCompression:f}),t={...WY(_,o),...d};await V1(l,r,h,n);let u=await fetch(_.baseUrl,{method:`POST`,headers:t,body:JSON.stringify(e),signal:n});if(H1(l,u.headers,h),!u.ok){let e=await u.text();throw Error(`${_.name} API error ${u.status}: ${e}`)}let p=rX(_,await u.json()).content.filter(e=>e.type===`text`).map(e=>e.text).join(``);A1(r,`info`,`Compaction complete`,`Summary: ${p.length} chars`),Wr({type:`compact-done`,payload:{groupId:r,summary:p}})}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;Wr({type:`error`,payload:{groupId:r,error:`Compaction failed: ${e instanceof Error?e.message:String(e)}`}})}}function W1(e,t,n){let r=t.input_tokens||0,i=t.output_tokens||0,a=t.cache_read_input_tokens||0,o=t.cache_creation_input_tokens||0;return{type:`token-usage`,payload:{groupId:e,inputTokens:r,outputTokens:i,cacheReadTokens:a,cacheCreationTokens:o,totalTokens:r+i+a+o,contextLimit:n}}}async function*G1(e,t){let n=e.getReader(),r=new TextDecoder,i=``;try{for(;!t?.aborted;){let{done:e,value:t}=await n.read();if(e)break;i+=r.decode(t,{stream:!0});let a=i.split(`
2227
2227
 
2228
2228
  `);i=a.pop()||``;for(let e of a){let t=e.split(`
2229
2229
  `);for(let e of t)if(!(!e||e.startsWith(`:`))&&e.startsWith(`data: `)){let t=e.slice(6).trim();if(t===`[DONE]`)continue;try{yield JSON.parse(t)}catch{}}}}}finally{n.releaseLock()}}const K1={"litert-community/gemma-4-E2B-it-litert-lm":`https://huggingface.co/litert-community/gemma-4-E2B-it-litert-lm/resolve/main/gemma-4-E2B-it-web.litertlm`,"litert-community/gemma-4-E4B-it-litert-lm":`https://huggingface.co/litert-community/gemma-4-E4B-it-litert-lm/resolve/main/gemma-4-E4B-it-web.litertlm`},q1=Object.keys(K1);function J1(){return typeof navigator<`u`&&`gpu`in navigator&&typeof WebAssembly<`u`&&`Suspending`in WebAssembly}let Y1=null,X1=null,Z1=null,Q1=null;async function $1(e,t,n){return oJ(e,t,n,{cacheName:`shadow-claw-litertlm-models`,chunkSize:16777216})}async function e0(e,t,n){if(X1===e&&Y1)return Y1;if(Z1&&Q1===e)return Z1;Q1=e,Z1=(async()=>{if(Y1){try{await Y1.delete?.()}catch{}Y1=null,X1=null}let r=K1[e];if(!r)throw Error(`LiteRT-LM: Model '${e} is not supported. Supported models: ${q1.join(`, `)}`);let i=await import(`./dist-DUy1CvmT.js`).catch(()=>{throw Error(`LiteRT-LM: The @litert-lm/core package is not installed. Run: npm install @litert-lm/core`)}),a=i.Engine??i.default?.Engine;if(typeof a?.create!=`function`)throw Error(`LiteRT-LM: Could not locate Engine.create in @litert-lm/core. Ensure you have the latest version installed.`);let o=await $1(r,t??(()=>{}),n),s=await a.create({model:o,mainExecutorSettings:{maxNumTokens:8192}});return Y1=s,X1=e,s})();try{return await Z1}finally{Z1=null,Q1=null}}function t0(e){if(!e)return null;let t=e.match(/<\|tool_call>call:([A-Za-z0-9_]+)(\{[\s\S]*?)(?:<tool_call\|>|$)/);if(!t)return null;let n=t[1],r=t[2];r=r.replace(/<\|"\|>/g,`"`);function i(e){return e.replace(/([{,]\s*)([A-Za-z_$][A-Za-z0-9_$]*)(\s*:)/g,`$1"$2"$3`)}let a={},o=[r,i(r)];for(let e of o)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t)){a=t;break}}catch{}if(Object.keys(a).length===0){let e=r.indexOf(`{`),t=r.lastIndexOf(`}`);if(e>=0&&t>e){let n=r.slice(e,t+1);for(let e of[n,i(n)])try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t)){a=t;break}}catch{}}}return{name:n,input:a}}function n0(e){let t=Kq(String(e||``),`litert_lm`).trim();if(!t)return null;let n=e=>{try{let t=JSON.parse(e);if(t&&typeof t==`object`&&(t.type===`tool_use`||t.type===`response`))return t.tools_calls&&!t.tool_calls&&(t.tool_calls=t.tools_calls),{...t,format:`json`}}catch{}return null},r=n(t);if(r)return r;let i=t.indexOf(`{`),a=t.lastIndexOf(`}`);if(i>=0&&a>i&&(r=n(t.slice(i,a+1)),r))return r;if(t.includes(`"tool_use"`)){let e=/"name"\s*:\s*"([^"]+)"/.exec(t);if(e){let n={},r=/"input"\s*:\s*(\{.*?\})\s*(?:]|\}|"|$)/s.exec(t);if(r)try{n=JSON.parse(r[1])}catch{}return{type:`tool_use`,format:`json`,tool_calls:[{id:`litert_${Date.now()}`,name:e[1],input:n}]}}}let o=t0(t);return o?{type:`tool_use`,format:`model_specific`,tool_calls:[{id:`litert_${Date.now()}`,name:o.name,input:o.input}]}:null}function r0(e,t,n){let r=[],i=e||``;if(n.length>0){let e=[``,`TOOL CALLING INSTRUCTIONS:`,`Return ONLY valid JSON (no markdown fences).`,`To call a tool: {"type":"tool_use","tool_calls":[{"name":"<tool>","input":{...}}]}`,`To reply: {"type":"response","response":"<your answer>"}`,`IMPORTANT: When you need to use a tool, output ONLY the JSON above — do NOT describe the call as text.`,``,`Available tools:`,n.map(e=>{let t=Object.keys(e.input_schema.properties||{}).join(`, `),n=e.description.split(`. `)[0];return`${e.name}(${t}): ${n}`}).join(`
@@ -1 +1 @@
1
- import{r as e}from"./config-Bnwx4EfS.js";import{Ct as t,ht as n}from"./orchestrator-DAJkyJmV.js";import{t as r}from"./setConfig-DFMYnYLE.js";async function i(i,a,o,s,c=``,l=0,u=``,d=!0){let f=o.trim(),p=t(s),m=c.trim(),h=Number.isFinite(l)?Math.max(0,Math.floor(l)):0,g=u.trim(),_=!!d;i.peerjsMyPeerId=f,i.peerjsTrustedPeerIds=p,i.peerjsServerHost=m,i.peerjsServerPort=h,i.peerjsServerPath=g,i.peerjsServerSecure=_,await r(a,e.PEERJS_MY_PEER_ID,f),await r(a,e.PEERJS_TRUSTED_PEER_IDS,JSON.stringify(p)),await r(a,e.PEERJS_SERVER_HOST,m),await r(a,e.PEERJS_SERVER_PORT,h?String(h):``),await r(a,e.PEERJS_SERVER_PATH,g),await r(a,e.PEERJS_SERVER_SECURE,_?`true`:`false`);let v=m?{host:m,path:g||void 0,port:h||void 0,secure:_}:{};i.peerjs.stop(),i.peerjs.configure(f,p,v),f&&n(i,`peerjs`)&&i.peerjs.start()}export{i as t};
1
+ import{r as e}from"./config-Bnwx4EfS.js";import{Ct as t,ht as n}from"./orchestrator-BeJfwtvz.js";import{t as r}from"./setConfig-DFMYnYLE.js";async function i(i,a,o,s,c=``,l=0,u=``,d=!0){let f=o.trim(),p=t(s),m=c.trim(),h=Number.isFinite(l)?Math.max(0,Math.floor(l)):0,g=u.trim(),_=!!d;i.peerjsMyPeerId=f,i.peerjsTrustedPeerIds=p,i.peerjsServerHost=m,i.peerjsServerPort=h,i.peerjsServerPath=g,i.peerjsServerSecure=_,await r(a,e.PEERJS_MY_PEER_ID,f),await r(a,e.PEERJS_TRUSTED_PEER_IDS,JSON.stringify(p)),await r(a,e.PEERJS_SERVER_HOST,m),await r(a,e.PEERJS_SERVER_PORT,h?String(h):``),await r(a,e.PEERJS_SERVER_PATH,g),await r(a,e.PEERJS_SERVER_SECURE,_?`true`:`false`);let v=m?{host:m,path:g||void 0,port:h||void 0,secure:_}:{};i.peerjs.stop(),i.peerjs.configure(f,p,v),f&&n(i,`peerjs`)&&i.peerjs.start()}export{i as t};
@@ -1,4 +1,4 @@
1
- <!doctype html><html lang="en"><head><title>ShadowClaw</title><meta charset="utf-8"><meta name="revision" content="53a4905ade9f05a2f96a146f462cb18899583a68" /><meta name="version" content="1.31.0" /><meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover"><meta name="description" content="ShadowClaw - Browser-native AI agent." /><link rel="canonical" href="https://xt-ml.github.io/shadow-claw/"><meta property="og:title" content="ShadowClaw"><meta property="og:description" content="Browser-native personal AI assistant with local and remote LLM orchestration, Web Workers, OPFS storage, and agentic tool execution."><meta property="og:type" content="website"><meta property="og:url" content="https://xt-ml.github.io/shadow-claw/"><meta property="og:image" content="https://xt-ml.github.io/shadow-claw/assets/icons/512.png"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="ShadowClaw"><meta name="twitter:description" content="Browser-native personal AI assistant with local and remote LLM orchestration, Web Workers, OPFS storage, and agentic tool execution."><meta name="twitter:image" content="https://xt-ml.github.io/shadow-claw/assets/icons/512.png"><script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"SoftwareApplication","@id":"https://xt-ml.github.io/shadow-claw/#software","name":"ShadowClaw","description":"Browser-native personal AI assistant with local and remote LLM orchestration, Web Workers, OPFS storage, and agentic tool execution.","url":"https://xt-ml.github.io/shadow-claw/","applicationCategory":"DeveloperApplication","operatingSystem":"Web, Browser, Desktop","offers":{"@type":"Offer","price":"0","priceCurrency":"USD"},"author":{"@type":"Organization","name":"xt-ml","url":"https://github.com/xt-ml"},"codeRepository":"https://github.com/xt-ml/shadow-claw","license":"https://github.com/xt-ml/shadow-claw/blob/main/LICENSE"},{"@type":"WebSite","@id":"https://xt-ml.github.io/shadow-claw/#website","url":"https://xt-ml.github.io/shadow-claw/","name":"ShadowClaw","description":"Official website and live deployment of ShadowClaw browser-native AI assistant.","publisher":{"@type":"Organization","name":"xt-ml","url":"https://github.com/xt-ml"}},{"@type":"Organization","@id":"https://xt-ml.github.io/shadow-claw/#organization","name":"xt-ml","url":"https://github.com/xt-ml","sameAs":["https://github.com/xt-ml"]}]}</script><meta name="theme-color" content="#fff" /><meta http-equiv="origin-trial" content="A88uTgESYWcVgREKVReKB6jom41uP8TzW6ei3jNdidf+Xl6ONqKRjKNBphsxhrZmdkakLK3oXDgkGq53rtZYSAMAAAB2eyJvcmlnaW4iOiJodHRwczovL3h0LW1sLmdpdGh1Yi5pbzo0NDMiLCJmZWF0dXJlIjoiV2ViTUNQIiwiZXhwaXJ5IjoxNzk0ODczNjAwLCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlfQ=="><base href="/shadow-claw/"><script id="shadow-claw-site-config" type="application/json">{"$schema":"https:\u002f\u002fjson-schema.org\u002fdraft\u002f2020-12\u002fschema","site":{"title":"ShadowClaw","description":"ShadowClaw - Browser-native AI agent.","themeColor":"#fff"},"branding":{"faviconPath":"assets\u002ficons\u002ffavicon.ico","appleTouchIconPath":"assets\u002ficons\u002f180.png","notFoundPath":"404.html"},"pwa":{"manifestPath":"manifest.json","themeColor":"#000000"},"sitemapPath":"sitemap.xml","assets":["assets"],"sidebar":{"pagesHidden":false,"chatHidden":false,"tasksHidden":false,"filesHidden":false,"defaultPage":"pages"},"settings":{"defaultToolsProfile":"__builtin_default"},"customElements":{"allowedElements":["block-garden","block-garden-option","block-garden-select"],"allowedDomains":["kherrick.github.io","cdn.jsdelivr.net"],"scripts":[{"src":"https:\u002f\u002fkherrick.github.io\u002fblock-garden-knowledge-hub\u002f.agents\u002fscripts\u002fmain\u002fblock-garden-adapter.js","hasInit":true},"https:\u002f\u002fkherrick.github.io\u002fblock-garden\u002fblock-garden-bundle-min.mjs"]},"security":{"connectSrc":["'self'","blob:","data:","https:\u002f\u002fkherrick.github.io","https:\u002f\u002fcdn.jsdelivr.net"]}}</script>
1
+ <!doctype html><html lang="en"><head><title>ShadowClaw</title><meta charset="utf-8"><meta name="revision" content="979d27349392e33a2f52555e93b057de32865e31" /><meta name="version" content="1.32.0" /><meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover"><meta name="description" content="ShadowClaw - Browser-native AI agent." /><link rel="canonical" href="https://xt-ml.github.io/shadow-claw/"><meta property="og:title" content="ShadowClaw"><meta property="og:description" content="Browser-native personal AI assistant with local and remote LLM orchestration, Web Workers, OPFS storage, and agentic tool execution."><meta property="og:type" content="website"><meta property="og:url" content="https://xt-ml.github.io/shadow-claw/"><meta property="og:image" content="https://xt-ml.github.io/shadow-claw/assets/icons/512.png"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="ShadowClaw"><meta name="twitter:description" content="Browser-native personal AI assistant with local and remote LLM orchestration, Web Workers, OPFS storage, and agentic tool execution."><meta name="twitter:image" content="https://xt-ml.github.io/shadow-claw/assets/icons/512.png"><script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"SoftwareApplication","@id":"https://xt-ml.github.io/shadow-claw/#software","name":"ShadowClaw","description":"Browser-native personal AI assistant with local and remote LLM orchestration, Web Workers, OPFS storage, and agentic tool execution.","url":"https://xt-ml.github.io/shadow-claw/","applicationCategory":"DeveloperApplication","operatingSystem":"Web, Browser, Desktop","offers":{"@type":"Offer","price":"0","priceCurrency":"USD"},"author":{"@type":"Organization","name":"xt-ml","url":"https://github.com/xt-ml"},"codeRepository":"https://github.com/xt-ml/shadow-claw","license":"https://github.com/xt-ml/shadow-claw/blob/main/LICENSE"},{"@type":"WebSite","@id":"https://xt-ml.github.io/shadow-claw/#website","url":"https://xt-ml.github.io/shadow-claw/","name":"ShadowClaw","description":"Official website and live deployment of ShadowClaw browser-native AI assistant.","publisher":{"@type":"Organization","name":"xt-ml","url":"https://github.com/xt-ml"}},{"@type":"Organization","@id":"https://xt-ml.github.io/shadow-claw/#organization","name":"xt-ml","url":"https://github.com/xt-ml","sameAs":["https://github.com/xt-ml"]}]}</script><meta name="theme-color" content="#fff" /><meta http-equiv="origin-trial" content="A88uTgESYWcVgREKVReKB6jom41uP8TzW6ei3jNdidf+Xl6ONqKRjKNBphsxhrZmdkakLK3oXDgkGq53rtZYSAMAAAB2eyJvcmlnaW4iOiJodHRwczovL3h0LW1sLmdpdGh1Yi5pbzo0NDMiLCJmZWF0dXJlIjoiV2ViTUNQIiwiZXhwaXJ5IjoxNzk0ODczNjAwLCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlfQ=="><base href="/shadow-claw/"><script id="shadow-claw-site-config" type="application/json">{"$schema":"https:\u002f\u002fjson-schema.org\u002fdraft\u002f2020-12\u002fschema","site":{"title":"ShadowClaw","description":"ShadowClaw - Browser-native AI agent.","themeColor":"#fff"},"branding":{"faviconPath":"assets\u002ficons\u002ffavicon.ico","appleTouchIconPath":"assets\u002ficons\u002f180.png","notFoundPath":"404.html"},"pwa":{"manifestPath":"manifest.json","themeColor":"#000000"},"sitemapPath":"sitemap.xml","assets":["assets"],"sidebar":{"pagesHidden":false,"chatHidden":false,"tasksHidden":false,"filesHidden":false,"defaultPage":"pages"},"settings":{"defaultToolsProfile":"__builtin_default"},"customElements":{"allowedElements":["block-garden","block-garden-option","block-garden-select"],"allowedDomains":["kherrick.github.io","cdn.jsdelivr.net"],"scripts":[{"src":"https:\u002f\u002fkherrick.github.io\u002fblock-garden-knowledge-hub\u002f.agents\u002fscripts\u002fmain\u002fblock-garden-adapter.js","hasInit":true},"https:\u002f\u002fkherrick.github.io\u002fblock-garden\u002fblock-garden-bundle-min.mjs"]},"security":{"connectSrc":["'self'","blob:","data:","https:\u002f\u002fkherrick.github.io","https:\u002f\u002fcdn.jsdelivr.net"]}}</script>
2
2
  <script>var ShadowClawThemeInit=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);function n(){if(globalThis.trustedTypes)return;let e=new Map;globalThis.trustedTypes={createPolicy:(t,n)=>{if(e.has(t))throw TypeError(`Policy with name "${t}" already exists.`);let r={createHTML:n.createHTML?e=>n.createHTML(e):void 0,createScriptURL:n.createScriptURL?e=>n.createScriptURL(e):void 0,createScript:n.createScript?e=>n.createScript(e):void 0};return e.set(t,r),r},getPolicy:t=>e.get(t)??null,isHTML:e=>typeof e==`string`||e instanceof Object&&`toString`in e,isScriptURL:e=>typeof e==`string`||e instanceof Object&&`toString`in e,isScript:e=>typeof e==`string`||e instanceof Object&&`toString`in e}}let r=`__shadowClawDefaultTrustedTypesPolicyState`,i=`default`,a=`shadowclaw-sandbox`;function o(){let e=globalThis;return e[r]||(e[r]={initialized:!1,policy:null}),e[r]}function s(){let e=o();if(e.initialized)return;let t=Reflect.get(globalThis,`trustedTypes`);if(!(!t||typeof t.createPolicy!=`function`)){e.initialized=!0;try{if(typeof t.getPolicy==`function`){let n=t.getPolicy(i);if(n){e.policy=n;return}}let n=!1;if(typeof t.getPolicyNames==`function`){let e=t.getPolicyNames();Array.isArray(e)&&e.includes(i)&&(n=!0)}if(n){if(typeof t.getPolicy==`function`){let n=t.getPolicy(a);if(n){e.policy=n;return}}e.policy=t.createPolicy(a,{createHTML:e=>e,createScriptURL:e=>e});return}e.policy=t.createPolicy(i,{createHTML:e=>e,createScriptURL:e=>e})}catch{typeof t.getPolicy==`function`&&(e.policy=t.getPolicy(i)??t.getPolicy(a)??null)}}}new class{loading=!1;models=new Map;getModelInfo(e){return this.models.get(e.toLowerCase())??null}registerModelInfo(e,t){this.models.set(e.toLowerCase(),t)}clear(){this.models.clear()}async fetchModelInfo(e,t,n){if(e.modelsUrl){this.loading=!0;try{let r=new Headers;if(r.set(`Content-Type`,`application/json`),e.headers)for(let[t,n]of Object.entries(e.headers))r.set(t,n);if(n)for(let[e,t]of Object.entries(n))r.set(e,t);if(t&&e.apiKeyHeader){let n=e.apiKeyHeaderFormat;r.set(e.apiKeyHeader,n?n.replace(`{key}`,t):t)}let i=await fetch(e.modelsUrl,{headers:r});if(!i.ok)throw Error(`HTTP ${i.status} ${i.statusText}`);let a=await i.json(),o=Array.isArray(a.data)?a.data:Array.isArray(a.models)?a.models:[];for(let e of o){if(!e.id)continue;let t=e.context_length??e.context_window??0,n=e.max_completion_tokens||e.per_request_limits?.completion_tokens||e.top_provider?.max_completion_tokens||null,r=typeof e.supports_tools==`boolean`?e.supports_tools:typeof e.supportsTools==`boolean`?e.supportsTools:void 0,i=this.extractModalities(e,`input`),a=this.extractModalities(e,`output`),o=this.modalitiesInclude(i,`image`,`vision`),s=this.modalitiesInclude(i,`audio`,`voice`,`hearing`),c=this.modalitiesInclude(i,`video`),l=e.id===`openrouter/free`||this.supportedParametersInclude(e,`image`,`vision`,`audio`,`tool`,`structured`),u=this.extractReasoning(e);!t&&Array.isArray(e.providers)&&e.providers.length>0&&(t=e.providers[0]?.context_length||0),this.registerModelInfo(e.id,{contextWindow:t,maxOutput:n,...r!==void 0&&{supportsTools:r},...i.length>0&&{inputModalities:i},...a.length>0&&{outputModalities:a},...o!==void 0&&{supportsImageInput:o},...s!==void 0&&{supportsAudioInput:s},...c!==void 0&&{supportsVideoInput:c},...u&&{reasoning:u},...l&&{routesByRequestFeatures:l}})}o.length>0&&console.log(`[ModelRegistry] Registered ${o.length} models for provider "${e.id}"`)}catch(t){console.error(`[ModelRegistry] Error fetching models for ${e.id}:`,t)}finally{this.loading=!1}}}extractModalities(e,t){let n=t===`input`?e.input_modalities||e.inputModalities:e.output_modalities||e.outputModalities,r=e.architecture||{},i=t===`input`?r.input_modalities||r.inputModalities:r.output_modalities||r.outputModalities,a=typeof r.modality==`string`?r.modality:``,o=this.parseArchitectureModality(a,t),s=[...this.normalizeStringArray(n),...this.normalizeStringArray(i),...o];return Array.from(new Set(s))}extractReasoning(e){let t=e?.reasoning;if(!t||typeof t!=`object`)return;let n=this.normalizeStringArray(t.supported_efforts),r=typeof t.default_effort==`string`?t.default_effort.toLowerCase():void 0,i=typeof t.default_enabled==`boolean`?t.default_enabled:void 0,a=typeof t.supports_max_tokens==`boolean`?t.supports_max_tokens:void 0,o=typeof t.mandatory==`boolean`?t.mandatory:void 0;if(!(n.length===0&&r===void 0&&i===void 0&&a===void 0&&o===void 0))return{...n.length>0&&{supportedEfforts:n},...r!==void 0&&{defaultEffort:r},...i!==void 0&&{defaultEnabled:i},...a!==void 0&&{supportsMaxTokens:a},...o!==void 0&&{mandatory:o}}}modalitiesInclude(e,...t){if(e.length!==0)return t.some(t=>e.some(e=>e.includes(t)))}normalizeStringArray(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.toLowerCase()):[]}parseArchitectureModality(e,t){if(!e)return[];let[n=``,r=``]=e.toLowerCase().split(`->`).map(e=>e.trim());return(t===`input`?n:r).split(/[+,/\s]+/).map(e=>e.trim()).filter(Boolean)}supportedParametersInclude(e,...t){let n=this.normalizeStringArray(e.supported_parameters||e.supportedParameters);return t.some(e=>n.some(t=>t.includes(e)))}};function c(e){return e.replace(/^\/+|\/+$/g,``)}function l(e){let t=c(e);return t.endsWith(`/index.html`)?t=t.slice(0,-11):t.endsWith(`index.html`)&&(t=t.slice(0,-10)),c(t)}function u(e){let t=c(e),n=t.split(`/`).filter(Boolean);if(n.length===0)return null;let r=n[0].toLowerCase();if(r===`pages`){if(n.length>=3){let e=n[1];return{page:`pages`,groupId:e===`main`?`br:main`:e.startsWith(`br-`)?`br:${e.slice(3)}`:e,path:n.slice(2).join(`/`)}}return{page:`pages`,groupId:`br:main`,path:n.slice(1).join(`/`)}}if(r===`files`){let e=n[1]||`main`;return{page:`files`,groupId:e===`main`?`br:main`:e.startsWith(`br-`)?`br:${e.slice(3)}`:e,path:n.slice(2).join(`/`)||void 0}}if(r===`chat`){let e=n[1]||`main`;return{page:`chat`,groupId:e===`main`?`br:main`:e.startsWith(`br-`)?`br:${e.slice(3)}`:e}}if(r===`tasks`){let e=n[1]||`main`;return{page:`tasks`,groupId:e===`main`?`br:main`:e.startsWith(`br-`)?`br:${e.slice(3)}`:e}}return r===`main`?{page:`pages`,groupId:`br:main`,path:n.slice(1).join(`/`)}:{page:`pages`,groupId:`br:main`,path:t}}function d(){if(typeof document<`u`){let e=document.getElementById(`shadow-claw-static-routing`);if(e&&e.textContent)try{let t=JSON.parse(e.textContent);if(t&&typeof t==`object`&&t.routes)return t}catch(e){console.warn(`Failed to parse embedded static routing manifest:`,e)}}return null}function f(e,t){let n=t||d();if(!n||!n.routes)return null;let r=l(e);if(!r)return null;for(let[e,t]of Object.entries(n.routes))if(!(!t||!t.prettyPath)&&l(t.prettyPath)===r)return u(e);return null}let p=null,ee=new Set([`chat`,`files`,`tasks`,`pages`,`settings`,`tools`,`channels`]);function m(){p=null}typeof globalThis<`u`&&(globalThis.__applyBasePathCacheReset=m);function h(){let e=typeof window<`u`?window:typeof self<`u`?self:globalThis;if(e&&e.__SHADOWCLAW_DEPLOY_ID__){let t=String(e.__SHADOWCLAW_DEPLOY_ID__).trim();if(t)return t.replace(/[^a-zA-Z0-9_-]/g,`-`)}let t=globalThis.process;if(t&&t.env&&t.env.SHADOWCLAW_DEPLOY_ID){let e=String(t.env.SHADOWCLAW_DEPLOY_ID).trim();if(e)return e.replace(/[^a-zA-Z0-9_-]/g,`-`)}let n=te();return!n||n===`/`?``:n.replace(/^\/+|\/+$/g,``).replace(/[^a-zA-Z0-9_-]/g,`-`)}function te(){if(p!==null)return p;if((typeof window>`u`||globalThis.WorkerGlobalScope!==void 0&&typeof self<`u`&&self instanceof globalThis.WorkerGlobalScope)&&typeof self<`u`&&self.location){let e=(self.location.pathname||`/`).split(`/`).filter(Boolean);if(e.length<=1)return p=`/`,p;let t=e[0].toLowerCase(),n=t===`service-worker.js`||t===`sw.js`||t===`manifest.json`||t===`sitemap.xml`||t===`favicon.ico`||t===`index.html`||t===`service-worker`||t===`assets`||t===`dist`||t===`public`;if(n&&e.length===2)return p=`/`,p;if(!n)return p=`/`+e[0]+`/`,p}let e=typeof window<`u`&&window.location?window.location:typeof self<`u`&&self.location?self.location:null;if(!e)return`/`;if(typeof document<`u`&&typeof document.querySelector==`function`){let t=document.querySelector(`base[href]`);if(t){let n=t.getAttribute(`href`);if(n)try{let t=new URL(n,e.origin).pathname;return t.endsWith(`/`)||(t+=`/`),p=t,p}catch{}}}let t=e.pathname||`/`;if(t===`/`)return p=`/`,p;let n=t.split(`/`).filter(Boolean),r=n.findIndex(e=>ee.has(e.toLowerCase()));return r>=0?r===0?(p=`/`,p):(p=`/`+n.slice(0,r).join(`/`)+`/`,p):f(t)?(p=`/`,p):n.length===1&&!t.includes(`.`)?(p=`/`+n[0]+`/`,p):(p=`/`,p)}function ne(e){let t=e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`(^|\\s)@${t}\\b`,`i`)}ne(`ShadowClaw`);function g(){let e=h();return e?`shadowclaw-${e}`:`shadowclaw`}g();let _={github:{providerId:`github`,name:`GitHub`,aliases:[`github`,`api.github.com`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`http_api`,`git_remote`],authTypes:[`token`,`oauth`],tokenAuth:{token:{headerName:`Authorization`,headerPrefix:`token `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},oauth:{authorizeUrl:`https://github.com/login/oauth/authorize`,tokenUrl:`https://github.com/login/oauth/access_token`,defaultScopes:[`repo`,`read:user`],usePkce:!0,clientAuthMethod:`request_body`,scopeSeparator:`space`}},gitlab:{providerId:`gitlab`,name:`GitLab`,aliases:[`gitlab`,`gitlab.com`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`http_api`,`git_remote`],authTypes:[`token`,`oauth`],tokenAuth:{token:{headerName:`PRIVATE-TOKEN`,headerPrefix:``},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},tokenAuthByServiceType:{git_remote:{token:{headerName:`Authorization`,headerPrefix:`Bearer `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}}},oauth:{authorizeUrl:`https://gitlab.com/oauth/authorize`,tokenUrl:`https://gitlab.com/oauth/token`,defaultScopes:[`read_api`,`read_user`],usePkce:!0,clientAuthMethod:`request_body`,scopeSeparator:`space`}},figma:{providerId:`figma`,name:`Figma`,aliases:[`figma`,`api.figma.com`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`http_api`],authTypes:[`token`,`oauth`],tokenAuth:{token:{headerName:`X-Figma-Token`,headerPrefix:``},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},oauth:{authorizeUrl:`https://www.figma.com/oauth`,tokenUrl:`https://api.figma.com/v1/oauth/token`,refreshUrl:`https://api.figma.com/v1/oauth/refresh`,defaultScopes:[],usePkce:!0,clientAuthMethod:`basic_header`,scopeSeparator:`space`}},notion:{providerId:`notion`,name:`Notion`,aliases:[`notion`,`api.notion.com`,`notion.so`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`http_api`],authTypes:[`token`,`oauth`],tokenAuth:{token:{headerName:`Authorization`,headerPrefix:`Bearer `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},oauth:{authorizeUrl:`https://api.notion.com/v1/oauth/authorize`,tokenUrl:`https://api.notion.com/v1/oauth/token`,defaultScopes:[],usePkce:!0,clientAuthMethod:`basic_header`,scopeSeparator:`space`}},microsoft_graph:{providerId:`microsoft_graph`,name:`Microsoft Graph`,aliases:[`microsoft`,`graph.microsoft.com`,`microsoft_graph`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`http_api`],authTypes:[`token`,`oauth`],tokenAuth:{token:{headerName:`Authorization`,headerPrefix:`Bearer `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},oauth:{authorizeUrl:`https://login.microsoftonline.com/common/oauth2/v2.0/authorize`,tokenUrl:`https://login.microsoftonline.com/common/oauth2/v2.0/token`,defaultScopes:[`openid`,`profile`,`offline_access`,`User.Read`],usePkce:!0,clientAuthMethod:`request_body`,scopeSeparator:`space`}},yahoo_mail:{providerId:`yahoo_mail`,name:`Yahoo Mail`,aliases:[`yahoo`,`yahoo_mail`,`mail.yahoo.com`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`http_api`],authTypes:[`token`,`oauth`],tokenAuth:{token:{headerName:`Authorization`,headerPrefix:`Bearer `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},oauth:{authorizeUrl:`https://api.login.yahoo.com/oauth2/request_auth`,tokenUrl:`https://api.login.yahoo.com/oauth2/get_token`,defaultScopes:[`mail-r`,`mail-w`],usePkce:!0,clientAuthMethod:`request_body`,scopeSeparator:`space`}},google:{providerId:`google`,name:`Google`,aliases:[`google`,`googleapis.com`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`http_api`],authTypes:[`token`,`oauth`],tokenAuth:{token:{headerName:`Authorization`,headerPrefix:`Bearer `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},oauth:{authorizeUrl:`https://accounts.google.com/o/oauth2/v2/auth`,tokenUrl:`https://oauth2.googleapis.com/token`,defaultScopes:[`openid`,`profile`,`email`],usePkce:!0,clientAuthMethod:`request_body`,scopeSeparator:`space`}},atlassian:{providerId:`atlassian`,name:`Atlassian`,aliases:[`atlassian`,`api.atlassian.com`],modes:[`oauth`,`token`,`basic`],defaultMode:`basic`,serviceTypes:[`http_api`,`git_remote`],authTypes:[`token`,`oauth`,`basic_userpass`],tokenAuth:{token:{headerName:`Authorization`,headerPrefix:`Bearer `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `},basic:{headerName:`Authorization`,headerPrefix:`Basic `}},oauth:{authorizeUrl:`https://auth.atlassian.com/authorize`,tokenUrl:`https://auth.atlassian.com/oauth/token`,defaultScopes:[],usePkce:!0,clientAuthMethod:`request_body`,scopeSeparator:`space`}},slack:{providerId:`slack`,name:`Slack`,aliases:[`slack`,`slack.com`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`http_api`],authTypes:[`token`,`oauth`],tokenAuth:{token:{headerName:`Authorization`,headerPrefix:`Bearer `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},oauth:{authorizeUrl:`https://slack.com/oauth/v2/authorize`,tokenUrl:`https://slack.com/api/oauth.v2.access`,defaultScopes:[],usePkce:!1,clientAuthMethod:`request_body`,scopeSeparator:`comma`}},linear:{providerId:`linear`,name:`Linear`,aliases:[`linear`,`api.linear.app`,`linear.app`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`http_api`],authTypes:[`token`,`oauth`],tokenAuth:{token:{headerName:`Authorization`,headerPrefix:`Bearer `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},oauth:{authorizeUrl:`https://linear.app/oauth/authorize`,tokenUrl:`https://api.linear.app/oauth/token`,defaultScopes:[],usePkce:!0,clientAuthMethod:`request_body`,scopeSeparator:`space`}},azure_devops:{providerId:`azure_devops`,name:`Azure DevOps`,aliases:[`azure_devops`,`dev.azure.com`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`http_api`,`git_remote`],authTypes:[`token`,`oauth`,`basic_userpass`,`ssh_key`],tokenAuth:{token:{headerName:`Authorization`,headerPrefix:`Bearer `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},tokenAuthByServiceType:{git_remote:{token:{headerName:`Authorization`,headerPrefix:`Basic `},oauth:{headerName:`Authorization`,headerPrefix:`Basic `}}},oauth:{authorizeUrl:`https://app.vssps.visualstudio.com/oauth2/authorize`,tokenUrl:`https://app.vssps.visualstudio.com/oauth2/token`,defaultScopes:[`vso.code`,`vso.profile`,`offline_access`],usePkce:!1,clientAuthMethod:`request_body`,scopeSeparator:`space`}},custom_mcp:{providerId:`custom_mcp`,name:`Custom MCP`,aliases:[`custom_mcp`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`mcp_remote`,`webmcp_local`],authTypes:[`none`,`token`,`oauth`,`custom_header`,`ssh_key`],tokenAuth:{token:{headerName:`Authorization`,headerPrefix:`Bearer `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},oauth:{authorizeUrl:`https://example.com/oauth/authorize`,tokenUrl:`https://example.com/oauth/token`,defaultScopes:[],usePkce:!0,clientAuthMethod:`request_body`,scopeSeparator:`space`}}};Object.fromEntries(Object.values(_).filter(e=>!!e.oauth).map(e=>{let t=e.oauth;return[e.providerId,{id:e.providerId,name:e.name,authorizeUrl:t.authorizeUrl,tokenUrl:t.tokenUrl,redirectUri:t.redirectUri,defaultScopes:t.defaultScopes,usePkce:t.usePkce,clientAuthMethod:t.clientAuthMethod,scopeSeparator:t.scopeSeparator}]})),Object.fromEntries(Object.values(_).map(e=>[e.providerId,{providerId:e.providerId,modes:e.modes,defaultMode:e.defaultMode}])),new Promise(e=>{});
3
3
  /*! @license DOMPurify 3.4.13 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.13/LICENSE */
4
4
  function v(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function y(e){if(Array.isArray(e))return e}function b(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function re(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
@@ -1,4 +1,4 @@
1
- <!doctype html><html lang="en"><head><title>ShadowClaw</title><meta charset="utf-8"><meta name="revision" content="53a4905ade9f05a2f96a146f462cb18899583a68" /><meta name="version" content="1.31.0" /><meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover"><meta name="description" content="ShadowClaw - Browser-native AI agent." /><link rel="canonical" href="https://xt-ml.github.io/shadow-claw/"><meta property="og:title" content="ShadowClaw"><meta property="og:description" content="Browser-native personal AI assistant with local and remote LLM orchestration, Web Workers, OPFS storage, and agentic tool execution."><meta property="og:type" content="website"><meta property="og:url" content="https://xt-ml.github.io/shadow-claw/"><meta property="og:image" content="https://xt-ml.github.io/shadow-claw/assets/icons/512.png"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="ShadowClaw"><meta name="twitter:description" content="Browser-native personal AI assistant with local and remote LLM orchestration, Web Workers, OPFS storage, and agentic tool execution."><meta name="twitter:image" content="https://xt-ml.github.io/shadow-claw/assets/icons/512.png"><script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"SoftwareApplication","@id":"https://xt-ml.github.io/shadow-claw/#software","name":"ShadowClaw","description":"Browser-native personal AI assistant with local and remote LLM orchestration, Web Workers, OPFS storage, and agentic tool execution.","url":"https://xt-ml.github.io/shadow-claw/","applicationCategory":"DeveloperApplication","operatingSystem":"Web, Browser, Desktop","offers":{"@type":"Offer","price":"0","priceCurrency":"USD"},"author":{"@type":"Organization","name":"xt-ml","url":"https://github.com/xt-ml"},"codeRepository":"https://github.com/xt-ml/shadow-claw","license":"https://github.com/xt-ml/shadow-claw/blob/main/LICENSE"},{"@type":"WebSite","@id":"https://xt-ml.github.io/shadow-claw/#website","url":"https://xt-ml.github.io/shadow-claw/","name":"ShadowClaw","description":"Official website and live deployment of ShadowClaw browser-native AI assistant.","publisher":{"@type":"Organization","name":"xt-ml","url":"https://github.com/xt-ml"}},{"@type":"Organization","@id":"https://xt-ml.github.io/shadow-claw/#organization","name":"xt-ml","url":"https://github.com/xt-ml","sameAs":["https://github.com/xt-ml"]}]}</script><meta name="theme-color" content="#fff" /><meta http-equiv="origin-trial" content="A88uTgESYWcVgREKVReKB6jom41uP8TzW6ei3jNdidf+Xl6ONqKRjKNBphsxhrZmdkakLK3oXDgkGq53rtZYSAMAAAB2eyJvcmlnaW4iOiJodHRwczovL3h0LW1sLmdpdGh1Yi5pbzo0NDMiLCJmZWF0dXJlIjoiV2ViTUNQIiwiZXhwaXJ5IjoxNzk0ODczNjAwLCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlfQ=="><base href="/shadow-claw/"><script id="shadow-claw-site-config" type="application/json">{"$schema":"https:\u002f\u002fjson-schema.org\u002fdraft\u002f2020-12\u002fschema","site":{"title":"ShadowClaw","description":"ShadowClaw - Browser-native AI agent.","themeColor":"#fff"},"branding":{"faviconPath":"assets\u002ficons\u002ffavicon.ico","appleTouchIconPath":"assets\u002ficons\u002f180.png","notFoundPath":"404.html"},"pwa":{"manifestPath":"manifest.json","themeColor":"#000000"},"sitemapPath":"sitemap.xml","assets":["assets"],"sidebar":{"pagesHidden":false,"chatHidden":false,"tasksHidden":false,"filesHidden":false,"defaultPage":"pages"},"settings":{"defaultToolsProfile":"__builtin_default"},"customElements":{"allowedElements":["block-garden","block-garden-option","block-garden-select"],"allowedDomains":["kherrick.github.io","cdn.jsdelivr.net"],"scripts":[{"src":"https:\u002f\u002fkherrick.github.io\u002fblock-garden-knowledge-hub\u002f.agents\u002fscripts\u002fmain\u002fblock-garden-adapter.js","hasInit":true},"https:\u002f\u002fkherrick.github.io\u002fblock-garden\u002fblock-garden-bundle-min.mjs"]},"security":{"connectSrc":["'self'","blob:","data:","https:\u002f\u002fkherrick.github.io","https:\u002f\u002fcdn.jsdelivr.net"]}}</script>
1
+ <!doctype html><html lang="en"><head><title>ShadowClaw</title><meta charset="utf-8"><meta name="revision" content="979d27349392e33a2f52555e93b057de32865e31" /><meta name="version" content="1.32.0" /><meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover"><meta name="description" content="ShadowClaw - Browser-native AI agent." /><link rel="canonical" href="https://xt-ml.github.io/shadow-claw/"><meta property="og:title" content="ShadowClaw"><meta property="og:description" content="Browser-native personal AI assistant with local and remote LLM orchestration, Web Workers, OPFS storage, and agentic tool execution."><meta property="og:type" content="website"><meta property="og:url" content="https://xt-ml.github.io/shadow-claw/"><meta property="og:image" content="https://xt-ml.github.io/shadow-claw/assets/icons/512.png"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="ShadowClaw"><meta name="twitter:description" content="Browser-native personal AI assistant with local and remote LLM orchestration, Web Workers, OPFS storage, and agentic tool execution."><meta name="twitter:image" content="https://xt-ml.github.io/shadow-claw/assets/icons/512.png"><script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"SoftwareApplication","@id":"https://xt-ml.github.io/shadow-claw/#software","name":"ShadowClaw","description":"Browser-native personal AI assistant with local and remote LLM orchestration, Web Workers, OPFS storage, and agentic tool execution.","url":"https://xt-ml.github.io/shadow-claw/","applicationCategory":"DeveloperApplication","operatingSystem":"Web, Browser, Desktop","offers":{"@type":"Offer","price":"0","priceCurrency":"USD"},"author":{"@type":"Organization","name":"xt-ml","url":"https://github.com/xt-ml"},"codeRepository":"https://github.com/xt-ml/shadow-claw","license":"https://github.com/xt-ml/shadow-claw/blob/main/LICENSE"},{"@type":"WebSite","@id":"https://xt-ml.github.io/shadow-claw/#website","url":"https://xt-ml.github.io/shadow-claw/","name":"ShadowClaw","description":"Official website and live deployment of ShadowClaw browser-native AI assistant.","publisher":{"@type":"Organization","name":"xt-ml","url":"https://github.com/xt-ml"}},{"@type":"Organization","@id":"https://xt-ml.github.io/shadow-claw/#organization","name":"xt-ml","url":"https://github.com/xt-ml","sameAs":["https://github.com/xt-ml"]}]}</script><meta name="theme-color" content="#fff" /><meta http-equiv="origin-trial" content="A88uTgESYWcVgREKVReKB6jom41uP8TzW6ei3jNdidf+Xl6ONqKRjKNBphsxhrZmdkakLK3oXDgkGq53rtZYSAMAAAB2eyJvcmlnaW4iOiJodHRwczovL3h0LW1sLmdpdGh1Yi5pbzo0NDMiLCJmZWF0dXJlIjoiV2ViTUNQIiwiZXhwaXJ5IjoxNzk0ODczNjAwLCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlfQ=="><base href="/shadow-claw/"><script id="shadow-claw-site-config" type="application/json">{"$schema":"https:\u002f\u002fjson-schema.org\u002fdraft\u002f2020-12\u002fschema","site":{"title":"ShadowClaw","description":"ShadowClaw - Browser-native AI agent.","themeColor":"#fff"},"branding":{"faviconPath":"assets\u002ficons\u002ffavicon.ico","appleTouchIconPath":"assets\u002ficons\u002f180.png","notFoundPath":"404.html"},"pwa":{"manifestPath":"manifest.json","themeColor":"#000000"},"sitemapPath":"sitemap.xml","assets":["assets"],"sidebar":{"pagesHidden":false,"chatHidden":false,"tasksHidden":false,"filesHidden":false,"defaultPage":"pages"},"settings":{"defaultToolsProfile":"__builtin_default"},"customElements":{"allowedElements":["block-garden","block-garden-option","block-garden-select"],"allowedDomains":["kherrick.github.io","cdn.jsdelivr.net"],"scripts":[{"src":"https:\u002f\u002fkherrick.github.io\u002fblock-garden-knowledge-hub\u002f.agents\u002fscripts\u002fmain\u002fblock-garden-adapter.js","hasInit":true},"https:\u002f\u002fkherrick.github.io\u002fblock-garden\u002fblock-garden-bundle-min.mjs"]},"security":{"connectSrc":["'self'","blob:","data:","https:\u002f\u002fkherrick.github.io","https:\u002f\u002fcdn.jsdelivr.net"]}}</script>
2
2
  <script>var ShadowClawThemeInit=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);function n(){if(globalThis.trustedTypes)return;let e=new Map;globalThis.trustedTypes={createPolicy:(t,n)=>{if(e.has(t))throw TypeError(`Policy with name "${t}" already exists.`);let r={createHTML:n.createHTML?e=>n.createHTML(e):void 0,createScriptURL:n.createScriptURL?e=>n.createScriptURL(e):void 0,createScript:n.createScript?e=>n.createScript(e):void 0};return e.set(t,r),r},getPolicy:t=>e.get(t)??null,isHTML:e=>typeof e==`string`||e instanceof Object&&`toString`in e,isScriptURL:e=>typeof e==`string`||e instanceof Object&&`toString`in e,isScript:e=>typeof e==`string`||e instanceof Object&&`toString`in e}}let r=`__shadowClawDefaultTrustedTypesPolicyState`,i=`default`,a=`shadowclaw-sandbox`;function o(){let e=globalThis;return e[r]||(e[r]={initialized:!1,policy:null}),e[r]}function s(){let e=o();if(e.initialized)return;let t=Reflect.get(globalThis,`trustedTypes`);if(!(!t||typeof t.createPolicy!=`function`)){e.initialized=!0;try{if(typeof t.getPolicy==`function`){let n=t.getPolicy(i);if(n){e.policy=n;return}}let n=!1;if(typeof t.getPolicyNames==`function`){let e=t.getPolicyNames();Array.isArray(e)&&e.includes(i)&&(n=!0)}if(n){if(typeof t.getPolicy==`function`){let n=t.getPolicy(a);if(n){e.policy=n;return}}e.policy=t.createPolicy(a,{createHTML:e=>e,createScriptURL:e=>e});return}e.policy=t.createPolicy(i,{createHTML:e=>e,createScriptURL:e=>e})}catch{typeof t.getPolicy==`function`&&(e.policy=t.getPolicy(i)??t.getPolicy(a)??null)}}}new class{loading=!1;models=new Map;getModelInfo(e){return this.models.get(e.toLowerCase())??null}registerModelInfo(e,t){this.models.set(e.toLowerCase(),t)}clear(){this.models.clear()}async fetchModelInfo(e,t,n){if(e.modelsUrl){this.loading=!0;try{let r=new Headers;if(r.set(`Content-Type`,`application/json`),e.headers)for(let[t,n]of Object.entries(e.headers))r.set(t,n);if(n)for(let[e,t]of Object.entries(n))r.set(e,t);if(t&&e.apiKeyHeader){let n=e.apiKeyHeaderFormat;r.set(e.apiKeyHeader,n?n.replace(`{key}`,t):t)}let i=await fetch(e.modelsUrl,{headers:r});if(!i.ok)throw Error(`HTTP ${i.status} ${i.statusText}`);let a=await i.json(),o=Array.isArray(a.data)?a.data:Array.isArray(a.models)?a.models:[];for(let e of o){if(!e.id)continue;let t=e.context_length??e.context_window??0,n=e.max_completion_tokens||e.per_request_limits?.completion_tokens||e.top_provider?.max_completion_tokens||null,r=typeof e.supports_tools==`boolean`?e.supports_tools:typeof e.supportsTools==`boolean`?e.supportsTools:void 0,i=this.extractModalities(e,`input`),a=this.extractModalities(e,`output`),o=this.modalitiesInclude(i,`image`,`vision`),s=this.modalitiesInclude(i,`audio`,`voice`,`hearing`),c=this.modalitiesInclude(i,`video`),l=e.id===`openrouter/free`||this.supportedParametersInclude(e,`image`,`vision`,`audio`,`tool`,`structured`),u=this.extractReasoning(e);!t&&Array.isArray(e.providers)&&e.providers.length>0&&(t=e.providers[0]?.context_length||0),this.registerModelInfo(e.id,{contextWindow:t,maxOutput:n,...r!==void 0&&{supportsTools:r},...i.length>0&&{inputModalities:i},...a.length>0&&{outputModalities:a},...o!==void 0&&{supportsImageInput:o},...s!==void 0&&{supportsAudioInput:s},...c!==void 0&&{supportsVideoInput:c},...u&&{reasoning:u},...l&&{routesByRequestFeatures:l}})}o.length>0&&console.log(`[ModelRegistry] Registered ${o.length} models for provider "${e.id}"`)}catch(t){console.error(`[ModelRegistry] Error fetching models for ${e.id}:`,t)}finally{this.loading=!1}}}extractModalities(e,t){let n=t===`input`?e.input_modalities||e.inputModalities:e.output_modalities||e.outputModalities,r=e.architecture||{},i=t===`input`?r.input_modalities||r.inputModalities:r.output_modalities||r.outputModalities,a=typeof r.modality==`string`?r.modality:``,o=this.parseArchitectureModality(a,t),s=[...this.normalizeStringArray(n),...this.normalizeStringArray(i),...o];return Array.from(new Set(s))}extractReasoning(e){let t=e?.reasoning;if(!t||typeof t!=`object`)return;let n=this.normalizeStringArray(t.supported_efforts),r=typeof t.default_effort==`string`?t.default_effort.toLowerCase():void 0,i=typeof t.default_enabled==`boolean`?t.default_enabled:void 0,a=typeof t.supports_max_tokens==`boolean`?t.supports_max_tokens:void 0,o=typeof t.mandatory==`boolean`?t.mandatory:void 0;if(!(n.length===0&&r===void 0&&i===void 0&&a===void 0&&o===void 0))return{...n.length>0&&{supportedEfforts:n},...r!==void 0&&{defaultEffort:r},...i!==void 0&&{defaultEnabled:i},...a!==void 0&&{supportsMaxTokens:a},...o!==void 0&&{mandatory:o}}}modalitiesInclude(e,...t){if(e.length!==0)return t.some(t=>e.some(e=>e.includes(t)))}normalizeStringArray(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.toLowerCase()):[]}parseArchitectureModality(e,t){if(!e)return[];let[n=``,r=``]=e.toLowerCase().split(`->`).map(e=>e.trim());return(t===`input`?n:r).split(/[+,/\s]+/).map(e=>e.trim()).filter(Boolean)}supportedParametersInclude(e,...t){let n=this.normalizeStringArray(e.supported_parameters||e.supportedParameters);return t.some(e=>n.some(t=>t.includes(e)))}};function c(e){return e.replace(/^\/+|\/+$/g,``)}function l(e){let t=c(e);return t.endsWith(`/index.html`)?t=t.slice(0,-11):t.endsWith(`index.html`)&&(t=t.slice(0,-10)),c(t)}function u(e){let t=c(e),n=t.split(`/`).filter(Boolean);if(n.length===0)return null;let r=n[0].toLowerCase();if(r===`pages`){if(n.length>=3){let e=n[1];return{page:`pages`,groupId:e===`main`?`br:main`:e.startsWith(`br-`)?`br:${e.slice(3)}`:e,path:n.slice(2).join(`/`)}}return{page:`pages`,groupId:`br:main`,path:n.slice(1).join(`/`)}}if(r===`files`){let e=n[1]||`main`;return{page:`files`,groupId:e===`main`?`br:main`:e.startsWith(`br-`)?`br:${e.slice(3)}`:e,path:n.slice(2).join(`/`)||void 0}}if(r===`chat`){let e=n[1]||`main`;return{page:`chat`,groupId:e===`main`?`br:main`:e.startsWith(`br-`)?`br:${e.slice(3)}`:e}}if(r===`tasks`){let e=n[1]||`main`;return{page:`tasks`,groupId:e===`main`?`br:main`:e.startsWith(`br-`)?`br:${e.slice(3)}`:e}}return r===`main`?{page:`pages`,groupId:`br:main`,path:n.slice(1).join(`/`)}:{page:`pages`,groupId:`br:main`,path:t}}function d(){if(typeof document<`u`){let e=document.getElementById(`shadow-claw-static-routing`);if(e&&e.textContent)try{let t=JSON.parse(e.textContent);if(t&&typeof t==`object`&&t.routes)return t}catch(e){console.warn(`Failed to parse embedded static routing manifest:`,e)}}return null}function f(e,t){let n=t||d();if(!n||!n.routes)return null;let r=l(e);if(!r)return null;for(let[e,t]of Object.entries(n.routes))if(!(!t||!t.prettyPath)&&l(t.prettyPath)===r)return u(e);return null}let p=null,ee=new Set([`chat`,`files`,`tasks`,`pages`,`settings`,`tools`,`channels`]);function m(){p=null}typeof globalThis<`u`&&(globalThis.__applyBasePathCacheReset=m);function h(){let e=typeof window<`u`?window:typeof self<`u`?self:globalThis;if(e&&e.__SHADOWCLAW_DEPLOY_ID__){let t=String(e.__SHADOWCLAW_DEPLOY_ID__).trim();if(t)return t.replace(/[^a-zA-Z0-9_-]/g,`-`)}let t=globalThis.process;if(t&&t.env&&t.env.SHADOWCLAW_DEPLOY_ID){let e=String(t.env.SHADOWCLAW_DEPLOY_ID).trim();if(e)return e.replace(/[^a-zA-Z0-9_-]/g,`-`)}let n=te();return!n||n===`/`?``:n.replace(/^\/+|\/+$/g,``).replace(/[^a-zA-Z0-9_-]/g,`-`)}function te(){if(p!==null)return p;if((typeof window>`u`||globalThis.WorkerGlobalScope!==void 0&&typeof self<`u`&&self instanceof globalThis.WorkerGlobalScope)&&typeof self<`u`&&self.location){let e=(self.location.pathname||`/`).split(`/`).filter(Boolean);if(e.length<=1)return p=`/`,p;let t=e[0].toLowerCase(),n=t===`service-worker.js`||t===`sw.js`||t===`manifest.json`||t===`sitemap.xml`||t===`favicon.ico`||t===`index.html`||t===`service-worker`||t===`assets`||t===`dist`||t===`public`;if(n&&e.length===2)return p=`/`,p;if(!n)return p=`/`+e[0]+`/`,p}let e=typeof window<`u`&&window.location?window.location:typeof self<`u`&&self.location?self.location:null;if(!e)return`/`;if(typeof document<`u`&&typeof document.querySelector==`function`){let t=document.querySelector(`base[href]`);if(t){let n=t.getAttribute(`href`);if(n)try{let t=new URL(n,e.origin).pathname;return t.endsWith(`/`)||(t+=`/`),p=t,p}catch{}}}let t=e.pathname||`/`;if(t===`/`)return p=`/`,p;let n=t.split(`/`).filter(Boolean),r=n.findIndex(e=>ee.has(e.toLowerCase()));return r>=0?r===0?(p=`/`,p):(p=`/`+n.slice(0,r).join(`/`)+`/`,p):f(t)?(p=`/`,p):n.length===1&&!t.includes(`.`)?(p=`/`+n[0]+`/`,p):(p=`/`,p)}function ne(e){let t=e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`(^|\\s)@${t}\\b`,`i`)}ne(`ShadowClaw`);function g(){let e=h();return e?`shadowclaw-${e}`:`shadowclaw`}g();let _={github:{providerId:`github`,name:`GitHub`,aliases:[`github`,`api.github.com`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`http_api`,`git_remote`],authTypes:[`token`,`oauth`],tokenAuth:{token:{headerName:`Authorization`,headerPrefix:`token `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},oauth:{authorizeUrl:`https://github.com/login/oauth/authorize`,tokenUrl:`https://github.com/login/oauth/access_token`,defaultScopes:[`repo`,`read:user`],usePkce:!0,clientAuthMethod:`request_body`,scopeSeparator:`space`}},gitlab:{providerId:`gitlab`,name:`GitLab`,aliases:[`gitlab`,`gitlab.com`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`http_api`,`git_remote`],authTypes:[`token`,`oauth`],tokenAuth:{token:{headerName:`PRIVATE-TOKEN`,headerPrefix:``},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},tokenAuthByServiceType:{git_remote:{token:{headerName:`Authorization`,headerPrefix:`Bearer `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}}},oauth:{authorizeUrl:`https://gitlab.com/oauth/authorize`,tokenUrl:`https://gitlab.com/oauth/token`,defaultScopes:[`read_api`,`read_user`],usePkce:!0,clientAuthMethod:`request_body`,scopeSeparator:`space`}},figma:{providerId:`figma`,name:`Figma`,aliases:[`figma`,`api.figma.com`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`http_api`],authTypes:[`token`,`oauth`],tokenAuth:{token:{headerName:`X-Figma-Token`,headerPrefix:``},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},oauth:{authorizeUrl:`https://www.figma.com/oauth`,tokenUrl:`https://api.figma.com/v1/oauth/token`,refreshUrl:`https://api.figma.com/v1/oauth/refresh`,defaultScopes:[],usePkce:!0,clientAuthMethod:`basic_header`,scopeSeparator:`space`}},notion:{providerId:`notion`,name:`Notion`,aliases:[`notion`,`api.notion.com`,`notion.so`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`http_api`],authTypes:[`token`,`oauth`],tokenAuth:{token:{headerName:`Authorization`,headerPrefix:`Bearer `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},oauth:{authorizeUrl:`https://api.notion.com/v1/oauth/authorize`,tokenUrl:`https://api.notion.com/v1/oauth/token`,defaultScopes:[],usePkce:!0,clientAuthMethod:`basic_header`,scopeSeparator:`space`}},microsoft_graph:{providerId:`microsoft_graph`,name:`Microsoft Graph`,aliases:[`microsoft`,`graph.microsoft.com`,`microsoft_graph`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`http_api`],authTypes:[`token`,`oauth`],tokenAuth:{token:{headerName:`Authorization`,headerPrefix:`Bearer `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},oauth:{authorizeUrl:`https://login.microsoftonline.com/common/oauth2/v2.0/authorize`,tokenUrl:`https://login.microsoftonline.com/common/oauth2/v2.0/token`,defaultScopes:[`openid`,`profile`,`offline_access`,`User.Read`],usePkce:!0,clientAuthMethod:`request_body`,scopeSeparator:`space`}},yahoo_mail:{providerId:`yahoo_mail`,name:`Yahoo Mail`,aliases:[`yahoo`,`yahoo_mail`,`mail.yahoo.com`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`http_api`],authTypes:[`token`,`oauth`],tokenAuth:{token:{headerName:`Authorization`,headerPrefix:`Bearer `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},oauth:{authorizeUrl:`https://api.login.yahoo.com/oauth2/request_auth`,tokenUrl:`https://api.login.yahoo.com/oauth2/get_token`,defaultScopes:[`mail-r`,`mail-w`],usePkce:!0,clientAuthMethod:`request_body`,scopeSeparator:`space`}},google:{providerId:`google`,name:`Google`,aliases:[`google`,`googleapis.com`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`http_api`],authTypes:[`token`,`oauth`],tokenAuth:{token:{headerName:`Authorization`,headerPrefix:`Bearer `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},oauth:{authorizeUrl:`https://accounts.google.com/o/oauth2/v2/auth`,tokenUrl:`https://oauth2.googleapis.com/token`,defaultScopes:[`openid`,`profile`,`email`],usePkce:!0,clientAuthMethod:`request_body`,scopeSeparator:`space`}},atlassian:{providerId:`atlassian`,name:`Atlassian`,aliases:[`atlassian`,`api.atlassian.com`],modes:[`oauth`,`token`,`basic`],defaultMode:`basic`,serviceTypes:[`http_api`,`git_remote`],authTypes:[`token`,`oauth`,`basic_userpass`],tokenAuth:{token:{headerName:`Authorization`,headerPrefix:`Bearer `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `},basic:{headerName:`Authorization`,headerPrefix:`Basic `}},oauth:{authorizeUrl:`https://auth.atlassian.com/authorize`,tokenUrl:`https://auth.atlassian.com/oauth/token`,defaultScopes:[],usePkce:!0,clientAuthMethod:`request_body`,scopeSeparator:`space`}},slack:{providerId:`slack`,name:`Slack`,aliases:[`slack`,`slack.com`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`http_api`],authTypes:[`token`,`oauth`],tokenAuth:{token:{headerName:`Authorization`,headerPrefix:`Bearer `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},oauth:{authorizeUrl:`https://slack.com/oauth/v2/authorize`,tokenUrl:`https://slack.com/api/oauth.v2.access`,defaultScopes:[],usePkce:!1,clientAuthMethod:`request_body`,scopeSeparator:`comma`}},linear:{providerId:`linear`,name:`Linear`,aliases:[`linear`,`api.linear.app`,`linear.app`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`http_api`],authTypes:[`token`,`oauth`],tokenAuth:{token:{headerName:`Authorization`,headerPrefix:`Bearer `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},oauth:{authorizeUrl:`https://linear.app/oauth/authorize`,tokenUrl:`https://api.linear.app/oauth/token`,defaultScopes:[],usePkce:!0,clientAuthMethod:`request_body`,scopeSeparator:`space`}},azure_devops:{providerId:`azure_devops`,name:`Azure DevOps`,aliases:[`azure_devops`,`dev.azure.com`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`http_api`,`git_remote`],authTypes:[`token`,`oauth`,`basic_userpass`,`ssh_key`],tokenAuth:{token:{headerName:`Authorization`,headerPrefix:`Bearer `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},tokenAuthByServiceType:{git_remote:{token:{headerName:`Authorization`,headerPrefix:`Basic `},oauth:{headerName:`Authorization`,headerPrefix:`Basic `}}},oauth:{authorizeUrl:`https://app.vssps.visualstudio.com/oauth2/authorize`,tokenUrl:`https://app.vssps.visualstudio.com/oauth2/token`,defaultScopes:[`vso.code`,`vso.profile`,`offline_access`],usePkce:!1,clientAuthMethod:`request_body`,scopeSeparator:`space`}},custom_mcp:{providerId:`custom_mcp`,name:`Custom MCP`,aliases:[`custom_mcp`],modes:[`oauth`,`token`],defaultMode:`oauth`,serviceTypes:[`mcp_remote`,`webmcp_local`],authTypes:[`none`,`token`,`oauth`,`custom_header`,`ssh_key`],tokenAuth:{token:{headerName:`Authorization`,headerPrefix:`Bearer `},oauth:{headerName:`Authorization`,headerPrefix:`Bearer `}},oauth:{authorizeUrl:`https://example.com/oauth/authorize`,tokenUrl:`https://example.com/oauth/token`,defaultScopes:[],usePkce:!0,clientAuthMethod:`request_body`,scopeSeparator:`space`}}};Object.fromEntries(Object.values(_).filter(e=>!!e.oauth).map(e=>{let t=e.oauth;return[e.providerId,{id:e.providerId,name:e.name,authorizeUrl:t.authorizeUrl,tokenUrl:t.tokenUrl,redirectUri:t.redirectUri,defaultScopes:t.defaultScopes,usePkce:t.usePkce,clientAuthMethod:t.clientAuthMethod,scopeSeparator:t.scopeSeparator}]})),Object.fromEntries(Object.values(_).map(e=>[e.providerId,{providerId:e.providerId,modes:e.modes,defaultMode:e.defaultMode}])),new Promise(e=>{});
3
3
  /*! @license DOMPurify 3.4.13 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.13/LICENSE */
4
4
  function v(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function y(e){if(Array.isArray(e))return e}function b(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function re(){throw TypeError(`Invalid attempt to destructure non-iterable instance.