shadow-claw 1.24.0 → 1.25.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 (85) hide show
  1. package/README.md +2 -1
  2. package/bin/cli.mjs +111 -2
  3. package/bin/commands/webrtc-listen.mjs +21 -1
  4. package/bin/utils/control-client.mjs +44 -30
  5. package/bin/utils/control-client.test.mjs +10 -0
  6. package/bin/utils/webrtc-control-client.mjs +23 -4
  7. package/dist/public/AGENTS.md +8 -1
  8. package/dist/public/README.md +2 -1
  9. package/dist/public/agent.worker.js +49 -49
  10. package/dist/public/backup-controller-CvzDOq4T.js +1 -0
  11. package/dist/public/{configurePeerJs-CxpZeDJJ.js → configurePeerJs-UfQ6HUlv.js} +1 -1
  12. package/dist/public/docs/README.md +1 -1
  13. package/dist/public/docs/example/article/index.html +1 -1
  14. package/dist/public/docs/guides/server-development-configuration.md +28 -0
  15. package/dist/public/docs/publishing/index.html +1 -1
  16. package/dist/public/docs/skill-creator/index.html +1 -1
  17. package/dist/public/docs/subsystems/cli.md +25 -19
  18. package/dist/public/docs/subsystems/control-plane.md +11 -0
  19. package/dist/public/{downloadGroupFile-By0GR6eV.js → downloadGroupFile-9niHBj9n.js} +1 -1
  20. package/dist/public/{e2e-bridge-IGWsRl4i.js → e2e-bridge-D28tOggc.js} +1 -1
  21. package/dist/public/{file-viewer-D0eflgt6.js → file-viewer-BVg3B_JH.js} +1 -1
  22. package/dist/public/index.html +1 -1
  23. package/dist/public/index.js +1 -1
  24. package/dist/public/initControlPlane-D5kHKcB5.js +1 -0
  25. package/dist/public/llms.txt +1 -1
  26. package/dist/public/main/index.html +1 -1
  27. package/dist/public/main/memory/index.html +1 -1
  28. package/dist/public/{markdown-BnpKxSxl.js → markdown-SiFq0PTy.js} +1 -1
  29. package/dist/public/{orchestrator-nJj59RqD.js → orchestrator-CnwkoBpe.js} +1 -1
  30. package/dist/public/{orchestrator-3h9xxHUm.js → orchestrator-tHWrqi_F.js} +5 -5
  31. package/dist/public/{peerjs-BP4laMXj.js → peerjs-CuSJUH-r.js} +1 -1
  32. package/dist/public/push-client-D0lkwrK0.js +1 -0
  33. package/dist/public/service-worker/fetch-proxy.js +1 -1
  34. package/dist/public/service-worker.js +1 -1
  35. package/dist/public/{shadow-claw-CbwETBWf.js → shadow-claw-CUbhMmcB.js} +2 -2
  36. package/dist/public/{shadow-claw-channels-BDWG5Qa3.js → shadow-claw-channels-mY-JMvib.js} +1 -1
  37. package/dist/public/{shadow-claw-chat-Crv0DTCY.js → shadow-claw-chat-BN85a1xk.js} +1 -1
  38. package/dist/public/{shadow-claw-control-plane-CX1IGbh9.js → shadow-claw-control-plane-C0lSxLpW.js} +2 -2
  39. package/dist/public/{shadow-claw-conversations-_9qAaRXk.js → shadow-claw-conversations-0Q-VC_7N.js} +1 -1
  40. package/dist/public/{shadow-claw-file-viewer-Blf6yGVD.js → shadow-claw-file-viewer-AZfG4D-u.js} +1 -1
  41. package/dist/public/{shadow-claw-files-CYySBDCl.js → shadow-claw-files-Bx4v0Ggp.js} +1 -1
  42. package/dist/public/{shadow-claw-git-v8S0JjuR.js → shadow-claw-git-DD7iQRxq.js} +2 -2
  43. package/dist/public/{shadow-claw-llm-GWgoVfhI.js → shadow-claw-llm-CfeDBZKB.js} +1 -1
  44. package/dist/public/{shadow-claw-networking-qHbP95z9.js → shadow-claw-networking-e0EarDVs.js} +1 -1
  45. package/dist/public/{shadow-claw-notifications-YyHOK2Fr.js → shadow-claw-notifications-BkxuDEQI.js} +3 -3
  46. package/dist/public/{shadow-claw-pages-DFZHhzFZ.js → shadow-claw-pages-BWSE91I1.js} +1 -1
  47. package/dist/public/{shadow-claw-settings-DhxrKIfA.js → shadow-claw-settings-BZWrAoQA.js} +2 -2
  48. package/dist/public/{shadow-claw-storage-BFynbP0j.js → shadow-claw-storage-Crs6LY15.js} +1 -1
  49. package/dist/public/{shadow-claw-task-server-3BIeb5oZ.js → shadow-claw-task-server-CKm_Ennl.js} +1 -1
  50. package/dist/public/{shadow-claw-tasks-Caxc9atL.js → shadow-claw-tasks-Czx6Ucf5.js} +1 -1
  51. package/dist/public/{shadow-claw-terminal-Beb5qF-U.js → shadow-claw-terminal-Dmtr9KY1.js} +1 -1
  52. package/dist/public/{shadow-claw-tools-BfJx3A9W.js → shadow-claw-tools-t3Qq4TDO.js} +1 -1
  53. package/dist/public/{shadow-claw-webvm-BCS8ykeP.js → shadow-claw-webvm-CIuSywD_.js} +1 -1
  54. package/dist/public/{syncWebMcpRegistration-B_M2fCjH.js → syncWebMcpRegistration-DzC80wVG.js} +1 -1
  55. package/dist/server.js +203 -203
  56. package/package.json +1 -1
  57. package/src/components/settings/shadow-claw-notifications/shadow-claw-notifications.test.ts +3 -0
  58. package/src/components/settings/shadow-claw-notifications/shadow-claw-notifications.ts +43 -9
  59. package/src/core/backup-controller.ts +33 -4
  60. package/src/core/control-plane-client.test.ts +9 -2
  61. package/src/core/control-plane-client.ts +18 -2
  62. package/src/core/orchestrator/utils/operations/task.ts +46 -15
  63. package/src/core/utils/initControlPlane.ts +2 -0
  64. package/src/server/app.ts +2 -0
  65. package/src/server/config.test.ts +49 -0
  66. package/src/server/config.ts +47 -0
  67. package/src/server/control-plane.test.ts +36 -0
  68. package/src/server/control-plane.ts +41 -14
  69. package/src/server/middleware/pna.test.ts +15 -3
  70. package/src/server/middleware/pna.ts +6 -2
  71. package/src/server/peer.ts +6 -2
  72. package/src/server/routes/backup.test.ts +14 -0
  73. package/src/server/routes/backup.ts +44 -15
  74. package/src/server/server.test.ts +118 -0
  75. package/src/server/server.ts +22 -5
  76. package/src/server/tls.test.ts +266 -0
  77. package/src/server/tls.ts +178 -0
  78. package/src/service-worker/fetch-proxy-rules.test.ts +41 -0
  79. package/src/service-worker/fetch-proxy-rules.ts +15 -8
  80. package/src/service-worker/fetch-proxy.ts +18 -2
  81. package/src/subsystems/notifications/push-client.test.ts +5 -1
  82. package/src/subsystems/notifications/push-client.ts +50 -12
  83. package/dist/public/backup-controller-C_s9in2t.js +0 -1
  84. package/dist/public/initControlPlane-C9jpnWev.js +0 -1
  85. package/dist/public/push-client-CrjEXK3U.js +0 -1
@@ -1,4 +1,4 @@
1
- import{b as e,r as t}from"./config-CrHchneq.js";import{n}from"./txPromise-EBECky1b.js";import{t as r}from"./getConfig-D89uJgo5.js";import{m as i,u as a}from"./custom-element-security-NCqQ5lmC.js";import{t as o}from"./orchestrator-3h9xxHUm.js";import{f as s,h as c}from"./mcp-reconnect-9emsqGRe.js";import{r as l,t as u}from"./toast-D3gxhZpN.js";import{t as d}from"./shadow-claw-element-DIrv3P6A.js";import"./shadow-claw-card-DCxWEHgX.js";import"./shadow-claw-empty-state-obMInUIf.js";const f=new CSSStyleSheet;f.replaceSync(`*,
1
+ import{b as e,r as t}from"./config-CrHchneq.js";import{n}from"./txPromise-EBECky1b.js";import{t as r}from"./getConfig-D89uJgo5.js";import{m as i,u as a}from"./custom-element-security-NCqQ5lmC.js";import{t as o}from"./orchestrator-tHWrqi_F.js";import{f as s,h as c}from"./mcp-reconnect-9emsqGRe.js";import{r as l,t as u}from"./toast-D3gxhZpN.js";import{t as d}from"./shadow-claw-element-DIrv3P6A.js";import"./shadow-claw-card-DCxWEHgX.js";import"./shadow-claw-empty-state-obMInUIf.js";const f=new CSSStyleSheet;f.replaceSync(`*,
2
2
  *::before,
3
3
  *::after {
4
4
  font-family: var(--shadow-claw-font-sans);
@@ -444,4 +444,4 @@ import{b as e,r as t}from"./config-CrHchneq.js";import{n}from"./txPromise-EBECky
444
444
  </button>
445
445
  <button class="cancel-btn" data-action="cancel-account-form">Cancel</button>
446
446
  </div>
447
- </div>`),p.querySelector(`[data-action="save-account"]`)?.addEventListener(`click`,()=>this.saveAccountForm()),p.querySelector(`[data-action="cancel-account-form"]`)?.addEventListener(`click`,()=>this.hideAccountForm()),p.querySelector(`[data-field="acct-auth-mode"]`)?.addEventListener(`change`,()=>this.updateAuthModeVisibility(p)),p.querySelector(`[data-action="connect-oauth"]`)?.addEventListener(`click`,()=>void this.connectOAuthFromForm(p)),this.updateAuthModeVisibility(p))}updateAuthModeVisibility(e){let t=e.querySelector(`[data-field="acct-auth-mode"]`)?.value===`oauth`,n=e.querySelector(`[data-region="oauth-fields"]`),r=e.querySelector(`[data-region="pat-fields"]`);n instanceof HTMLElement&&(n.style.display=t?`block`:`none`),r instanceof HTMLElement&&(r.style.display=t?`none`:`block`)}updateCustomProxyVisibility(){let e=this.shadowRoot;if(!e)return;let t=e.querySelector(`[data-setting="git-proxy-custom"]`),n=e.querySelector(`[data-region="git-custom-proxy-field"]`);n instanceof HTMLElement&&(n.style.display=t?.checked?`block`:`none`)}async connectOAuthFromForm(e){let t=e.querySelector(`[data-field="acct-oauth-provider"]`)?.value,n=e.querySelector(`[data-field="acct-oauth-client-id"]`)?.value.trim(),r=e.querySelector(`[data-field="acct-oauth-client-secret"]`)?.value.trim(),i=e.querySelector(`[data-field="acct-oauth-scope"]`)?.value.trim();if(!t){u(`OAuth provider is required.`,4e3);return}if(!n){u(`OAuth client ID is required.`,4e3);return}let a=e.querySelector(`[data-region="oauth-status"]`),o=e.querySelector(`[data-action="connect-oauth"]`);a&&(a.textContent=`Starting OAuth...`),o&&(o.disabled=!0);try{let e=i?i.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean):void 0,o=await fetch(`/oauth/authorize`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({providerId:t,clientId:n,clientSecret:r||void 0,redirectUri:`${window.location.origin}/oauth/callback`,scope:e})}),s=await o.json();if(!o.ok||!s.state||!s.authorizeUrl)throw Error(s.error||`OAuth authorize failed`);window.open(s.authorizeUrl,`shadowclaw-oauth`,`popup=yes,width=540,height=720`);let c=s.state,u=`pending`;for(let e=0;e<60;e++){let e=await fetch(`/oauth/session/${encodeURIComponent(c)}`),t=await e.json();if(!e.ok)throw Error(t.error||`OAuth session not found`);if(u=t.status||`pending`,u===`authorized`)break;if(u===`error`)throw Error(t.error||`OAuth authorization failed`);await new Promise(e=>setTimeout(e,1e3))}if(u!==`authorized`)throw Error(`OAuth authorization timed out`);let d=await fetch(`/oauth/token`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({state:c})}),f=await d.json();if(!d.ok||!f.accessToken)throw Error(f.error||`OAuth token exchange failed`);this.pendingOauthResult={providerId:t,accessToken:f.accessToken,refreshToken:f.refreshToken,expiresAt:f.expiresIn?Date.now()+f.expiresIn*1e3:void 0,scope:f.scope,tokenType:f.tokenType},a&&(a.textContent=`OAuth connected`),l(`OAuth connected`,3e3)}catch(e){let t=e instanceof Error?e.message:String(e);a&&(a.textContent=`OAuth failed`),u(`OAuth connect failed: ${t}`,6e3)}finally{o&&(o.disabled=!1)}}async deleteAccount(e){if(this.db){this.accounts=this.accounts.filter(t=>t.id!==e),this.defaultAccountId===e&&(this.defaultAccountId=this.accounts[0]?.id||``);try{let{setConfig:e}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await e(this.db,t.GIT_ACCOUNTS,this.accounts),await e(this.db,t.GIT_DEFAULT_ACCOUNT,this.defaultAccountId)}catch(e){console.warn(`Error persisting account deletion:`,e)}this.renderAccountList(),this.updateGitWarning(),l(`Account deleted`,3e3)}}async migrateLegacyAccount(){if(!this.db)return;let e=await r(this.db,t.GIT_TOKEN),n=await r(this.db,t.GIT_USERNAME);if(!e&&!n)return;let i=await r(this.db,t.GIT_PASSWORD)||``,a={id:`legacy-migrated`,label:`GitHub`,hostPattern:`github.com`,token:e||``,username:n||``,password:i,authorName:``,authorEmail:``};this.accounts=[a],this.defaultAccountId=a.id;let{setConfig:o}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await o(this.db,t.GIT_ACCOUNTS,this.accounts),await o(this.db,t.GIT_DEFAULT_ACCOUNT,a.id)}async render(){let e=this.shadowRoot;if(e)try{let n=await r(this.db,t.GIT_CORS_PROXY)||`local`,i=e.querySelector(`[data-setting="git-proxy-local"]`),a=e.querySelector(`[data-setting="git-proxy-public"]`),s=e.querySelector(`[data-setting="git-proxy-custom"]`),c=e.querySelector(`[data-setting="git-proxy-url-input"]`);i&&a&&s&&(i.checked=n===`local`,a.checked=n===`public`,s.checked=n===`custom`),c&&(c.value=o.gitProxyUrl||`/git-proxy`),this.updateCustomProxyVisibility();let l=e.querySelector(`[data-setting="git-author-name-input"]`);l&&(l.value=await r(this.db,t.GIT_AUTHOR_NAME)||`ShadowClaw`);let u=e.querySelector(`[data-setting="git-author-email-input"]`);u&&(u.value=await r(this.db,t.GIT_AUTHOR_EMAIL)||`agent@example.com`);let d=await r(this.db,t.GIT_ACCOUNTS);this.accounts=Array.isArray(d)?d:[],this.defaultAccountId=await r(this.db,t.GIT_DEFAULT_ACCOUNT)||``,this.accounts.length===0&&await this.migrateLegacyAccount(),this.renderAccountList(),this.updateGitWarning()}catch(e){console.warn(`Could not load git settings:`,e)}}async saveAccountForm(){if(!this.db)return;let e=this.shadowRoot;if(!e)return;let n=e.querySelector(`[data-region="account-form-slot"]`);if(!n)return;let r=n.querySelector(`[data-field="acct-label"]`)?.value.trim(),i=n.querySelector(`[data-field="acct-host"]`)?.value.trim(),a=n.querySelector(`[data-field="acct-auth-mode"]`)?.value;if(!r||!i){u(`Label and Host Pattern are required.`,4e3);return}try{let{encryptValue:e}=await import(`./crypto-C8c5wMzN.js`).then(e=>e.t),{setConfig:o}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n),s=n.querySelector(`[data-field="acct-token"]`)?.value.trim(),c=n.querySelector(`[data-field="acct-password"]`)?.value.trim(),d=n.querySelector(`[data-field="acct-username"]`)?.value.trim()||``,f=n.querySelector(`[data-field="acct-author-name"]`)?.value.trim()||``,p=n.querySelector(`[data-field="acct-author-email"]`)?.value.trim()||``,m=this.editingAccountId===`new`,h=m?null:this.accounts.find(e=>e.id===this.editingAccountId),g=h?.token||``,_=h?.password||``,v=h?.oauthProviderId,y=h?.oauthClientId,b=h?.oauthClientSecret,x=h?.accessTokenExpiresAt,S=h?.refreshToken,C=h?.scopes,w=h?.tokenType,T=h?.oauthRefreshFailureCount,E=h?.oauthReauthRequired,D=h?.oauthReauthRequiredAt;if(a===`oauth`){v=n.querySelector(`[data-field="acct-oauth-provider"]`)?.value,y=n.querySelector(`[data-field="acct-oauth-client-id"]`)?.value.trim();let t=n.querySelector(`[data-field="acct-oauth-client-secret"]`)?.value.trim(),r=n.querySelector(`[data-field="acct-oauth-scope"]`)?.value.trim(),i=r?r.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean):void 0;if(!v){u(`OAuth provider is required for OAuth mode.`,4e3);return}if(!y){u(`OAuth client ID is required for OAuth mode.`,4e3);return}if(t){let n=await e(t);n&&(b=n)}if(this.pendingOauthResult?.accessToken){let t=await e(this.pendingOauthResult.accessToken);if(t&&(g=t),this.pendingOauthResult.refreshToken){let t=await e(this.pendingOauthResult.refreshToken);t&&(S=t)}x=this.pendingOauthResult.expiresAt,C=this.pendingOauthResult.scope?this.pendingOauthResult.scope.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean):i||C,w=this.pendingOauthResult.tokenType,T=0,E=!1,D=void 0}else C=i||C;if(!g){u(`Connect OAuth first to obtain an access token for this account.`,5e3);return}_=``}else{if(s){let t=await e(s);t&&(g=t)}if(c){let t=await e(c);t&&(_=t)}v=void 0,y=void 0,b=void 0,x=void 0,S=void 0,C=void 0,w=void 0,T=void 0,E=void 0,D=void 0}if(m){let{ulid:e}=await import(`./ulid-BY7rQVLN.js`).then(e=>e.n),n={id:e(),label:r,hostPattern:i,token:g,username:a===`oauth`?``:d,password:_,authorName:f,authorEmail:p,authMode:a||`token`,oauthProviderId:v,oauthClientId:y,oauthClientSecret:b,accessTokenExpiresAt:x,refreshToken:S,scopes:C,tokenType:w,oauthRefreshFailureCount:T,oauthReauthRequired:E,oauthReauthRequiredAt:D};this.accounts.push(n),this.accounts.length===1&&(this.defaultAccountId=n.id,await o(this.db,t.GIT_DEFAULT_ACCOUNT,n.id))}else h&&(h.label=r,h.hostPattern=i,h.token=g,h.username=a===`oauth`?``:d,h.password=_,h.authorName=f,h.authorEmail=p,h.authMode=a||`token`,h.oauthProviderId=v,h.oauthClientId=y,h.oauthClientSecret=b,h.accessTokenExpiresAt=x,h.refreshToken=S,h.scopes=C,h.tokenType=w,h.oauthRefreshFailureCount=T,h.oauthReauthRequired=E,h.oauthReauthRequiredAt=D);await o(this.db,t.GIT_ACCOUNTS,this.accounts),this.hideAccountForm(),this.renderAccountList(),this.updateGitWarning(),l(m?`Account added`:`Account updated`,3e3)}catch(e){u(`Error saving account: `+(e instanceof Error?e.message:String(e)),6e3)}}async saveGitSettings(){if(!this.db)return;let e=this.shadowRoot;if(e)try{let{setConfig:n}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n),r=e.querySelector(`[data-setting="git-proxy-public"]`),i=e.querySelector(`[data-setting="git-proxy-custom"]`),a=r?.checked?`public`:i?.checked?`custom`:`local`;if(await n(this.db,t.GIT_CORS_PROXY,a),a===`custom`){let t=e.querySelector(`[data-setting="git-proxy-url-input"]`)?.value.trim()||`/git-proxy`,{orchestratorStore:n}=await import(`./orchestrator-3h9xxHUm.js`).then(e=>e.n);await n.setGitProxyUrl(this.db,t)}let o=e.querySelector(`[data-setting="git-author-name-input"]`);o&&await n(this.db,t.GIT_AUTHOR_NAME,o.value.trim()||`ShadowClaw`);let s=e.querySelector(`[data-setting="git-author-email-input"]`);s&&await n(this.db,t.GIT_AUTHOR_EMAIL,s.value.trim()||`agent@example.com`),l(`Git settings saved`,3e3),this.updateGitWarning()}catch(e){u(`Error saving Git settings: `+(e instanceof Error?e.message:String(e)),6e3)}}async setDefaultAccount(e){if(this.db){this.defaultAccountId=e;try{let{setConfig:n}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await n(this.db,t.GIT_DEFAULT_ACCOUNT,e)}catch(e){console.warn(`Error setting default account:`,e)}this.renderAccountList(),l(`Default account updated`,3e3)}}async updateGitWarning(){let e=this.shadowRoot;if(!e)return;let t=e.querySelector(`[data-setting="git-proxy-warning"]`);if(!t)return;let n=e.querySelector(`[data-setting="git-proxy-public"]`),r=this.accounts.some(e=>!!e.token);t.style.display=n?.checked&&r?`block`:`none`}};customElements.get(_)||customElements.define(_,x);export{x as ShadowClawGit};
447
+ </div>`),p.querySelector(`[data-action="save-account"]`)?.addEventListener(`click`,()=>this.saveAccountForm()),p.querySelector(`[data-action="cancel-account-form"]`)?.addEventListener(`click`,()=>this.hideAccountForm()),p.querySelector(`[data-field="acct-auth-mode"]`)?.addEventListener(`change`,()=>this.updateAuthModeVisibility(p)),p.querySelector(`[data-action="connect-oauth"]`)?.addEventListener(`click`,()=>void this.connectOAuthFromForm(p)),this.updateAuthModeVisibility(p))}updateAuthModeVisibility(e){let t=e.querySelector(`[data-field="acct-auth-mode"]`)?.value===`oauth`,n=e.querySelector(`[data-region="oauth-fields"]`),r=e.querySelector(`[data-region="pat-fields"]`);n instanceof HTMLElement&&(n.style.display=t?`block`:`none`),r instanceof HTMLElement&&(r.style.display=t?`none`:`block`)}updateCustomProxyVisibility(){let e=this.shadowRoot;if(!e)return;let t=e.querySelector(`[data-setting="git-proxy-custom"]`),n=e.querySelector(`[data-region="git-custom-proxy-field"]`);n instanceof HTMLElement&&(n.style.display=t?.checked?`block`:`none`)}async connectOAuthFromForm(e){let t=e.querySelector(`[data-field="acct-oauth-provider"]`)?.value,n=e.querySelector(`[data-field="acct-oauth-client-id"]`)?.value.trim(),r=e.querySelector(`[data-field="acct-oauth-client-secret"]`)?.value.trim(),i=e.querySelector(`[data-field="acct-oauth-scope"]`)?.value.trim();if(!t){u(`OAuth provider is required.`,4e3);return}if(!n){u(`OAuth client ID is required.`,4e3);return}let a=e.querySelector(`[data-region="oauth-status"]`),o=e.querySelector(`[data-action="connect-oauth"]`);a&&(a.textContent=`Starting OAuth...`),o&&(o.disabled=!0);try{let e=i?i.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean):void 0,o=await fetch(`/oauth/authorize`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({providerId:t,clientId:n,clientSecret:r||void 0,redirectUri:`${window.location.origin}/oauth/callback`,scope:e})}),s=await o.json();if(!o.ok||!s.state||!s.authorizeUrl)throw Error(s.error||`OAuth authorize failed`);window.open(s.authorizeUrl,`shadowclaw-oauth`,`popup=yes,width=540,height=720`);let c=s.state,u=`pending`;for(let e=0;e<60;e++){let e=await fetch(`/oauth/session/${encodeURIComponent(c)}`),t=await e.json();if(!e.ok)throw Error(t.error||`OAuth session not found`);if(u=t.status||`pending`,u===`authorized`)break;if(u===`error`)throw Error(t.error||`OAuth authorization failed`);await new Promise(e=>setTimeout(e,1e3))}if(u!==`authorized`)throw Error(`OAuth authorization timed out`);let d=await fetch(`/oauth/token`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({state:c})}),f=await d.json();if(!d.ok||!f.accessToken)throw Error(f.error||`OAuth token exchange failed`);this.pendingOauthResult={providerId:t,accessToken:f.accessToken,refreshToken:f.refreshToken,expiresAt:f.expiresIn?Date.now()+f.expiresIn*1e3:void 0,scope:f.scope,tokenType:f.tokenType},a&&(a.textContent=`OAuth connected`),l(`OAuth connected`,3e3)}catch(e){let t=e instanceof Error?e.message:String(e);a&&(a.textContent=`OAuth failed`),u(`OAuth connect failed: ${t}`,6e3)}finally{o&&(o.disabled=!1)}}async deleteAccount(e){if(this.db){this.accounts=this.accounts.filter(t=>t.id!==e),this.defaultAccountId===e&&(this.defaultAccountId=this.accounts[0]?.id||``);try{let{setConfig:e}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await e(this.db,t.GIT_ACCOUNTS,this.accounts),await e(this.db,t.GIT_DEFAULT_ACCOUNT,this.defaultAccountId)}catch(e){console.warn(`Error persisting account deletion:`,e)}this.renderAccountList(),this.updateGitWarning(),l(`Account deleted`,3e3)}}async migrateLegacyAccount(){if(!this.db)return;let e=await r(this.db,t.GIT_TOKEN),n=await r(this.db,t.GIT_USERNAME);if(!e&&!n)return;let i=await r(this.db,t.GIT_PASSWORD)||``,a={id:`legacy-migrated`,label:`GitHub`,hostPattern:`github.com`,token:e||``,username:n||``,password:i,authorName:``,authorEmail:``};this.accounts=[a],this.defaultAccountId=a.id;let{setConfig:o}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await o(this.db,t.GIT_ACCOUNTS,this.accounts),await o(this.db,t.GIT_DEFAULT_ACCOUNT,a.id)}async render(){let e=this.shadowRoot;if(e)try{let n=await r(this.db,t.GIT_CORS_PROXY)||`local`,i=e.querySelector(`[data-setting="git-proxy-local"]`),a=e.querySelector(`[data-setting="git-proxy-public"]`),s=e.querySelector(`[data-setting="git-proxy-custom"]`),c=e.querySelector(`[data-setting="git-proxy-url-input"]`);i&&a&&s&&(i.checked=n===`local`,a.checked=n===`public`,s.checked=n===`custom`),c&&(c.value=o.gitProxyUrl||`/git-proxy`),this.updateCustomProxyVisibility();let l=e.querySelector(`[data-setting="git-author-name-input"]`);l&&(l.value=await r(this.db,t.GIT_AUTHOR_NAME)||`ShadowClaw`);let u=e.querySelector(`[data-setting="git-author-email-input"]`);u&&(u.value=await r(this.db,t.GIT_AUTHOR_EMAIL)||`agent@example.com`);let d=await r(this.db,t.GIT_ACCOUNTS);this.accounts=Array.isArray(d)?d:[],this.defaultAccountId=await r(this.db,t.GIT_DEFAULT_ACCOUNT)||``,this.accounts.length===0&&await this.migrateLegacyAccount(),this.renderAccountList(),this.updateGitWarning()}catch(e){console.warn(`Could not load git settings:`,e)}}async saveAccountForm(){if(!this.db)return;let e=this.shadowRoot;if(!e)return;let n=e.querySelector(`[data-region="account-form-slot"]`);if(!n)return;let r=n.querySelector(`[data-field="acct-label"]`)?.value.trim(),i=n.querySelector(`[data-field="acct-host"]`)?.value.trim(),a=n.querySelector(`[data-field="acct-auth-mode"]`)?.value;if(!r||!i){u(`Label and Host Pattern are required.`,4e3);return}try{let{encryptValue:e}=await import(`./crypto-C8c5wMzN.js`).then(e=>e.t),{setConfig:o}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n),s=n.querySelector(`[data-field="acct-token"]`)?.value.trim(),c=n.querySelector(`[data-field="acct-password"]`)?.value.trim(),d=n.querySelector(`[data-field="acct-username"]`)?.value.trim()||``,f=n.querySelector(`[data-field="acct-author-name"]`)?.value.trim()||``,p=n.querySelector(`[data-field="acct-author-email"]`)?.value.trim()||``,m=this.editingAccountId===`new`,h=m?null:this.accounts.find(e=>e.id===this.editingAccountId),g=h?.token||``,_=h?.password||``,v=h?.oauthProviderId,y=h?.oauthClientId,b=h?.oauthClientSecret,x=h?.accessTokenExpiresAt,S=h?.refreshToken,C=h?.scopes,w=h?.tokenType,T=h?.oauthRefreshFailureCount,E=h?.oauthReauthRequired,D=h?.oauthReauthRequiredAt;if(a===`oauth`){v=n.querySelector(`[data-field="acct-oauth-provider"]`)?.value,y=n.querySelector(`[data-field="acct-oauth-client-id"]`)?.value.trim();let t=n.querySelector(`[data-field="acct-oauth-client-secret"]`)?.value.trim(),r=n.querySelector(`[data-field="acct-oauth-scope"]`)?.value.trim(),i=r?r.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean):void 0;if(!v){u(`OAuth provider is required for OAuth mode.`,4e3);return}if(!y){u(`OAuth client ID is required for OAuth mode.`,4e3);return}if(t){let n=await e(t);n&&(b=n)}if(this.pendingOauthResult?.accessToken){let t=await e(this.pendingOauthResult.accessToken);if(t&&(g=t),this.pendingOauthResult.refreshToken){let t=await e(this.pendingOauthResult.refreshToken);t&&(S=t)}x=this.pendingOauthResult.expiresAt,C=this.pendingOauthResult.scope?this.pendingOauthResult.scope.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean):i||C,w=this.pendingOauthResult.tokenType,T=0,E=!1,D=void 0}else C=i||C;if(!g){u(`Connect OAuth first to obtain an access token for this account.`,5e3);return}_=``}else{if(s){let t=await e(s);t&&(g=t)}if(c){let t=await e(c);t&&(_=t)}v=void 0,y=void 0,b=void 0,x=void 0,S=void 0,C=void 0,w=void 0,T=void 0,E=void 0,D=void 0}if(m){let{ulid:e}=await import(`./ulid-BY7rQVLN.js`).then(e=>e.n),n={id:e(),label:r,hostPattern:i,token:g,username:a===`oauth`?``:d,password:_,authorName:f,authorEmail:p,authMode:a||`token`,oauthProviderId:v,oauthClientId:y,oauthClientSecret:b,accessTokenExpiresAt:x,refreshToken:S,scopes:C,tokenType:w,oauthRefreshFailureCount:T,oauthReauthRequired:E,oauthReauthRequiredAt:D};this.accounts.push(n),this.accounts.length===1&&(this.defaultAccountId=n.id,await o(this.db,t.GIT_DEFAULT_ACCOUNT,n.id))}else h&&(h.label=r,h.hostPattern=i,h.token=g,h.username=a===`oauth`?``:d,h.password=_,h.authorName=f,h.authorEmail=p,h.authMode=a||`token`,h.oauthProviderId=v,h.oauthClientId=y,h.oauthClientSecret=b,h.accessTokenExpiresAt=x,h.refreshToken=S,h.scopes=C,h.tokenType=w,h.oauthRefreshFailureCount=T,h.oauthReauthRequired=E,h.oauthReauthRequiredAt=D);await o(this.db,t.GIT_ACCOUNTS,this.accounts),this.hideAccountForm(),this.renderAccountList(),this.updateGitWarning(),l(m?`Account added`:`Account updated`,3e3)}catch(e){u(`Error saving account: `+(e instanceof Error?e.message:String(e)),6e3)}}async saveGitSettings(){if(!this.db)return;let e=this.shadowRoot;if(e)try{let{setConfig:n}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n),r=e.querySelector(`[data-setting="git-proxy-public"]`),i=e.querySelector(`[data-setting="git-proxy-custom"]`),a=r?.checked?`public`:i?.checked?`custom`:`local`;if(await n(this.db,t.GIT_CORS_PROXY,a),a===`custom`){let t=e.querySelector(`[data-setting="git-proxy-url-input"]`)?.value.trim()||`/git-proxy`,{orchestratorStore:n}=await import(`./orchestrator-tHWrqi_F.js`).then(e=>e.n);await n.setGitProxyUrl(this.db,t)}let o=e.querySelector(`[data-setting="git-author-name-input"]`);o&&await n(this.db,t.GIT_AUTHOR_NAME,o.value.trim()||`ShadowClaw`);let s=e.querySelector(`[data-setting="git-author-email-input"]`);s&&await n(this.db,t.GIT_AUTHOR_EMAIL,s.value.trim()||`agent@example.com`),l(`Git settings saved`,3e3),this.updateGitWarning()}catch(e){u(`Error saving Git settings: `+(e instanceof Error?e.message:String(e)),6e3)}}async setDefaultAccount(e){if(this.db){this.defaultAccountId=e;try{let{setConfig:n}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await n(this.db,t.GIT_DEFAULT_ACCOUNT,e)}catch(e){console.warn(`Error setting default account:`,e)}this.renderAccountList(),l(`Default account updated`,3e3)}}async updateGitWarning(){let e=this.shadowRoot;if(!e)return;let t=e.querySelector(`[data-setting="git-proxy-warning"]`);if(!t)return;let n=e.querySelector(`[data-setting="git-proxy-public"]`),r=this.accounts.some(e=>!!e.token);t.style.display=n?.checked&&r?`block`:`none`}};customElements.get(_)||customElements.define(_,x);export{x as ShadowClawGit};
@@ -1,4 +1,4 @@
1
- import{P as e,R as t,c as n,r,u as i}from"./config-CrHchneq.js";import{n as a}from"./txPromise-EBECky1b.js";import{t as o}from"./getConfig-D89uJgo5.js";import{u as s}from"./custom-element-security-NCqQ5lmC.js";import{$ as c,J as l,K as u,Nt as d,Q as f,Ut as p,W as m,_ as h,ct as g,d as _,et as v,f as y,g as b,h as x,it as S,lt as C,p as w,q as T,t as E,tt as D,v as O}from"./orchestrator-3h9xxHUm.js";import{t as k}from"./setConfig-DFMYnYLE.js";import{a as A,r as j,t as M}from"./toast-D3gxhZpN.js";import{t as N}from"./shadow-claw-element-DIrv3P6A.js";import{t as P}from"./effect-BEsuusE8.js";import{n as F,r as I}from"./prompt-api-OUOP-B-R.js";import{n as L,t as R}from"./model-ranking-C60HgQ2c.js";const z=[{pattern:`gemma-3-1b-it-ONNX-GQA`,contextWindow:128e3},{pattern:`gemma-3-1b-it-ONNX`,contextWindow:128e3},{pattern:`Qwen3-0.6B-ONNX`,contextWindow:131072},{pattern:`Qwen3.5`,contextWindow:32768},{pattern:`Llama-3.2`,contextWindow:128e3},{pattern:`Phi-4`,contextWindow:128e3},{pattern:`Phi-3.5`,contextWindow:128e3},{pattern:`SmolLM`,contextWindow:8192},{pattern:`DeepSeek-R1`,contextWindow:128e3},{pattern:`LFM2`,contextWindow:32768},{pattern:`gpt-oss`,contextWindow:32768},{pattern:`gemma-4`,contextWindow:128e3},{pattern:`browser-built-in`,contextWindow:4096}];function B(e){let n=t.getModelInfo(e);if(n&&typeof n.contextWindow==`number`&&n.contextWindow>0)return n.contextWindow;for(let{pattern:t,contextWindow:n}of z)if(e.includes(t))return n;return null}function V(t,r,i){let a=r;t===`prompt_api`&&(r===`browser-built-in`||!r)&&(i?a=i:d()||(a=n));let o=e(a),s=typeof navigator>`u`?null:navigator,c=typeof s?.deviceMemory==`number`?s.deviceMemory:null,l=typeof s?.hardwareConcurrency==`number`?s.hardwareConcurrency:null;if(t===`prompt_api`||t===`transformers_js_browser`||t===`litert_lm_browser`||t===`ollama`){let e=B(a),t=o;c!==null&&(t=c>=32?Math.min(t,16384):c>=16?Math.min(t,8192):c>=8?Math.min(t,4096):Math.min(t,2048)),l!==null&&(l<=4?t=Math.min(t,2048):l>=16?t=Math.min(o,Math.max(t,8192)):l>=8&&(t=Math.min(o,Math.max(t,4096)))),/thinking|reasoning/i.test(a)&&(t=Math.min(t,4096)),t=Math.max(512,Math.min(t,o));let n=[];return e!==null&&n.push(`native context: ${e.toLocaleString()} tokens`),c!==null&&n.push(`${c} GB browser-reported memory`),l!==null&&n.push(`${l} CPU threads`),/thinking|reasoning/i.test(a)&&n.push(`reasoning model`),{recommended:t,detail:n.length>0?`Recommended for this device: ${t.toLocaleString()} tokens (${n.join(`, `)}). Model ceiling: ${o.toLocaleString()}.`:`Recommended for local inference: ${t.toLocaleString()} tokens. Model ceiling: ${o.toLocaleString()}.`}}return{recommended:o,detail:`Model-aware ceiling: ${o.toLocaleString()} tokens.`}}const H=new CSSStyleSheet;H.replaceSync(`*,
1
+ import{P as e,R as t,c as n,r,u as i}from"./config-CrHchneq.js";import{n as a}from"./txPromise-EBECky1b.js";import{t as o}from"./getConfig-D89uJgo5.js";import{u as s}from"./custom-element-security-NCqQ5lmC.js";import{$ as c,J as l,K as u,Nt as d,Q as f,Ut as p,W as m,_ as h,ct as g,d as _,et as v,f as y,g as b,h as x,it as S,lt as C,p as w,q as T,t as E,tt as D,v as O}from"./orchestrator-tHWrqi_F.js";import{t as k}from"./setConfig-DFMYnYLE.js";import{a as A,r as j,t as M}from"./toast-D3gxhZpN.js";import{t as N}from"./shadow-claw-element-DIrv3P6A.js";import{t as P}from"./effect-BEsuusE8.js";import{n as F,r as I}from"./prompt-api-OUOP-B-R.js";import{n as L,t as R}from"./model-ranking-C60HgQ2c.js";const z=[{pattern:`gemma-3-1b-it-ONNX-GQA`,contextWindow:128e3},{pattern:`gemma-3-1b-it-ONNX`,contextWindow:128e3},{pattern:`Qwen3-0.6B-ONNX`,contextWindow:131072},{pattern:`Qwen3.5`,contextWindow:32768},{pattern:`Llama-3.2`,contextWindow:128e3},{pattern:`Phi-4`,contextWindow:128e3},{pattern:`Phi-3.5`,contextWindow:128e3},{pattern:`SmolLM`,contextWindow:8192},{pattern:`DeepSeek-R1`,contextWindow:128e3},{pattern:`LFM2`,contextWindow:32768},{pattern:`gpt-oss`,contextWindow:32768},{pattern:`gemma-4`,contextWindow:128e3},{pattern:`browser-built-in`,contextWindow:4096}];function B(e){let n=t.getModelInfo(e);if(n&&typeof n.contextWindow==`number`&&n.contextWindow>0)return n.contextWindow;for(let{pattern:t,contextWindow:n}of z)if(e.includes(t))return n;return null}function V(t,r,i){let a=r;t===`prompt_api`&&(r===`browser-built-in`||!r)&&(i?a=i:d()||(a=n));let o=e(a),s=typeof navigator>`u`?null:navigator,c=typeof s?.deviceMemory==`number`?s.deviceMemory:null,l=typeof s?.hardwareConcurrency==`number`?s.hardwareConcurrency:null;if(t===`prompt_api`||t===`transformers_js_browser`||t===`litert_lm_browser`||t===`ollama`){let e=B(a),t=o;c!==null&&(t=c>=32?Math.min(t,16384):c>=16?Math.min(t,8192):c>=8?Math.min(t,4096):Math.min(t,2048)),l!==null&&(l<=4?t=Math.min(t,2048):l>=16?t=Math.min(o,Math.max(t,8192)):l>=8&&(t=Math.min(o,Math.max(t,4096)))),/thinking|reasoning/i.test(a)&&(t=Math.min(t,4096)),t=Math.max(512,Math.min(t,o));let n=[];return e!==null&&n.push(`native context: ${e.toLocaleString()} tokens`),c!==null&&n.push(`${c} GB browser-reported memory`),l!==null&&n.push(`${l} CPU threads`),/thinking|reasoning/i.test(a)&&n.push(`reasoning model`),{recommended:t,detail:n.length>0?`Recommended for this device: ${t.toLocaleString()} tokens (${n.join(`, `)}). Model ceiling: ${o.toLocaleString()}.`:`Recommended for local inference: ${t.toLocaleString()} tokens. Model ceiling: ${o.toLocaleString()}.`}}return{recommended:o,detail:`Model-aware ceiling: ${o.toLocaleString()} tokens.`}}const H=new CSSStyleSheet;H.replaceSync(`*,
2
2
  *::before,
3
3
  *::after {
4
4
  font-family: var(--shadow-claw-font-sans);
@@ -1,4 +1,4 @@
1
- import{n as e}from"./txPromise-EBECky1b.js";import{m as t,t as n,x as r}from"./orchestrator-3h9xxHUm.js";import{a as i,r as a,t as o}from"./toast-D3gxhZpN.js";import{t as s}from"./shadow-claw-element-DIrv3P6A.js";import{t as c}from"./effect-BEsuusE8.js";const l=new CSSStyleSheet;l.replaceSync(`*,
1
+ import{n as e}from"./txPromise-EBECky1b.js";import{m as t,t as n,x as r}from"./orchestrator-tHWrqi_F.js";import{a as i,r as a,t as o}from"./toast-D3gxhZpN.js";import{t as s}from"./shadow-claw-element-DIrv3P6A.js";import{t as c}from"./effect-BEsuusE8.js";const l=new CSSStyleSheet;l.replaceSync(`*,
2
2
  *::before,
3
3
  *::after {
4
4
  font-family: var(--shadow-claw-font-sans);
@@ -1,4 +1,4 @@
1
- import{r as e}from"./config-CrHchneq.js";import{n as t}from"./txPromise-EBECky1b.js";import{t as n}from"./getConfig-D89uJgo5.js";import{t as r}from"./setConfig-DFMYnYLE.js";import{i,n as a,r as o,t as s}from"./push-client-CrjEXK3U.js";import{r as c,t as l}from"./toast-D3gxhZpN.js";import{t as u}from"./shadow-claw-element-DIrv3P6A.js";import"./shadow-claw-empty-state-obMInUIf.js";const d=new CSSStyleSheet;d.replaceSync(`*,
1
+ import{r as e}from"./config-CrHchneq.js";import{n as t}from"./txPromise-EBECky1b.js";import{t as n}from"./getConfig-D89uJgo5.js";import{t as r}from"./setConfig-DFMYnYLE.js";import{a as i,i as a,n as o,r as s,t as c}from"./push-client-D0lkwrK0.js";import{r as l,t as u}from"./toast-D3gxhZpN.js";import{t as d}from"./shadow-claw-element-DIrv3P6A.js";import"./shadow-claw-empty-state-obMInUIf.js";const f=new CSSStyleSheet;f.replaceSync(`*,
2
2
  *::before,
3
3
  *::after {
4
4
  font-family: var(--shadow-claw-font-sans);
@@ -177,7 +177,7 @@ import{r as e}from"./config-CrHchneq.js";import{n as t}from"./txPromise-EBECky1b
177
177
  border-color: var(--shadow-claw-accent-primary);
178
178
  outline: none;
179
179
  }
180
- `);const f=new DOMParser().parseFromString(`<template>
180
+ `);const p=new DOMParser().parseFromString(`<template>
181
181
  <div class="settings-section">
182
182
  <h3>🔔 Push Notifications</h3>
183
183
 
@@ -250,4 +250,4 @@ import{r as e}from"./config-CrHchneq.js";import{n as t}from"./txPromise-EBECky1b
250
250
  </div>
251
251
  </div>
252
252
  </template>
253
- `,`text/html`),p=f.querySelector(`template`);let m=[];m=p?Array.from(p.content.children):Array.from(f.head.children).concat(Array.from(f.body.children));var h=m,g=class extends u{static styles=d;static template=h;_backendAvailable=!0;_selectedId=null;_subscribed=!1;_subscriptions=[];constructor(){super()}async connectedCallback(){if(!this.shadowRoot)throw Error(`shadowRoot not found`);await this.refreshState(),await this.loadProxyConfig(),await this.loadSubscriptions(),this.bindEventListeners()}bindEventListeners(){let e=this.shadowRoot;e&&(e.querySelector(`[data-action="toggle-push"]`)?.addEventListener(`click`,()=>this.handleToggle()),e.querySelector(`[data-action="send-notification"]`)?.addEventListener(`click`,()=>this.handleSendNotification()),e.querySelector(`[data-action="delete-subscription"]`)?.addEventListener(`click`,()=>this.handleDeleteSubscription()),e.querySelector(`[data-action="refresh-subscriptions"]`)?.addEventListener(`click`,()=>this.loadSubscriptions()),e.querySelector(`[data-input="push-proxy-url"]`)?.addEventListener(`change`,e=>this.handleProxyUrlChange(e)))}renderSubscriptionList(){let e=this.shadowRoot;if(!e)return;let t=e.querySelector(`[data-info="subscription-list"]`);if(t){if(t.replaceChildren(),this._subscriptions.length===0){let e=this._backendAvailable?`No subscriptions stored.`:`⚠️ Backend services unavailable (push notification server is not running).`,n=document.createElement(`shadow-claw-empty-state`);n.setAttribute(`compact`,``),n.setAttribute(`message`,e),t.append(n);return}this._subscriptions.forEach(e=>{let n=`#${e.id}`,r=e.endpoint.length>60?`…${e.endpoint.slice(-56)}`:e.endpoint,i=e.created_at||``,a=document.createElement(`div`);a.className=`subscription-item${this._selectedId===e.id?` selected`:``}`,a.setAttribute(`data-sub-id`,String(e.id)),a.setAttribute(`data-endpoint`,e.endpoint);let o=document.createElement(`span`);o.className=`subscription-id`,o.title=e.endpoint,o.textContent=`${n} ${r}`;let s=document.createElement(`span`);s.className=`subscription-date`,s.textContent=i,a.append(o,s),a.addEventListener(`click`,()=>{this._selectedId=e.id,this.renderSubscriptionList(),this.updateActionButtons()}),t.append(a)})}}updateActionButtons(){let e=this.shadowRoot;if(!e)return;let t=this._selectedId!=null,n=e.querySelector(`[data-action="send-notification"]`),r=e.querySelector(`[data-action="delete-subscription"]`);n&&(n.disabled=!t),r&&(r.disabled=!t)}updateToggle(){let e=this.shadowRoot;if(!e)return;let t=e.querySelector(`[data-action="toggle-push"]`),n=e.querySelector(`[data-info="subscription-status"]`);t&&t.setAttribute(`aria-checked`,String(this._subscribed)),n&&(n.textContent=this._subscribed?`Enabled`:`Disabled`)}async handleDeleteSubscription(){if(this._selectedId!=null)try{let e=await a(`/push/subscription/${this._selectedId}`);(await fetch(e,{method:`DELETE`})).ok?(c(`Subscription deleted.`),await this.loadSubscriptions()):l(`Failed to delete subscription.`)}catch(e){l(`Delete failed: ${e.message}`)}}async handleProxyUrlChange(n){let i=n.target.value.trim();try{await r(await t(),e.PUSH_PROXY_URL,i),c(`Push proxy URL updated.`),await this.loadSubscriptions()}catch(e){l(`Failed to save proxy URL: ${e.message}`)}}async handleSendNotification(){if(this._selectedId==null)return;let e=this.shadowRoot;if(!e)return;let t=e.querySelector(`[data-input="notification-text"]`)?.value?.trim()||`Test notification from ShadowClaw`,n=this._subscriptions.find(e=>e.id===this._selectedId);if(n)try{let e=await a(`/push/send`),r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({endpoint:n.endpoint,payload:t})});r.ok?c(`Notification sent!`):r.status===410?(l(`Subscription expired and was removed.`),await this.loadSubscriptions()):l(`Failed to send: ${(await r.json().catch(()=>({}))).error||r.statusText}`)}catch(e){l(`Send failed: ${e.message}`)}}async handleToggle(){try{this._subscribed?(await i(),this._subscribed=!1,c(`Push notifications disabled.`)):(await o(),this._subscribed=!0,c(`Push notifications enabled!`)),this.updateToggle(),await this.loadSubscriptions()}catch(e){l(`Push notification error: ${e.message}`)}}async loadProxyConfig(){let r=this.shadowRoot;if(!r)return;let i=await n(await t(),e.PUSH_PROXY_URL),a=r.querySelector(`[data-input="push-proxy-url"]`);a&&(a.value=i||``)}async loadSubscriptions(){if(this.shadowRoot){try{let e=await a(`/push/subscriptions`),t=await fetch(e);if(!t.ok)return;this._subscriptions=await t.json(),this._backendAvailable=!0}catch{this._subscriptions=[],this._backendAvailable=!1}this._selectedId=null,this.renderSubscriptionList(),this.updateActionButtons()}}async refreshState(){try{let e=await s();this._subscribed=!!e,this.updateToggle()}catch{this._subscribed=!1,this.updateToggle()}}};customElements.define(`shadow-claw-notifications`,g);export{g as ShadowClawNotifications};
253
+ `,`text/html`),m=p.querySelector(`template`);let h=[];h=m?Array.from(m.content.children):Array.from(p.head.children).concat(Array.from(p.body.children));var g=h,_=class extends d{static styles=f;static template=g;_backendAvailable=!0;_selectedId=null;_subscribed=!1;_subscriptions=[];constructor(){super()}async connectedCallback(){if(!this.shadowRoot)throw Error(`shadowRoot not found`);await this.refreshState(),await this.loadProxyConfig(),await this.loadSubscriptions(),this.bindEventListeners()}bindEventListeners(){let e=this.shadowRoot;e&&(e.querySelector(`[data-action="toggle-push"]`)?.addEventListener(`click`,()=>this.handleToggle()),e.querySelector(`[data-action="send-notification"]`)?.addEventListener(`click`,()=>this.handleSendNotification()),e.querySelector(`[data-action="delete-subscription"]`)?.addEventListener(`click`,()=>this.handleDeleteSubscription()),e.querySelector(`[data-action="refresh-subscriptions"]`)?.addEventListener(`click`,()=>this.loadSubscriptions()),e.querySelector(`[data-input="push-proxy-url"]`)?.addEventListener(`change`,e=>this.handleProxyUrlChange(e)))}renderSubscriptionList(){let e=this.shadowRoot;if(!e)return;let t=e.querySelector(`[data-info="subscription-list"]`);if(t){if(t.replaceChildren(),this._subscriptions.length===0){let e=this._backendAvailable?`No subscriptions stored.`:`⚠️ Backend services unavailable (push notification server is not running).`,n=document.createElement(`shadow-claw-empty-state`);n.setAttribute(`compact`,``),n.setAttribute(`message`,e),t.append(n);return}this._subscriptions.forEach(e=>{let n=`#${e.id}`,r=e.endpoint.length>60?`…${e.endpoint.slice(-56)}`:e.endpoint,i=e.created_at||``,a=document.createElement(`div`);a.className=`subscription-item${this._selectedId===e.id?` selected`:``}`,a.setAttribute(`data-sub-id`,String(e.id)),a.setAttribute(`data-endpoint`,e.endpoint);let o=document.createElement(`span`);o.className=`subscription-id`,o.title=e.endpoint,o.textContent=`${n} ${r}`;let s=document.createElement(`span`);s.className=`subscription-date`,s.textContent=i,a.append(o,s),a.addEventListener(`click`,()=>{this._selectedId=e.id,this.renderSubscriptionList(),this.updateActionButtons()}),t.append(a)})}}updateActionButtons(){let e=this.shadowRoot;if(!e)return;let t=this._selectedId!=null,n=e.querySelector(`[data-action="send-notification"]`),r=e.querySelector(`[data-action="delete-subscription"]`);n&&(n.disabled=!t),r&&(r.disabled=!t)}updateToggle(){let e=this.shadowRoot;if(!e)return;let t=e.querySelector(`[data-action="toggle-push"]`),n=e.querySelector(`[data-info="subscription-status"]`);t&&t.setAttribute(`aria-checked`,String(this._subscribed)),n&&(n.textContent=this._subscribed?`Enabled`:`Disabled`)}async handleDeleteSubscription(){if(this._selectedId!=null)try{let e=await s(`/push/subscription/${this._selectedId}`);(await fetch(e,o(e,{method:`DELETE`}))).ok?(l(`Subscription deleted.`),await this.loadSubscriptions()):u(`Failed to delete subscription.`)}catch(e){u(`Delete failed: ${e.message}`)}}async handleProxyUrlChange(n){let i=n.target.value.trim();try{await r(await t(),e.PUSH_PROXY_URL,i),l(`Push proxy URL updated.`),await this.loadSubscriptions()}catch(e){u(`Failed to save proxy URL: ${e.message}`)}}async handleSendNotification(){if(this._selectedId==null)return;let e=this.shadowRoot;if(!e)return;let t=e.querySelector(`[data-input="notification-text"]`)?.value?.trim()||`Test notification from ShadowClaw`,n=this._subscriptions.find(e=>e.id===this._selectedId);if(n)try{let e=await s(`/push/send`),r=await fetch(e,o(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({endpoint:n.endpoint,payload:t})}));r.ok?l(`Notification sent!`):r.status===410?(u(`Subscription expired and was removed.`),await this.loadSubscriptions()):u(`Failed to send: ${(await r.json().catch(()=>({}))).error||r.statusText}`)}catch(e){u(`Send failed: ${e.message}`)}}async handleToggle(){try{this._subscribed?(await i(),this._subscribed=!1,l(`Push notifications disabled.`)):(await a(),this._subscribed=!0,l(`Push notifications enabled!`)),this.updateToggle(),await this.loadSubscriptions()}catch(e){u(`Push notification error: ${e.message}`)}}async loadProxyConfig(){let r=this.shadowRoot;if(!r)return;let i=await n(await t(),e.PUSH_PROXY_URL),a=r.querySelector(`[data-input="push-proxy-url"]`);a&&(a.value=i||``)}async loadSubscriptions(){if(this.shadowRoot){try{let r=typeof location<`u`&&(location.protocol===`file:`||location.hostname.endsWith(`.github.io`)||location.hostname.endsWith(`.pages.dev`)),i=await n(await t(),e.PUSH_PROXY_URL)||(typeof localStorage<`u`?localStorage.getItem(e.PUSH_PROXY_URL):null);if(r&&!i){this._subscriptions=[],this._backendAvailable=!1,this._selectedId=null,this.renderSubscriptionList(),this.updateActionButtons();return}let a=await s(`/push/subscriptions`),c=await fetch(a,o(a));if(!c.ok){this._subscriptions=[],this._backendAvailable=!1,this._selectedId=null,this.renderSubscriptionList(),this.updateActionButtons();return}this._subscriptions=await c.json(),this._backendAvailable=!0}catch{this._subscriptions=[],this._backendAvailable=!1}this._selectedId=null,this.renderSubscriptionList(),this.updateActionButtons()}}async refreshState(){try{let e=await c();this._subscribed=!!e,this.updateToggle()}catch{this._subscribed=!1,this.updateToggle()}}};customElements.define(`shadow-claw-notifications`,_);export{_ as ShadowClawNotifications};
@@ -1,4 +1,4 @@
1
- import{r as e}from"./config-CrHchneq.js";import{a as t,n,o as r,r as i,s as a,u as o}from"./app-routes-Bs-riIvr.js";import{n as s}from"./txPromise-EBECky1b.js";import{t as c}from"./getConfig-D89uJgo5.js";import{d as l,i as u,l as d,n as f,r as p,s as m,u as h}from"./custom-element-security-NCqQ5lmC.js";import{n as g}from"./toast-60iDlgiH.js";import{_n as _,a as v,bn as y,c as b,mn as x,r as S,s as C,sn as w,t as T}from"./orchestrator-3h9xxHUm.js";import{t as ee}from"./buffer-9oRIc-5Z.js";import{a as te,r as E,t as D}from"./toast-D3gxhZpN.js";import{t as ne}from"./shadow-claw-element-DIrv3P6A.js";import{t as O}from"./effect-BEsuusE8.js";import{t as re}from"./config-value-oBfKgLT4.js";import"./shadow-claw-page-header-action-button-Bmua3mAb.js";import"./shadow-claw-page-header-DMKbkv3s.js";import{n as k,t as ie}from"./markdown-BnpKxSxl.js";import{t as ae}from"./file-viewer-D0eflgt6.js";import{a as A,c as oe,i as se,n as ce,o as le,r as ue,s as de,t as fe}from"./iframe-storage-proxy-B9Zt-vJ2.js";function pe(e,t,n){n&&(n.textContent=`Navigated to page: ${t||e.path}`)}function j(e,t){if(e===t||e===`main`&&t===`br:main`||e===`br:main`&&t===`main`)return!0;if(!e.includes(`:`)&&!t.includes(`:`))return!1;let n=e=>e.trim().replace(/:/g,`-`);return n(e)===n(t)}function M(e,i,a,s=typeof window<`u`?window.location.origin:``){let c=e.trim();if(!c||c.startsWith(`#`))return null;let l=c.split(/[?#]/,1)[0],u=l.replace(/^(?:\.\/)+/u,``),d=[];if(u.startsWith(`files/`)&&d.push(`/${u}`),l.startsWith(`/`)){let e=l.lastIndexOf(`/files/`);e>0&&d.push(l.slice(e)),d.push(l)}for(let e of d){let t=r(e);if(t&&j(t.groupId,a))return t.path}let f=o(c,n(t(a,i)),s||(typeof window<`u`?window.location.origin:``));if(!f||s&&f.origin!==s)return null;let p=r(f.pathname);return!p||!j(p.groupId,a)?null:p.path}function N(e,t,n,r,i=typeof window<`u`?window.location.origin:``){if(!e)return e;let s=i||(typeof window<`u`?window.location.origin:``),c=new DOMParser().parseFromString(e,`text/html`),l=(e,i)=>{let l=Array.from(c.querySelectorAll(e));for(let e of l){let c=(e.getAttribute(i)||``).trim();if(!c||c.startsWith(`#`)||c.startsWith(`javascript:`))continue;let l=o(c,n,s);!l||s&&l.origin!==s||i===`href`&&!(a(l.pathname)||M(c,t,r,s))||e.setAttribute(i,`${l.pathname}${l.search}${l.hash}`)}};return l(`a[href]`,`href`),l(`img[src]`,`src`),l(`audio[src]`,`src`),l(`video[src]`,`src`),l(`source[src]`,`src`),c.body.innerHTML}const me={ALLOWED_URI_REGEXP:/^(?:(?:https?|mailto|ftp|tel|file|blob|data):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i,ADD_TAGS:[`iframe`,`figure`,`figcaption`],CUSTOM_ELEMENT_HANDLING:{tagNameCheck:e=>m(e),attributeNameCheck:()=>!0,allowCustomizedBuiltInElements:!1},ADD_ATTR:[`allow`,`allowfullscreen`,`frameborder`,`scrolling`,`referrerpolicy`,`loading`]};async function he({content:e,filePath:r,searchParams:i=``,groupId:a,origin:o=typeof window<`u`?window.location?.origin:``,sanitizeOptions:s=me,resolveRelativeImagesInHtmlFn:c}){let l=n(t(a,r)),u=N(e,r,l,a,o),m=d(c?await c(u,r,a):u,s),h=crypto.randomUUID().replace(/-/g,``),g=n(`/assets/file-viewer-preview-bridge.js`),_=n(`/assets/iframe-storage-bridge.js`),v=f(),y=p(h),b=typeof document<`u`?document.getElementById(`shadow-claw-site-config`):null,x=b&&b.textContent?`<script id="shadow-claw-site-config" type="application/json">${b.textContent}<\/script>`:``,S=i?`<script nonce="${h}">(function(){try{Object.defineProperty(window.location,"search",{get:function(){return ${JSON.stringify(i)};},configurable:true});}catch(e){}})();<\/script>`:``,C=v.map(e=>`<script type="module" src="${e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`//`)?e:n(e.startsWith(`/`)?e:`/${e.replace(/^pages\/main\//,``)}`)}" nonce="${h}"><\/script>`).join(`
1
+ import{r as e}from"./config-CrHchneq.js";import{a as t,n,o as r,r as i,s as a,u as o}from"./app-routes-Bs-riIvr.js";import{n as s}from"./txPromise-EBECky1b.js";import{t as c}from"./getConfig-D89uJgo5.js";import{d as l,i as u,l as d,n as f,r as p,s as m,u as h}from"./custom-element-security-NCqQ5lmC.js";import{n as g}from"./toast-60iDlgiH.js";import{_n as _,a as v,bn as y,c as b,mn as x,r as S,s as C,sn as w,t as T}from"./orchestrator-tHWrqi_F.js";import{t as ee}from"./buffer-9oRIc-5Z.js";import{a as te,r as E,t as D}from"./toast-D3gxhZpN.js";import{t as ne}from"./shadow-claw-element-DIrv3P6A.js";import{t as O}from"./effect-BEsuusE8.js";import{t as re}from"./config-value-oBfKgLT4.js";import"./shadow-claw-page-header-action-button-Bmua3mAb.js";import"./shadow-claw-page-header-DMKbkv3s.js";import{n as k,t as ie}from"./markdown-SiFq0PTy.js";import{t as ae}from"./file-viewer-BVg3B_JH.js";import{a as A,c as oe,i as se,n as ce,o as le,r as ue,s as de,t as fe}from"./iframe-storage-proxy-B9Zt-vJ2.js";function pe(e,t,n){n&&(n.textContent=`Navigated to page: ${t||e.path}`)}function j(e,t){if(e===t||e===`main`&&t===`br:main`||e===`br:main`&&t===`main`)return!0;if(!e.includes(`:`)&&!t.includes(`:`))return!1;let n=e=>e.trim().replace(/:/g,`-`);return n(e)===n(t)}function M(e,i,a,s=typeof window<`u`?window.location.origin:``){let c=e.trim();if(!c||c.startsWith(`#`))return null;let l=c.split(/[?#]/,1)[0],u=l.replace(/^(?:\.\/)+/u,``),d=[];if(u.startsWith(`files/`)&&d.push(`/${u}`),l.startsWith(`/`)){let e=l.lastIndexOf(`/files/`);e>0&&d.push(l.slice(e)),d.push(l)}for(let e of d){let t=r(e);if(t&&j(t.groupId,a))return t.path}let f=o(c,n(t(a,i)),s||(typeof window<`u`?window.location.origin:``));if(!f||s&&f.origin!==s)return null;let p=r(f.pathname);return!p||!j(p.groupId,a)?null:p.path}function N(e,t,n,r,i=typeof window<`u`?window.location.origin:``){if(!e)return e;let s=i||(typeof window<`u`?window.location.origin:``),c=new DOMParser().parseFromString(e,`text/html`),l=(e,i)=>{let l=Array.from(c.querySelectorAll(e));for(let e of l){let c=(e.getAttribute(i)||``).trim();if(!c||c.startsWith(`#`)||c.startsWith(`javascript:`))continue;let l=o(c,n,s);!l||s&&l.origin!==s||i===`href`&&!(a(l.pathname)||M(c,t,r,s))||e.setAttribute(i,`${l.pathname}${l.search}${l.hash}`)}};return l(`a[href]`,`href`),l(`img[src]`,`src`),l(`audio[src]`,`src`),l(`video[src]`,`src`),l(`source[src]`,`src`),c.body.innerHTML}const me={ALLOWED_URI_REGEXP:/^(?:(?:https?|mailto|ftp|tel|file|blob|data):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i,ADD_TAGS:[`iframe`,`figure`,`figcaption`],CUSTOM_ELEMENT_HANDLING:{tagNameCheck:e=>m(e),attributeNameCheck:()=>!0,allowCustomizedBuiltInElements:!1},ADD_ATTR:[`allow`,`allowfullscreen`,`frameborder`,`scrolling`,`referrerpolicy`,`loading`]};async function he({content:e,filePath:r,searchParams:i=``,groupId:a,origin:o=typeof window<`u`?window.location?.origin:``,sanitizeOptions:s=me,resolveRelativeImagesInHtmlFn:c}){let l=n(t(a,r)),u=N(e,r,l,a,o),m=d(c?await c(u,r,a):u,s),h=crypto.randomUUID().replace(/-/g,``),g=n(`/assets/file-viewer-preview-bridge.js`),_=n(`/assets/iframe-storage-bridge.js`),v=f(),y=p(h),b=typeof document<`u`?document.getElementById(`shadow-claw-site-config`):null,x=b&&b.textContent?`<script id="shadow-claw-site-config" type="application/json">${b.textContent}<\/script>`:``,S=i?`<script nonce="${h}">(function(){try{Object.defineProperty(window.location,"search",{get:function(){return ${JSON.stringify(i)};},configurable:true});}catch(e){}})();<\/script>`:``,C=v.map(e=>`<script type="module" src="${e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`//`)?e:n(e.startsWith(`/`)?e:`/${e.replace(/^pages\/main\//,``)}`)}" nonce="${h}"><\/script>`).join(`
2
2
  `),w=`<link rel="stylesheet" href="${n(`/theme.css`)}">`;return[`<!doctype html>`,`<html class="${de()}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">`,`<meta http-equiv="Content-Security-Policy" content="${y}">`,`<base href="${l}" target="_blank">`,S,x,`<script src="${_}" nonce="${h}"><\/script>`,`<script src="${g}" nonce="${h}"><\/script>`,oe(),w,C,`</head><body>`,m,`</body></html>`].join(``)}function ge(e,t){return t===0?{isPrevDisabled:!0,isNextDisabled:!0}:{isPrevDisabled:e<=0,isNextDisabled:e<0||e>=t-1}}async function _e(e,t,n=e=>T.removeAllPages(e)){return!e||!await t({title:`Remove All Pages`,message:`Remove ALL saved pages from Pages? This cannot be undone!`,confirmLabel:`Remove All`,cancelLabel:`Cancel`})?!1:(await n(e),!0)}const P={setItem:A,deleteItem:ce,clear:fe,getAll:se,getItem:ue,putItem:A};async function F(e,t,n,r=P){switch(e){case`setItem`:await r.setItem(n,String(t.key||``),t.value);return;case`removeItem`:await r.deleteItem(n,String(t.key||``));return;case`clear`:await r.clear(n);return;case`getAllItems`:return await r.getAll(n);case`idb-get`:return await r.getItem(`${n}::idb::${t.dbName}::${t.storeName}`,String(t.key||``));case`idb-getAll`:return await r.getAll(`${n}::idb::${t.dbName}::${t.storeName}`);case`idb-put`:{let e=t.key==null?`__auto_${Date.now()}`:String(t.key);return await r.putItem(`${n}::idb::${t.dbName}::${t.storeName}`,e,t.value),e}case`idb-delete`:await r.deleteItem(`${n}::idb::${t.dbName}::${t.storeName}`,String(t.key||``));return;case`idb-clear`:await r.clear(`${n}::idb::${t.dbName}::${t.storeName}`);return;case`idb-deleteDatabase`:await r.clear(`${n}::idb::${t.dbName}::__default__`);return;case`idb-count`:{let e=await r.getAll(`${n}::idb::${t.dbName}::${t.storeName}`);return Object.keys(e).length}default:throw Error(`Unknown storage proxy method: ${e}`)}}async function I(e,t,n,r,i,a=P){if(t)try{let o=await F(n,r,i,a);e.postMessage({type:`shadow-claw-storage-proxy-result`,requestId:t,result:o??null},`*`)}catch(n){e.postMessage({type:`shadow-claw-storage-proxy-result`,requestId:t,error:n instanceof Error?n.message:String(n)},`*`)}}function ve({root:e,rendered:t,selectedPath:n,onIframeLoad:r}){let i=e.querySelector(`[data-pages-iframe]`);if(i instanceof HTMLIFrameElement)return i;let a=document.createElement(`iframe`);return a.className=`pages__iframe`,a.setAttribute(`data-pages-iframe`,``),a.setAttribute(`title`,n?`Preview: ${n}`:`Page preview`),a.setAttribute(`sandbox`,u()),a.setAttribute(`allow`,`fullscreen`),a.hidden=!0,r&&a.addEventListener(`load`,()=>{r(a.contentWindow)}),t.before(a),a}function L(e){if(typeof e==`string`||typeof e==`number`){let t=parseInt(String(e),10);if(!isNaN(t)&&t>=0)return Math.min(t,86400)}return 0}async function ye(t,n=c){if(!t)return 0;try{return L(await n(t,e.PAGES_AUTO_REFRESH_INTERVAL))}catch{return 0}}function R(e){if(!e)return``;let t=e.groupId;return t===`main`&&(t=`br:main`),`${t}\u0000${e.path}`}function z(e,t=[]){if(!e)return-1;let n=R(e);return t.findIndex(e=>R(e)===n)}function be(e=[]){let t=new Map;return e.forEach(e=>{let n=t.get(e.groupId)||[];n.push(e),t.set(e.groupId,n)}),t}function xe(e,t){if(!t||t.hidden)return!1;let n=e.replace(/^#/,``),r=t.querySelector(`[id="${n}"]`)||t.querySelector(`a[name="${n}"]`);return r?(r.scrollIntoView({behavior:`smooth`,block:`start`}),!0):!1}function Se(e){let t=e.detail;return t&&t.interval!==void 0?L(t.interval):null}function Ce(e,t){return!e||!t||!e.groupId||!e.path||e.path!==t.path?!1:e.groupId===t.groupId||j(e.groupId,t.groupId)}function we(e,t){let n=e.detail;return Ce(n,t)}function B(e,t){let n=[`data-no-nav`,`data-no-swipe`,`data-no-page-nav`,`data-prevent-nav`,`data-prevent-page-nav`,`data-isolate-input`,`data-isolate-navigation`,`data-game-controls`],r=e=>{if(!e||!(e instanceof HTMLElement))return!1;let t=e.tagName.toLowerCase();return!!(t===`input`||t===`textarea`||t===`select`||t===`option`||t===`iframe`||e.classList.contains(`pages__preview-frame`)||e.isContentEditable||e.contentEditable===`true`||e.getAttribute(`contenteditable`)===`true`||e.hasAttribute(`contenteditable`)||e.closest(`[data-pages-list]`)||e.closest(`[data-pages-dropdown]`)||e.closest(`.pages__sidebar`)||e.closest(`.pages__preview-frame`)||e.closest(`iframe`)||n.some(t=>e.closest(`[${t}]`)))};if(t&&r(t))return!0;if(e){let t=typeof e.composedPath==`function`?e.composedPath():[];for(let e of t)if(e instanceof HTMLElement){let t=e.tagName.toLowerCase();if(n.some(t=>e.hasAttribute(t))||t===`input`||t===`textarea`||t===`select`||t===`option`||t===`iframe`||e.classList.contains(`pages__preview-frame`)||e.isContentEditable||e.contentEditable===`true`||e.getAttribute(`contenteditable`)===`true`||e.hasAttribute(`contenteditable`))return!0}if(e.target&&r(e.target))return!0}return!1}function Te(e,t){return t||e.key!==`ArrowLeft`&&e.key!==`ArrowRight`||e.ctrlKey||e.altKey||e.metaKey?null:e.key===`ArrowLeft`?`previous`:`next`}function Ee(e,t,n,r){if(!t)return;let i=n?.activeElement||document.activeElement,a=Te(e,B(e,e.target||null)||B(void 0,i));a&&(e.preventDefault(),r(a))}function De(e,t,n=Date.now()){return e.button!==0||t?{mouseStartX:0,mouseStartY:0,mouseStartTime:0,isMouseDown:!1}:{mouseStartX:e.clientX,mouseStartY:e.clientY,mouseStartTime:n,isMouseDown:!0}}function V(e,t,n,r,i,a=Date.now(),o=50,s=600){let c=n-e,l=r-t,u=a-i;return Math.abs(c)>=o&&Math.abs(c)>Math.abs(l)&&u<=s?c<0?`next`:`previous`:null}function Oe(e,t,n,r,i=Date.now()){return!t.isMouseDown||n||r?null:V(t.mouseStartX,t.mouseStartY,e.clientX,e.clientY,t.mouseStartTime,i)}function ke(e,t,n){if(t===n||t<0||t>=e.length||n<0||n>=e.length)return e;let r=[...e],[i]=r.splice(t,1);return r.splice(n,0,i),r}async function Ae({db:e,currentPages:t,fromIndex:n,toIndex:r,reorderStoreFn:i=(e,t)=>T.reorderPages(e,t)}){if(!e||n===r)return{reordered:!1,reorderedPages:t,movedToFirst:null};let a=ke(t,n,r);if(a===t)return{reordered:!1,reorderedPages:t,movedToFirst:null};await i(e,a);let o=a[r]||null;return{reordered:!0,reorderedPages:a,movedToFirst:r===0?o:null}}function je(e,t,n,r=Date.now()){if(!t.touchStartTime||n)return null;if(e.changedTouches&&e.changedTouches.length===1){let n=e.changedTouches[0].clientX,i=e.changedTouches[0].clientY;return V(t.touchStartX,t.touchStartY,n,i,t.touchStartTime,r)}return null}function Me(e,t,n=Date.now()){return t?{touchStartX:0,touchStartY:0,touchStartTime:0}:e.touches&&e.touches.length===1?{touchStartX:e.touches[0].clientX,touchStartY:e.touches[0].clientY,touchStartTime:n}:null}function Ne(e,t,n){return!e&&t?`render-and-timer`:e&&n?`clear-timer`:`noop`}function Pe(e,t){return!e&&t}function Fe(e){return/\.(html?|xhtml)$/iu.test(e)}function Ie(e){return/\.(md|markdown)$/iu.test(e)}function Le(e){if(!e||typeof e!=`object`)return null;let t=e;return t.type===`shadow-claw-broadcast-result`&&typeof t.channel==`string`?{kind:`broadcast-result`,channel:t.channel,payload:t.payload}:t.type===`shadow-claw-storage-proxy`?{kind:`storage-proxy`,requestId:String(t.requestId||``),method:String(t.method||``),args:t.args&&typeof t.args==`object`?t.args:{}}:t.type===`shadow-claw-swipe`&&typeof t.direction==`string`?{kind:`swipe`,direction:t.direction}:t.type===`shadow-claw-iframe-resize`&&typeof t.height==`number`?{kind:`iframe-resize`,height:t.height}:t.type===`shadow-claw-file-viewer-link`&&typeof t.href==`string`?{kind:`file-viewer-link`,href:t.href}:null}var H=ee();function U(e){return{apng:`image/apng`,avif:`image/avif`,gif:`image/gif`,jpg:`image/jpeg`,jpeg:`image/jpeg`,png:`image/png`,svg:`image/svg+xml`,webp:`image/webp`}[e]??`image/jpeg`}async function Re({db:e,groupId:t,workspacePath:r,readGroupFileBytesFn:i=y,writeGroupFileFn:a=w,fetchFn:o=typeof fetch<`u`?fetch:void 0}){if(e)try{let n=await i(e,t,r),a=U(r.split(`.`).pop()?.toLowerCase()||``),o=new Uint8Array(n.byteLength);return o.set(new Uint8Array(n)),`data:${a};base64,${H.Buffer.from(o).toString(`base64`)}`}catch{}if(!o)return null;try{let i=r.replace(/^\/+/,``),s=[n(`/files/main/${i}`),n(`/static-main/${i}`),n(`/pages/main/${i}`)];for(let n of s)try{let i=await o(typeof window<`u`&&window.location?.origin?new URL(n,window.location.origin).toString():n);if(i.ok){let n=await i.blob();if(e)try{let i=await n.arrayBuffer();await a(e,t,r,new Uint8Array(i))}catch{}if(typeof FileReader<`u`)return await new Promise((e,t)=>{let r=new FileReader;r.onload=()=>e(r.result),r.onerror=t,r.readAsDataURL(n)});let o=await n.arrayBuffer(),s=H.Buffer.from(o).toString(`base64`);return`data:${n.type||U(r.split(`.`).pop()||``)};base64,${s}`}}catch{}}catch{}return null}function W(e){let t=e.querySelector(`[data-pages-iframe]`);t instanceof HTMLIFrameElement&&(t.removeAttribute(`srcdoc`),t.remove())}async function G(e,t=typeof document<`u`?document.querySelector(`shadow-claw`):null,n=te){return t&&typeof t.requestDialog==`function`?await t.requestDialog({mode:`confirm`,...e}):(n(e.message,4500),!1)}async function ze(e,t,n=c){if(!e||typeof e.transaction!=`function`)return!0;try{return re(await n(e,t),!0)}catch{return!0}}function Be(e,t,n=[]){if(e===t||j(e,t))return t;let r=n.find(t=>t.groupId===e);if(r)return r.groupId;let i=n.find(t=>j(e,t.groupId));return i?i.groupId:e||null}function Ve(e,t,n,i=[],a=typeof window<`u`?window.location.origin:``){let o=e.trim();if(!o||o.startsWith(`#`))return null;let s=[],c=o.split(/[?#]/,1)[0];if(/^[a-zA-Z][a-zA-Z\d+.-]*:/u.test(c)||c.startsWith(`//`)){let e;try{e=new URL(c,a||(typeof window<`u`?window.location.origin:``))}catch{return null}if(a&&e.origin!==a)return null;c=e.pathname}let l=c.replace(/^(?:\.\/)+/u,``);if(l.startsWith(`files/`)&&s.push(`/${l}`),c.startsWith(`/`)){let e=c.lastIndexOf(`/files/`);e>0&&s.push(c.slice(e)),s.push(c)}for(let e of s){let t=r(e);if(!t)continue;let a=Be(t.groupId,n,i);if(a)return{groupId:a,path:t.path}}let u=M(o,t,n,a);return u?{groupId:n,path:u}:null}async function He({container:e,groupId:t,filePath:n,groups:r,readImageAsDataUrlFn:i}){let a=Array.from(e.querySelectorAll(`img[src]`));a.length!==0&&await Promise.all(a.map(async e=>{let a=e.getAttribute(`src`)||``;if(!a||/^(?:blob:|data:|#)/u.test(a))return;let o=Ve(a,n,t,r);if(!o)return;let s=await i(o.groupId,o.path);s&&e.setAttribute(`src`,s)}))}function K(e,t,n){return e>0&&!t&&n}function Ue(e){if(!e)return;let t=typeof document<`u`&&document.documentElement.classList.contains(`dark-mode`),n={};if(typeof document<`u`&&typeof getComputedStyle<`u`){let e=getComputedStyle(document.documentElement);for(let t=0;t<e.length;t++){let r=e[t];r.startsWith(`--`)&&(n[r]=e.getPropertyValue(r))}}e.postMessage({type:`shadow-claw-theme-update`,theme:t?`dark`:`light`,customProperties:n},`*`)}function q({root:e,currentOpen:t,force:n}){if(!e)return t;let r=e.querySelector(`[data-pages-dropdown]`),i=r instanceof HTMLDetailsElement&&r.open,a;a=n===void 0?!(i||t):n;let o=e.querySelector(`.pages__sidebar`),s=e.querySelector(`.pages__content`);return o&&o.classList.toggle(`collapsed`,!a),s&&s.classList.toggle(`pages__content--sidebar-collapsed`,!a),r instanceof HTMLDetailsElement&&(a?r.setAttribute(`open`,``):r.removeAttribute(`open`)),a}const J=new CSSStyleSheet;J.replaceSync(`* {
3
3
  box-sizing: border-box;
4
4
  }
@@ -1,4 +1,4 @@
1
- import{r as e}from"./config-CrHchneq.js";import{n as t}from"./txPromise-EBECky1b.js";import{h as n}from"./custom-element-security-NCqQ5lmC.js";import{Z as r,a as i,c as a,ln as o,t as s}from"./orchestrator-3h9xxHUm.js";import{n as c,r as l}from"./crypto-C8c5wMzN.js";import{n as u,r as d,t as f}from"./toast-D3gxhZpN.js";import{t as p}from"./shadow-claw-element-DIrv3P6A.js";import{t as m}from"./config-value-oBfKgLT4.js";import"./shadow-claw-page-header-DMKbkv3s.js";import"./shadow-claw-dialog-BrOwAOdk.js";function h(e){try{return JSON.parse(JSON.stringify(e))}catch{return null}}async function g(t,n){let r=[],i=[];for(let a of t){let t=a.key;if(t===e.STORAGE_HANDLE)continue;if(t===e.GIT_PASSWORD||t===e.API_KEY||t.startsWith(`api_key:`)||t===e.IMESSAGE_API_KEY||t===e.TELEGRAM_BOT_TOKEN){if(n&&typeof a.value==`string`){let e=await c(a.value);e&&i.push({key:t,path:[],value:e})}continue}let o=h(a.value);if(t===e.GIT_ACCOUNTS&&Array.isArray(o))for(let e=0;e<o.length;e+=1){let r=o[e];if(!r||typeof r!=`object`)continue;let a=r.password;if(typeof a==`string`&&a){if(n){let n=await c(a);n&&i.push({key:t,path:[e,`password`],value:n})}delete r.password}}if(t===e.INTEGRATION_CONNECTIONS&&Array.isArray(o))for(let e=0;e<o.length;e+=1){let r=o[e]?.credentialRef,a=r?.encryptedSecret;if(typeof a==`string`&&a){if(n){let n=await c(a);n&&i.push({key:t,path:[e,`credentialRef`,`encryptedSecret`],value:n})}delete r.encryptedSecret}}if(t===e.REMOTE_MCP_CONNECTIONS&&Array.isArray(o))for(let e=0;e<o.length;e+=1){let r=o[e]?.credentialRef,a=r?.encryptedValue;if(typeof a==`string`&&a){if(n){let n=await c(a);n&&i.push({key:t,path:[e,`credentialRef`,`encryptedValue`],value:n})}delete r.encryptedValue}}r.push({key:t,value:o})}return{configEntries:r,plaintextPasswords:i}}function _(e,t,n){if(t.length===0)return n;let r=e;for(let n=0;n<t.length-1;n+=1){let i=t[n];if(typeof i==`number`){if(!Array.isArray(r)||!r[i])return e;r=r[i]}else{if(!r||typeof r!=`object`)return e;let t=r[i];if(!t||typeof t!=`object`)return e;r=t}}let i=t[t.length-1];if(typeof i==`number`){if(!Array.isArray(r))return e;r[i]=n}else{if(!r||typeof r!=`object`)return e;r[i]=n}return e}async function v(e,t){let n=await g(e,t);return{kind:`shadowclaw-settings-backup`,version:1,exportedAt:Date.now(),includePlaintextPasswords:t,configEntries:n.configEntries,plaintextPasswords:t?n.plaintextPasswords:void 0}}async function y(e,t){let n=await v(e,t);return new Blob([JSON.stringify(n,null,2)],{type:`application/json`})}async function b(e,t,n){let r=await v(t,n);await o(e,JSON.stringify(r,null,2))}async function x(e,t){if(!t.length)return e;let n=e.map(e=>({key:e.key,value:h(e.value)}));for(let e of t){let t=await l(e.value);if(!t)continue;let r=n.find(t=>t.key===e.key);r?r.value=_(r.value,e.path,t):e.path.length===0&&n.push({key:e.key,value:t})}return n}function S(e){let t=JSON.parse(e);if(t?.kind!==`shadowclaw-settings-backup`||t.version!==1||!Array.isArray(t.configEntries))throw Error(`Invalid settings backup file`);let n=Array.isArray(t.plaintextPasswords)?t.plaintextPasswords.filter(e=>e&&typeof e.key==`string`&&Array.isArray(e.path)&&typeof e.value==`string`):[];return{kind:`shadowclaw-settings-backup`,version:1,exportedAt:typeof t.exportedAt==`number`?t.exportedAt:Date.now(),includePlaintextPasswords:!!t.includePlaintextPasswords,configEntries:t.configEntries.filter(e=>e&&typeof e.key==`string`).map(e=>({key:e.key,value:e.value})),plaintextPasswords:n}}const C=new CSSStyleSheet;C.replaceSync(`*,
1
+ import{r as e}from"./config-CrHchneq.js";import{n as t}from"./txPromise-EBECky1b.js";import{h as n}from"./custom-element-security-NCqQ5lmC.js";import{Z as r,a as i,c as a,ln as o,t as s}from"./orchestrator-tHWrqi_F.js";import{n as c,r as l}from"./crypto-C8c5wMzN.js";import{n as u,r as d,t as f}from"./toast-D3gxhZpN.js";import{t as p}from"./shadow-claw-element-DIrv3P6A.js";import{t as m}from"./config-value-oBfKgLT4.js";import"./shadow-claw-page-header-DMKbkv3s.js";import"./shadow-claw-dialog-BrOwAOdk.js";function h(e){try{return JSON.parse(JSON.stringify(e))}catch{return null}}async function g(t,n){let r=[],i=[];for(let a of t){let t=a.key;if(t===e.STORAGE_HANDLE)continue;if(t===e.GIT_PASSWORD||t===e.API_KEY||t.startsWith(`api_key:`)||t===e.IMESSAGE_API_KEY||t===e.TELEGRAM_BOT_TOKEN){if(n&&typeof a.value==`string`){let e=await c(a.value);e&&i.push({key:t,path:[],value:e})}continue}let o=h(a.value);if(t===e.GIT_ACCOUNTS&&Array.isArray(o))for(let e=0;e<o.length;e+=1){let r=o[e];if(!r||typeof r!=`object`)continue;let a=r.password;if(typeof a==`string`&&a){if(n){let n=await c(a);n&&i.push({key:t,path:[e,`password`],value:n})}delete r.password}}if(t===e.INTEGRATION_CONNECTIONS&&Array.isArray(o))for(let e=0;e<o.length;e+=1){let r=o[e]?.credentialRef,a=r?.encryptedSecret;if(typeof a==`string`&&a){if(n){let n=await c(a);n&&i.push({key:t,path:[e,`credentialRef`,`encryptedSecret`],value:n})}delete r.encryptedSecret}}if(t===e.REMOTE_MCP_CONNECTIONS&&Array.isArray(o))for(let e=0;e<o.length;e+=1){let r=o[e]?.credentialRef,a=r?.encryptedValue;if(typeof a==`string`&&a){if(n){let n=await c(a);n&&i.push({key:t,path:[e,`credentialRef`,`encryptedValue`],value:n})}delete r.encryptedValue}}r.push({key:t,value:o})}return{configEntries:r,plaintextPasswords:i}}function _(e,t,n){if(t.length===0)return n;let r=e;for(let n=0;n<t.length-1;n+=1){let i=t[n];if(typeof i==`number`){if(!Array.isArray(r)||!r[i])return e;r=r[i]}else{if(!r||typeof r!=`object`)return e;let t=r[i];if(!t||typeof t!=`object`)return e;r=t}}let i=t[t.length-1];if(typeof i==`number`){if(!Array.isArray(r))return e;r[i]=n}else{if(!r||typeof r!=`object`)return e;r[i]=n}return e}async function v(e,t){let n=await g(e,t);return{kind:`shadowclaw-settings-backup`,version:1,exportedAt:Date.now(),includePlaintextPasswords:t,configEntries:n.configEntries,plaintextPasswords:t?n.plaintextPasswords:void 0}}async function y(e,t){let n=await v(e,t);return new Blob([JSON.stringify(n,null,2)],{type:`application/json`})}async function b(e,t,n){let r=await v(t,n);await o(e,JSON.stringify(r,null,2))}async function x(e,t){if(!t.length)return e;let n=e.map(e=>({key:e.key,value:h(e.value)}));for(let e of t){let t=await l(e.value);if(!t)continue;let r=n.find(t=>t.key===e.key);r?r.value=_(r.value,e.path,t):e.path.length===0&&n.push({key:e.key,value:t})}return n}function S(e){let t=JSON.parse(e);if(t?.kind!==`shadowclaw-settings-backup`||t.version!==1||!Array.isArray(t.configEntries))throw Error(`Invalid settings backup file`);let n=Array.isArray(t.plaintextPasswords)?t.plaintextPasswords.filter(e=>e&&typeof e.key==`string`&&Array.isArray(e.path)&&typeof e.value==`string`):[];return{kind:`shadowclaw-settings-backup`,version:1,exportedAt:typeof t.exportedAt==`number`?t.exportedAt:Date.now(),includePlaintextPasswords:!!t.includePlaintextPasswords,configEntries:t.configEntries.filter(e=>e&&typeof e.key==`string`).map(e=>({key:e.key,value:e.value})),plaintextPasswords:n}}const C=new CSSStyleSheet;C.replaceSync(`*,
2
2
  *::before,
3
3
  *::after {
4
4
  font-family: var(--shadow-claw-font-sans);
@@ -885,7 +885,7 @@ import{r as e}from"./config-CrHchneq.js";import{n as t}from"./txPromise-EBECky1b
885
885
  </div>
886
886
  </div>
887
887
  </template>
888
- `,`text/html`),T=w.querySelector(`template`);let E=[];E=T?Array.from(T.content.children):Array.from(w.head.children).concat(Array.from(w.body.children));var D=E;const O={ai:[()=>import(`./shadow-claw-llm-GWgoVfhI.js`)],environment:[()=>import(`./shadow-claw-networking-qHbP95z9.js`),()=>import(`./shadow-claw-webvm-BCS8ykeP.js`),()=>import(`./shadow-claw-storage-BFynbP0j.js`)],integrations:[()=>import(`./shadow-claw-git-v8S0JjuR.js`),()=>import(`./shadow-claw-accounts-B4sBTQEj.js`),()=>import(`./shadow-claw-mcp-remote-kY4LMFNN.js`),()=>import(`./shadow-claw-control-plane-CX1IGbh9.js`),()=>import(`./shadow-claw-integrations-D7ufpwhX.js`),()=>import(`./shadow-claw-task-server-3BIeb5oZ.js`),()=>import(`./shadow-claw-notifications-YyHOK2Fr.js`)]},k=new Set;async function A(e){if(k.has(e))return;let t=O[e];t&&(k.add(e),await Promise.all(t.map(e=>e())))}const j=`shadow-claw-settings`;var M=class extends p{static styles=C;static template=D;activeTab=`ai`;db=null;orchestrator=null;pendingRestoreFile=null;constructor(){super()}async connectedCallback(){if(!this.shadowRoot)throw Error(`shadowRoot not found`);this.db=await t(),this.orchestrator=s.orchestrator,await this.render()}activateTab(e){!e||this.activeTab===e||(this.activeTab=e,this.applyTabState())}applyTabState(){A(this.activeTab).catch(console.error);let e=this.shadowRoot;e&&(e.querySelectorAll(`[data-tab-target]`).forEach(e=>{let t=e.dataset.tabTarget===this.activeTab;e.classList.toggle(`active`,t),e.setAttribute(`aria-selected`,String(t)),e.tabIndex=t?0:-1}),e.querySelectorAll(`[data-tab-panel]`).forEach(e=>{e.hidden=e.dataset.tabPanel!==this.activeTab}))}bindSettingsActions(){let e=this.shadowRoot;if(!e)return;e.querySelector(`[data-action="backup-settings"]`)?.addEventListener(`click`,()=>this.openBackupDialog());let t=e.querySelector(`.settings__restore-input`);e.querySelector(`[data-action="restore-settings"]`)?.addEventListener(`click`,()=>{t instanceof HTMLInputElement&&(t.value=``,t.click())}),t?.addEventListener(`change`,e=>{let t=e.target;if(!(t instanceof HTMLInputElement))return;let n=t.files?.[0]||null;n&&(this.pendingRestoreFile=n,this.openRestoreDialog(n.name))}),e.querySelector(`[data-action="clear-settings"]`)?.addEventListener(`click`,()=>this.openClearDialog()),e.querySelector(`[data-action="cancel-backup-settings"]`)?.addEventListener(`click`,()=>this.closeDialog(`.settings__backup-dialog`)),e.querySelector(`[data-action="confirm-backup-settings"]`)?.addEventListener(`click`,()=>{this.confirmBackup()}),e.querySelector(`[data-action="cancel-restore-settings"]`)?.addEventListener(`click`,()=>{this.pendingRestoreFile=null,this.closeDialog(`.settings__restore-dialog`)}),e.querySelector(`[data-action="confirm-restore-settings"]`)?.addEventListener(`click`,()=>{this.confirmRestore()}),e.querySelector(`[data-action="cancel-clear-settings"]`)?.addEventListener(`click`,()=>this.closeDialog(`.settings__clear-dialog`)),e.querySelector(`[data-action="confirm-clear-settings"]`)?.addEventListener(`click`,()=>{this.confirmClear()}),e.querySelector(`[data-action="save-assistant-name"]`)?.addEventListener(`click`,()=>this.saveAssistantName()),e.querySelector(`[data-setting="activity-log-disk-logging-toggle"]`)?.addEventListener(`change`,e=>{let t=e.target;t&&this.onActivityLogDiskLoggingToggle(t.checked)}),e.querySelector(`[data-setting="sidebar-hide-pages-toggle"]`)?.addEventListener(`change`,e=>{let t=e.target;t&&this.onSidebarHidePagesToggle(t.checked)}),e.querySelector(`[data-setting="sidebar-hide-chat-toggle"]`)?.addEventListener(`change`,e=>{let t=e.target;t&&this.onSidebarHideChatToggle(t.checked)}),e.querySelector(`[data-setting="sidebar-hide-tasks-toggle"]`)?.addEventListener(`change`,e=>{let t=e.target;t&&this.onSidebarHideTasksToggle(t.checked)}),e.querySelector(`[data-setting="sidebar-hide-files-toggle"]`)?.addEventListener(`change`,e=>{let t=e.target;t&&this.onSidebarHideFilesToggle(t.checked)}),e.querySelector(`[data-setting="chat-split-view-toggle"]`)?.addEventListener(`change`,e=>{let t=e.target;t&&this.onChatSplitViewToggle(t.checked)}),e.querySelector(`[data-setting="pages-auto-refresh-input"]`)?.addEventListener(`change`,e=>{let t=e.target;if(t){let e=parseInt(t.value,10);this.onPagesAutoRefreshInputChange(isNaN(e)?0:e)}}),e.querySelector(`[data-setting="override-prerender-skeleton-toggle"]`)?.addEventListener(`change`,e=>{let t=e.target;t&&this.onOverridePrerenderSkeletonToggle(t.checked)}),e.querySelector(`[data-action="save-dom-allowed-iframe-hosts"]`)?.addEventListener(`click`,()=>{this.saveDomAllowedIframeHosts()})}closeDialog(e){this.getDialog(e)?.close()}getDialog(e){let t=this.shadowRoot;if(!t)return null;let n=t.querySelector(e);return n instanceof HTMLDialogElement?n:null}handleTabKeydown(e,t){let n=this.shadowRoot;if(!n)return;let r=Array.from(n.querySelectorAll(`[data-tab-target]`)),i=r.indexOf(t);if(i<0)return;let a=-1;switch(e.key){case`ArrowRight`:case`ArrowDown`:a=(i+1)%r.length;break;case`ArrowLeft`:case`ArrowUp`:a=(i-1+r.length)%r.length;break;case`Home`:a=0;break;case`End`:a=r.length-1;break;default:return}e.preventDefault();let o=r[a];o.focus(),this.activateTab(o.dataset.tabTarget)}openBackupDialog(){let e=this.shadowRoot?.querySelector(`[data-setting="include-plaintext-passwords"]`);e instanceof HTMLInputElement&&(e.checked=!1),this.showDialog(`.settings__backup-dialog`)}openClearDialog(){this.showDialog(`.settings__clear-dialog`)}openRestoreDialog(e){let t=this.shadowRoot?.querySelector(`[data-info="restore-filename"]`);t instanceof HTMLElement&&(t.textContent=`Selected file: ${e}`),this.showDialog(`.settings__restore-dialog`)}showDialog(e){let t=this.getDialog(e);if(t){if(typeof t.showModal==`function`){t.showModal();return}t.setAttribute(`open`,``)}}async confirmBackup(){if(!this.db){f(`Settings database is unavailable`,5e3);return}let e=this.shadowRoot?.querySelector(`[data-setting="include-plaintext-passwords"]`),t=e instanceof HTMLInputElement&&e.checked;try{if(t){let e=await this.promptForPlaintextBackupHandle();if(!e)return;await b(e,await this.getAllConfigEntries(),t),this.closeDialog(`.settings__backup-dialog`),d(`Settings backup saved`,3e3);return}let e=await y(await this.getAllConfigEntries(),t),n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=`shadowclaw-settings-backup-${Date.now()}.json`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n),this.closeDialog(`.settings__backup-dialog`),d(`Settings backup downloaded`,3e3)}catch(e){f(`Failed to backup settings: ${e instanceof Error?e.message:String(e)}`,6e3)}}async confirmClear(){if(!this.db){f(`Settings database is unavailable`,5e3);return}try{await this.replaceConfigEntries([]),this.closeDialog(`.settings__clear-dialog`),u(`Settings cleared. Reloading app...`,3200),setTimeout(()=>{window.location.reload()},250)}catch(e){f(`Failed to clear settings: ${e instanceof Error?e.message:String(e)}`,6e3)}}async confirmRestore(){if(!this.db){f(`Settings database is unavailable`,5e3);return}let e=this.pendingRestoreFile;if(!e){f(`No backup file selected`,4e3);return}try{let t=S(await e.text()),n=await x(t.configEntries,t.plaintextPasswords||[]);await this.replaceConfigEntries(n),this.pendingRestoreFile=null,this.closeDialog(`.settings__restore-dialog`),d(`Settings restored. Reloading app...`,3200),setTimeout(()=>{window.location.reload()},250)}catch(e){f(`Failed to restore settings: ${e instanceof Error?e.message:String(e)}`,6e3)}}async getAllConfigEntries(){if(!this.db)throw Error(`Database is unavailable`);return await new Promise((e,t)=>{try{let n=this.db?.transaction(`config`,`readonly`);if(!n){t(Error(`Failed to open read transaction`));return}let r=n.objectStore(`config`).getAll();r.onsuccess=()=>{e((Array.isArray(r.result)?r.result:[]).filter(e=>e&&typeof e.key==`string`).map(e=>({key:e.key,value:e.value})))},r.onerror=()=>{t(r.error||Error(`Failed to read settings config`))}}catch(e){t(e)}})}async onActivityLogDiskLoggingToggle(t){if(this.db)try{let{setConfig:n}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await n(this.db,e.ACTIVITY_LOG_DISK_LOGGING_ENABLED,t?`true`:`false`),d(t?`Activity log disk logging enabled`:`Activity log disk logging disabled`,2500)}catch(e){f(`Error saving activity log disk logging setting: `+(e instanceof Error?e.message:String(e)),6e3)}}async onChatSplitViewToggle(t){if(this.db)try{let{setConfig:n}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await n(this.db,e.CHAT_SPLIT_VIEW_ENABLED,t?`true`:`false`),this.dispatchEvent(new CustomEvent(`chat-split-view-change`,{detail:{enabled:t},bubbles:!0,composed:!0})),d(t?`Horizontal Chat split view enabled`:`Horizontal Chat split view disabled`,2500)}catch(e){f(`Error saving Chat split view setting: `+(e instanceof Error?e.message:String(e)),6e3)}}async onOverridePrerenderSkeletonToggle(t){try{a(`shadow-claw-override-prerender-skeleton`,t?`true`:`false`)}catch(e){console.warn(`Unable to save setting to localStorage:`,e)}if(this.db)try{let{setConfig:n}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await n(this.db,e.OVERRIDE_PRERENDER_SKELETON,t?`true`:`false`),d(t?`Pre-rendered content override enabled`:`Pre-rendered content override disabled`,2500)}catch(e){f(`Error saving pre-rendered content override setting: `+(e instanceof Error?e.message:String(e)),6e3)}}async onPagesAutoRefreshInputChange(t){if(!this.db)return;let n=Math.max(0,Math.min(t,86400));try{let{setConfig:t}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await t(this.db,e.PAGES_AUTO_REFRESH_INTERVAL,String(n)),window.dispatchEvent(new CustomEvent(`shadow-claw-pages-auto-refresh-change`,{detail:{interval:n}})),d(n>0?`Pages auto refresh set to ${n}s`:`Pages auto refresh disabled`,2500)}catch(e){f(`Error saving Pages auto refresh interval: `+(e instanceof Error?e.message:String(e)),6e3)}}async onSidebarHideChatToggle(t){if(this.db)try{let{setConfig:n}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await n(this.db,e.SIDEBAR_CHAT_HIDDEN,t?`true`:`false`),this.dispatchEvent(new CustomEvent(`sidebar-chat-visibility-change`,{detail:{hidden:t},bubbles:!0,composed:!0})),d(t?`Chat hidden in sidebar`:`Chat shown in sidebar`,2500)}catch(e){f(`Error saving sidebar Chat visibility: `+(e instanceof Error?e.message:String(e)),6e3)}}async onSidebarHideFilesToggle(t){if(this.db)try{let{setConfig:n}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await n(this.db,e.SIDEBAR_FILES_HIDDEN,t?`true`:`false`),this.dispatchEvent(new CustomEvent(`sidebar-files-visibility-change`,{detail:{hidden:t},bubbles:!0,composed:!0})),d(t?`Files hidden in sidebar`:`Files shown in sidebar`,2500)}catch(e){f(`Error saving sidebar Files visibility: `+(e instanceof Error?e.message:String(e)),6e3)}}async onSidebarHidePagesToggle(t){if(this.db)try{let{setConfig:n}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await n(this.db,e.SIDEBAR_PAGES_HIDDEN,t?`true`:`false`),this.dispatchEvent(new CustomEvent(`sidebar-pages-visibility-change`,{detail:{hidden:t},bubbles:!0,composed:!0})),d(t?`Pages hidden in sidebar`:`Pages shown in sidebar`,2500)}catch(e){f(`Error saving sidebar Pages visibility: `+(e instanceof Error?e.message:String(e)),6e3)}}async onSidebarHideTasksToggle(t){if(this.db)try{let{setConfig:n}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await n(this.db,e.SIDEBAR_TASKS_HIDDEN,t?`true`:`false`),this.dispatchEvent(new CustomEvent(`sidebar-tasks-visibility-change`,{detail:{hidden:t},bubbles:!0,composed:!0})),d(t?`Tasks hidden in sidebar`:`Tasks shown in sidebar`,2500)}catch(e){f(`Error saving sidebar Tasks visibility: `+(e instanceof Error?e.message:String(e)),6e3)}}async populateAssistantSettings(){let t=this.shadowRoot;if(!t||!this.db)return;let n=t.querySelector(`[data-setting="assistant-name-input"]`);if(n){let{getConfig:t}=await import(`./getConfig-D89uJgo5.js`).then(e=>e.n),r=await t(this.db,e.ASSISTANT_NAME),i=this.orchestrator?.assistantName||s.orchestrator?.assistantName;n.value=typeof r==`string`&&r||i||`ShadowClaw`}let{getConfig:r}=await import(`./getConfig-D89uJgo5.js`).then(e=>e.n),o=await r(this.db,e.ACTIVITY_LOG_DISK_LOGGING_ENABLED),c=o===!0||o===`true`||o===1||o===`1`,l=t.querySelector(`[data-setting="activity-log-disk-logging-toggle"]`);l&&(l.checked=c);let u=await r(this.db,e.SIDEBAR_PAGES_HIDDEN),d=u===!0||u===`true`||u===1||u===`1`,f=t.querySelector(`[data-setting="sidebar-hide-pages-toggle"]`);f&&(f.checked=d);let p=await r(this.db,e.SIDEBAR_CHAT_HIDDEN),h=p===!0||p===`true`||p===1||p===`1`,g=t.querySelector(`[data-setting="sidebar-hide-chat-toggle"]`);g&&(g.checked=h);let _=await r(this.db,e.SIDEBAR_TASKS_HIDDEN),v=_===!0||_===`true`||_===1||_===`1`,y=t.querySelector(`[data-setting="sidebar-hide-tasks-toggle"]`);y&&(y.checked=v);let b=await r(this.db,e.SIDEBAR_FILES_HIDDEN),x=b===!0||b===`true`||b===1||b===`1`,S=t.querySelector(`[data-setting="sidebar-hide-files-toggle"]`);S&&(S.checked=x);let C=m(await r(this.db,e.CHAT_SPLIT_VIEW_ENABLED),!1),w=t.querySelector(`[data-setting="chat-split-view-toggle"]`);w&&(w.checked=C);let T=t.querySelector(`[data-setting="pages-auto-refresh-input"]`);if(T){let t=await r(this.db,e.PAGES_AUTO_REFRESH_INTERVAL);if(typeof t==`string`||typeof t==`number`){let e=parseInt(String(t),10);T.value=!isNaN(e)&&e>=0?String(e):`0`}else T.value=`0`}let E=await r(this.db,e.OVERRIDE_PRERENDER_SKELETON),D=null;try{D=i(`shadow-claw-override-prerender-skeleton`)}catch{}let O=!0;if(E==null?D!==null&&(O=D===`true`):O=m(E),O)try{a(`shadow-claw-override-prerender-skeleton`,`true`)}catch{}let k=t.querySelector(`[data-setting="override-prerender-skeleton-toggle"]`);k&&(k.checked=O);let A=t.querySelector(`[data-setting="dom-allowed-iframe-hosts"]`);if(A){let t=await r(this.db,e.ALLOWED_IFRAME_HOST_PATTERNS);if(typeof t==`string`&&t.trim().length>0){A.value=t;let{setAllowedIframeHostPatterns:e}=await import(`./iframe-sanitizer-y2Z1pPwY.js`).then(e=>e.r);e(t)}else{let{DEFAULT_ALLOWED_IFRAME_HOST_PATTERNS:e}=await import(`./iframe-sanitizer-y2Z1pPwY.js`).then(e=>e.r);A.value=e.join(`
888
+ `,`text/html`),T=w.querySelector(`template`);let E=[];E=T?Array.from(T.content.children):Array.from(w.head.children).concat(Array.from(w.body.children));var D=E;const O={ai:[()=>import(`./shadow-claw-llm-CfeDBZKB.js`)],environment:[()=>import(`./shadow-claw-networking-e0EarDVs.js`),()=>import(`./shadow-claw-webvm-CIuSywD_.js`),()=>import(`./shadow-claw-storage-Crs6LY15.js`)],integrations:[()=>import(`./shadow-claw-git-DD7iQRxq.js`),()=>import(`./shadow-claw-accounts-B4sBTQEj.js`),()=>import(`./shadow-claw-mcp-remote-kY4LMFNN.js`),()=>import(`./shadow-claw-control-plane-C0lSxLpW.js`),()=>import(`./shadow-claw-integrations-D7ufpwhX.js`),()=>import(`./shadow-claw-task-server-CKm_Ennl.js`),()=>import(`./shadow-claw-notifications-BkxuDEQI.js`)]},k=new Set;async function A(e){if(k.has(e))return;let t=O[e];t&&(k.add(e),await Promise.all(t.map(e=>e())))}const j=`shadow-claw-settings`;var M=class extends p{static styles=C;static template=D;activeTab=`ai`;db=null;orchestrator=null;pendingRestoreFile=null;constructor(){super()}async connectedCallback(){if(!this.shadowRoot)throw Error(`shadowRoot not found`);this.db=await t(),this.orchestrator=s.orchestrator,await this.render()}activateTab(e){!e||this.activeTab===e||(this.activeTab=e,this.applyTabState())}applyTabState(){A(this.activeTab).catch(console.error);let e=this.shadowRoot;e&&(e.querySelectorAll(`[data-tab-target]`).forEach(e=>{let t=e.dataset.tabTarget===this.activeTab;e.classList.toggle(`active`,t),e.setAttribute(`aria-selected`,String(t)),e.tabIndex=t?0:-1}),e.querySelectorAll(`[data-tab-panel]`).forEach(e=>{e.hidden=e.dataset.tabPanel!==this.activeTab}))}bindSettingsActions(){let e=this.shadowRoot;if(!e)return;e.querySelector(`[data-action="backup-settings"]`)?.addEventListener(`click`,()=>this.openBackupDialog());let t=e.querySelector(`.settings__restore-input`);e.querySelector(`[data-action="restore-settings"]`)?.addEventListener(`click`,()=>{t instanceof HTMLInputElement&&(t.value=``,t.click())}),t?.addEventListener(`change`,e=>{let t=e.target;if(!(t instanceof HTMLInputElement))return;let n=t.files?.[0]||null;n&&(this.pendingRestoreFile=n,this.openRestoreDialog(n.name))}),e.querySelector(`[data-action="clear-settings"]`)?.addEventListener(`click`,()=>this.openClearDialog()),e.querySelector(`[data-action="cancel-backup-settings"]`)?.addEventListener(`click`,()=>this.closeDialog(`.settings__backup-dialog`)),e.querySelector(`[data-action="confirm-backup-settings"]`)?.addEventListener(`click`,()=>{this.confirmBackup()}),e.querySelector(`[data-action="cancel-restore-settings"]`)?.addEventListener(`click`,()=>{this.pendingRestoreFile=null,this.closeDialog(`.settings__restore-dialog`)}),e.querySelector(`[data-action="confirm-restore-settings"]`)?.addEventListener(`click`,()=>{this.confirmRestore()}),e.querySelector(`[data-action="cancel-clear-settings"]`)?.addEventListener(`click`,()=>this.closeDialog(`.settings__clear-dialog`)),e.querySelector(`[data-action="confirm-clear-settings"]`)?.addEventListener(`click`,()=>{this.confirmClear()}),e.querySelector(`[data-action="save-assistant-name"]`)?.addEventListener(`click`,()=>this.saveAssistantName()),e.querySelector(`[data-setting="activity-log-disk-logging-toggle"]`)?.addEventListener(`change`,e=>{let t=e.target;t&&this.onActivityLogDiskLoggingToggle(t.checked)}),e.querySelector(`[data-setting="sidebar-hide-pages-toggle"]`)?.addEventListener(`change`,e=>{let t=e.target;t&&this.onSidebarHidePagesToggle(t.checked)}),e.querySelector(`[data-setting="sidebar-hide-chat-toggle"]`)?.addEventListener(`change`,e=>{let t=e.target;t&&this.onSidebarHideChatToggle(t.checked)}),e.querySelector(`[data-setting="sidebar-hide-tasks-toggle"]`)?.addEventListener(`change`,e=>{let t=e.target;t&&this.onSidebarHideTasksToggle(t.checked)}),e.querySelector(`[data-setting="sidebar-hide-files-toggle"]`)?.addEventListener(`change`,e=>{let t=e.target;t&&this.onSidebarHideFilesToggle(t.checked)}),e.querySelector(`[data-setting="chat-split-view-toggle"]`)?.addEventListener(`change`,e=>{let t=e.target;t&&this.onChatSplitViewToggle(t.checked)}),e.querySelector(`[data-setting="pages-auto-refresh-input"]`)?.addEventListener(`change`,e=>{let t=e.target;if(t){let e=parseInt(t.value,10);this.onPagesAutoRefreshInputChange(isNaN(e)?0:e)}}),e.querySelector(`[data-setting="override-prerender-skeleton-toggle"]`)?.addEventListener(`change`,e=>{let t=e.target;t&&this.onOverridePrerenderSkeletonToggle(t.checked)}),e.querySelector(`[data-action="save-dom-allowed-iframe-hosts"]`)?.addEventListener(`click`,()=>{this.saveDomAllowedIframeHosts()})}closeDialog(e){this.getDialog(e)?.close()}getDialog(e){let t=this.shadowRoot;if(!t)return null;let n=t.querySelector(e);return n instanceof HTMLDialogElement?n:null}handleTabKeydown(e,t){let n=this.shadowRoot;if(!n)return;let r=Array.from(n.querySelectorAll(`[data-tab-target]`)),i=r.indexOf(t);if(i<0)return;let a=-1;switch(e.key){case`ArrowRight`:case`ArrowDown`:a=(i+1)%r.length;break;case`ArrowLeft`:case`ArrowUp`:a=(i-1+r.length)%r.length;break;case`Home`:a=0;break;case`End`:a=r.length-1;break;default:return}e.preventDefault();let o=r[a];o.focus(),this.activateTab(o.dataset.tabTarget)}openBackupDialog(){let e=this.shadowRoot?.querySelector(`[data-setting="include-plaintext-passwords"]`);e instanceof HTMLInputElement&&(e.checked=!1),this.showDialog(`.settings__backup-dialog`)}openClearDialog(){this.showDialog(`.settings__clear-dialog`)}openRestoreDialog(e){let t=this.shadowRoot?.querySelector(`[data-info="restore-filename"]`);t instanceof HTMLElement&&(t.textContent=`Selected file: ${e}`),this.showDialog(`.settings__restore-dialog`)}showDialog(e){let t=this.getDialog(e);if(t){if(typeof t.showModal==`function`){t.showModal();return}t.setAttribute(`open`,``)}}async confirmBackup(){if(!this.db){f(`Settings database is unavailable`,5e3);return}let e=this.shadowRoot?.querySelector(`[data-setting="include-plaintext-passwords"]`),t=e instanceof HTMLInputElement&&e.checked;try{if(t){let e=await this.promptForPlaintextBackupHandle();if(!e)return;await b(e,await this.getAllConfigEntries(),t),this.closeDialog(`.settings__backup-dialog`),d(`Settings backup saved`,3e3);return}let e=await y(await this.getAllConfigEntries(),t),n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=`shadowclaw-settings-backup-${Date.now()}.json`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n),this.closeDialog(`.settings__backup-dialog`),d(`Settings backup downloaded`,3e3)}catch(e){f(`Failed to backup settings: ${e instanceof Error?e.message:String(e)}`,6e3)}}async confirmClear(){if(!this.db){f(`Settings database is unavailable`,5e3);return}try{await this.replaceConfigEntries([]),this.closeDialog(`.settings__clear-dialog`),u(`Settings cleared. Reloading app...`,3200),setTimeout(()=>{window.location.reload()},250)}catch(e){f(`Failed to clear settings: ${e instanceof Error?e.message:String(e)}`,6e3)}}async confirmRestore(){if(!this.db){f(`Settings database is unavailable`,5e3);return}let e=this.pendingRestoreFile;if(!e){f(`No backup file selected`,4e3);return}try{let t=S(await e.text()),n=await x(t.configEntries,t.plaintextPasswords||[]);await this.replaceConfigEntries(n),this.pendingRestoreFile=null,this.closeDialog(`.settings__restore-dialog`),d(`Settings restored. Reloading app...`,3200),setTimeout(()=>{window.location.reload()},250)}catch(e){f(`Failed to restore settings: ${e instanceof Error?e.message:String(e)}`,6e3)}}async getAllConfigEntries(){if(!this.db)throw Error(`Database is unavailable`);return await new Promise((e,t)=>{try{let n=this.db?.transaction(`config`,`readonly`);if(!n){t(Error(`Failed to open read transaction`));return}let r=n.objectStore(`config`).getAll();r.onsuccess=()=>{e((Array.isArray(r.result)?r.result:[]).filter(e=>e&&typeof e.key==`string`).map(e=>({key:e.key,value:e.value})))},r.onerror=()=>{t(r.error||Error(`Failed to read settings config`))}}catch(e){t(e)}})}async onActivityLogDiskLoggingToggle(t){if(this.db)try{let{setConfig:n}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await n(this.db,e.ACTIVITY_LOG_DISK_LOGGING_ENABLED,t?`true`:`false`),d(t?`Activity log disk logging enabled`:`Activity log disk logging disabled`,2500)}catch(e){f(`Error saving activity log disk logging setting: `+(e instanceof Error?e.message:String(e)),6e3)}}async onChatSplitViewToggle(t){if(this.db)try{let{setConfig:n}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await n(this.db,e.CHAT_SPLIT_VIEW_ENABLED,t?`true`:`false`),this.dispatchEvent(new CustomEvent(`chat-split-view-change`,{detail:{enabled:t},bubbles:!0,composed:!0})),d(t?`Horizontal Chat split view enabled`:`Horizontal Chat split view disabled`,2500)}catch(e){f(`Error saving Chat split view setting: `+(e instanceof Error?e.message:String(e)),6e3)}}async onOverridePrerenderSkeletonToggle(t){try{a(`shadow-claw-override-prerender-skeleton`,t?`true`:`false`)}catch(e){console.warn(`Unable to save setting to localStorage:`,e)}if(this.db)try{let{setConfig:n}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await n(this.db,e.OVERRIDE_PRERENDER_SKELETON,t?`true`:`false`),d(t?`Pre-rendered content override enabled`:`Pre-rendered content override disabled`,2500)}catch(e){f(`Error saving pre-rendered content override setting: `+(e instanceof Error?e.message:String(e)),6e3)}}async onPagesAutoRefreshInputChange(t){if(!this.db)return;let n=Math.max(0,Math.min(t,86400));try{let{setConfig:t}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await t(this.db,e.PAGES_AUTO_REFRESH_INTERVAL,String(n)),window.dispatchEvent(new CustomEvent(`shadow-claw-pages-auto-refresh-change`,{detail:{interval:n}})),d(n>0?`Pages auto refresh set to ${n}s`:`Pages auto refresh disabled`,2500)}catch(e){f(`Error saving Pages auto refresh interval: `+(e instanceof Error?e.message:String(e)),6e3)}}async onSidebarHideChatToggle(t){if(this.db)try{let{setConfig:n}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await n(this.db,e.SIDEBAR_CHAT_HIDDEN,t?`true`:`false`),this.dispatchEvent(new CustomEvent(`sidebar-chat-visibility-change`,{detail:{hidden:t},bubbles:!0,composed:!0})),d(t?`Chat hidden in sidebar`:`Chat shown in sidebar`,2500)}catch(e){f(`Error saving sidebar Chat visibility: `+(e instanceof Error?e.message:String(e)),6e3)}}async onSidebarHideFilesToggle(t){if(this.db)try{let{setConfig:n}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await n(this.db,e.SIDEBAR_FILES_HIDDEN,t?`true`:`false`),this.dispatchEvent(new CustomEvent(`sidebar-files-visibility-change`,{detail:{hidden:t},bubbles:!0,composed:!0})),d(t?`Files hidden in sidebar`:`Files shown in sidebar`,2500)}catch(e){f(`Error saving sidebar Files visibility: `+(e instanceof Error?e.message:String(e)),6e3)}}async onSidebarHidePagesToggle(t){if(this.db)try{let{setConfig:n}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await n(this.db,e.SIDEBAR_PAGES_HIDDEN,t?`true`:`false`),this.dispatchEvent(new CustomEvent(`sidebar-pages-visibility-change`,{detail:{hidden:t},bubbles:!0,composed:!0})),d(t?`Pages hidden in sidebar`:`Pages shown in sidebar`,2500)}catch(e){f(`Error saving sidebar Pages visibility: `+(e instanceof Error?e.message:String(e)),6e3)}}async onSidebarHideTasksToggle(t){if(this.db)try{let{setConfig:n}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await n(this.db,e.SIDEBAR_TASKS_HIDDEN,t?`true`:`false`),this.dispatchEvent(new CustomEvent(`sidebar-tasks-visibility-change`,{detail:{hidden:t},bubbles:!0,composed:!0})),d(t?`Tasks hidden in sidebar`:`Tasks shown in sidebar`,2500)}catch(e){f(`Error saving sidebar Tasks visibility: `+(e instanceof Error?e.message:String(e)),6e3)}}async populateAssistantSettings(){let t=this.shadowRoot;if(!t||!this.db)return;let n=t.querySelector(`[data-setting="assistant-name-input"]`);if(n){let{getConfig:t}=await import(`./getConfig-D89uJgo5.js`).then(e=>e.n),r=await t(this.db,e.ASSISTANT_NAME),i=this.orchestrator?.assistantName||s.orchestrator?.assistantName;n.value=typeof r==`string`&&r||i||`ShadowClaw`}let{getConfig:r}=await import(`./getConfig-D89uJgo5.js`).then(e=>e.n),o=await r(this.db,e.ACTIVITY_LOG_DISK_LOGGING_ENABLED),c=o===!0||o===`true`||o===1||o===`1`,l=t.querySelector(`[data-setting="activity-log-disk-logging-toggle"]`);l&&(l.checked=c);let u=await r(this.db,e.SIDEBAR_PAGES_HIDDEN),d=u===!0||u===`true`||u===1||u===`1`,f=t.querySelector(`[data-setting="sidebar-hide-pages-toggle"]`);f&&(f.checked=d);let p=await r(this.db,e.SIDEBAR_CHAT_HIDDEN),h=p===!0||p===`true`||p===1||p===`1`,g=t.querySelector(`[data-setting="sidebar-hide-chat-toggle"]`);g&&(g.checked=h);let _=await r(this.db,e.SIDEBAR_TASKS_HIDDEN),v=_===!0||_===`true`||_===1||_===`1`,y=t.querySelector(`[data-setting="sidebar-hide-tasks-toggle"]`);y&&(y.checked=v);let b=await r(this.db,e.SIDEBAR_FILES_HIDDEN),x=b===!0||b===`true`||b===1||b===`1`,S=t.querySelector(`[data-setting="sidebar-hide-files-toggle"]`);S&&(S.checked=x);let C=m(await r(this.db,e.CHAT_SPLIT_VIEW_ENABLED),!1),w=t.querySelector(`[data-setting="chat-split-view-toggle"]`);w&&(w.checked=C);let T=t.querySelector(`[data-setting="pages-auto-refresh-input"]`);if(T){let t=await r(this.db,e.PAGES_AUTO_REFRESH_INTERVAL);if(typeof t==`string`||typeof t==`number`){let e=parseInt(String(t),10);T.value=!isNaN(e)&&e>=0?String(e):`0`}else T.value=`0`}let E=await r(this.db,e.OVERRIDE_PRERENDER_SKELETON),D=null;try{D=i(`shadow-claw-override-prerender-skeleton`)}catch{}let O=!0;if(E==null?D!==null&&(O=D===`true`):O=m(E),O)try{a(`shadow-claw-override-prerender-skeleton`,`true`)}catch{}let k=t.querySelector(`[data-setting="override-prerender-skeleton-toggle"]`);k&&(k.checked=O);let A=t.querySelector(`[data-setting="dom-allowed-iframe-hosts"]`);if(A){let t=await r(this.db,e.ALLOWED_IFRAME_HOST_PATTERNS);if(typeof t==`string`&&t.trim().length>0){A.value=t;let{setAllowedIframeHostPatterns:e}=await import(`./iframe-sanitizer-y2Z1pPwY.js`).then(e=>e.r);e(t)}else{let{DEFAULT_ALLOWED_IFRAME_HOST_PATTERNS:e}=await import(`./iframe-sanitizer-y2Z1pPwY.js`).then(e=>e.r);A.value=e.join(`
889
889
  `)}}let j=t.querySelector(`[data-setting="markdown-frontmatter-pages-toggle"]`);j&&(j.checked=m(await r(this.db,e.MARKDOWN_FRONTMATTER_PAGES),!0));let M=t.querySelector(`[data-setting="markdown-frontmatter-file-viewer-toggle"]`);M&&(M.checked=m(await r(this.db,e.MARKDOWN_FRONTMATTER_FILE_VIEWER),!0));let N=t.querySelector(`[data-setting="markdown-frontmatter-chat-toggle"]`);N&&(N.checked=m(await r(this.db,e.MARKDOWN_FRONTMATTER_CHAT),!0));let P=t.querySelector(`[data-setting="markdown-frontmatter-tasks-toggle"]`);P&&(P.checked=m(await r(this.db,e.MARKDOWN_FRONTMATTER_TASKS),!0))}async promptForPlaintextBackupHandle(){let e=Reflect.get(globalThis,`showSaveFilePicker`),t=typeof e==`function`?e.bind(globalThis):null;if(!t)throw Error(`Plaintext settings backup requires the File System Access API.`);try{return await t({id:`shadowclaw-settings-backup`,suggestedName:`shadowclaw-settings-backup-${n()}.json`,types:[{description:`JSON Files`,accept:{"application/json":[`.json`]}}]})}catch(e){if(e instanceof Error&&e.name===`AbortError`)return null;throw e}}async render(){let e=this.shadowRoot;if(!e)return;e.querySelector(`[data-action="show-channels-config"]`)?.addEventListener(`click`,()=>{this.dispatchEvent(new CustomEvent(`navigate`,{detail:{page:`channels`},bubbles:!0,composed:!0}))}),e.querySelector(`[data-action="show-tools-config"]`)?.addEventListener(`click`,()=>{this.dispatchEvent(new CustomEvent(`navigate`,{detail:{page:`tools`},bubbles:!0,composed:!0}))}),e.querySelectorAll(`[data-tab-target]`).forEach(e=>{e.addEventListener(`click`,()=>{this.activateTab(e.dataset.tabTarget)}),e.addEventListener(`keydown`,t=>{this.handleTabKeydown(t,e)})}),this.applyTabState(),this.bindSettingsActions();let t=e.querySelector(`[data-info="deployed-revision"]`);t&&(t.textContent=`Deployed revision: ${document.querySelector(`meta[name="revision"]`)?.getAttribute(`content`)?.trim()||`unknown`}`),await this.populateAssistantSettings()}async replaceConfigEntries(e){if(!this.db)throw Error(`Database is unavailable`);await new Promise((t,n)=>{try{let r=this.db?.transaction(`config`,`readwrite`);if(!r){n(Error(`Failed to open write transaction`));return}let i=r.objectStore(`config`);i.clear();for(let t of e)i.put({key:t.key,value:t.value});r.oncomplete=()=>t(),r.onerror=()=>n(r.error||Error(`Failed to update config`)),r.onabort=()=>n(r.error||Error(`Config update aborted`))}catch(e){n(e)}})}async saveAssistantName(){if(!this.db)return;let t=this.shadowRoot;if(!t)return;let n=t.querySelector(`[data-setting="assistant-name-input"]`);if(!n)return;let i=n.value.trim();if(!i){let{showWarning:e}=await import(`./toast-D3gxhZpN.js`).then(e=>e.o);e(`Please enter a name`,3e3);return}a(`assistantName`,i);try{let t=this.orchestrator||s.orchestrator;if(t)this.orchestrator=t,await r(t,this.db,i);else{let{setConfig:t}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n);await t(this.db,e.ASSISTANT_NAME,i)}}catch(e){console.warn(`Could not update orchestrator:`,e)}d(`Assistant name saved`,3e3)}async saveDomAllowedIframeHosts(){let t=this.shadowRoot;if(!t||!this.db)return;let n=t.querySelector(`[data-setting="dom-allowed-iframe-hosts"]`);if(!n)return;let r=n.value.split(`
890
890
  `).map(e=>e.trim()).filter(e=>e.length>0),i=t.querySelector(`[data-setting="markdown-frontmatter-pages-toggle"]`),a=t.querySelector(`[data-setting="markdown-frontmatter-file-viewer-toggle"]`),o=t.querySelector(`[data-setting="markdown-frontmatter-chat-toggle"]`),s=t.querySelector(`[data-setting="markdown-frontmatter-tasks-toggle"]`);try{let{setConfig:t}=await import(`./setConfig-DFMYnYLE.js`).then(e=>e.n),n=r.join(`
891
891
  `);await t(this.db,e.ALLOWED_IFRAME_HOST_PATTERNS,n),await t(this.db,e.MARKDOWN_FRONTMATTER_PAGES,String(i?.checked??!0)),await t(this.db,e.MARKDOWN_FRONTMATTER_FILE_VIEWER,String(a?.checked??!0)),await t(this.db,e.MARKDOWN_FRONTMATTER_CHAT,String(o?.checked??!0)),await t(this.db,e.MARKDOWN_FRONTMATTER_TASKS,String(s?.checked??!0));let{setAllowedIframeHostPatterns:c}=await import(`./iframe-sanitizer-y2Z1pPwY.js`).then(e=>e.r);c(r),d(`DOM iframe embed settings saved`,2500)}catch(e){f(`Error saving DOM iframe embed settings: `+(e instanceof Error?e.message:String(e)),6e3)}}};customElements.get(j)||customElements.define(j,M);export{M as ShadowClawSettings};
@@ -1,4 +1,4 @@
1
- import{r as e}from"./config-CrHchneq.js";import{n as t}from"./txPromise-EBECky1b.js";import{t as n}from"./getConfig-D89uJgo5.js";import{u as r}from"./custom-element-security-NCqQ5lmC.js";import{en as i,t as a,tn as o}from"./orchestrator-3h9xxHUm.js";import{c as s}from"./getGroupDir-P1h9wl6S.js";import{t as c}from"./setConfig-DFMYnYLE.js";import{a as l,r as u,t as d}from"./toast-D3gxhZpN.js";import{t as f}from"./shadow-claw-element-DIrv3P6A.js";import{t as p}from"./effect-BEsuusE8.js";import{t as m}from"./config-value-oBfKgLT4.js";async function h(){try{if(typeof navigator<`u`&&navigator.storage&&navigator.storage.estimate){let e=await navigator.storage.estimate();return{usage:e.usage||0,quota:e.quota||0}}}catch(e){console.warn(`Failed to get storage estimate:`,e)}return{usage:0,quota:0}}async function g(){try{if(typeof navigator<`u`&&navigator.storage&&navigator.storage.persisted)return await navigator.storage.persisted()}catch(e){console.warn(`Failed to check persistent storage:`,e)}return!1}async function _(){try{if(typeof navigator<`u`&&navigator.storage&&navigator.storage.persist)return await navigator.storage.persist()}catch(e){console.warn(`Failed to request persistent storage:`,e)}return!1}async function v(t){let n=Reflect.get(globalThis,`showDirectoryPicker`),r=typeof n==`function`?n.bind(globalThis):null;if(!r)throw Error(`Local folder picker is unavailable in this browser/context.`);try{let n=await r({mode:`readwrite`,id:`shadowclaw-storage`});return await c(t,e.STORAGE_HANDLE,n),await o(t),await i(t),!0}catch(e){if(e instanceof Error&&e.name===`AbortError`)return!1;throw e}}const y=new CSSStyleSheet;y.replaceSync(`*,
1
+ import{r as e}from"./config-CrHchneq.js";import{n as t}from"./txPromise-EBECky1b.js";import{t as n}from"./getConfig-D89uJgo5.js";import{u as r}from"./custom-element-security-NCqQ5lmC.js";import{en as i,t as a,tn as o}from"./orchestrator-tHWrqi_F.js";import{c as s}from"./getGroupDir-P1h9wl6S.js";import{t as c}from"./setConfig-DFMYnYLE.js";import{a as l,r as u,t as d}from"./toast-D3gxhZpN.js";import{t as f}from"./shadow-claw-element-DIrv3P6A.js";import{t as p}from"./effect-BEsuusE8.js";import{t as m}from"./config-value-oBfKgLT4.js";async function h(){try{if(typeof navigator<`u`&&navigator.storage&&navigator.storage.estimate){let e=await navigator.storage.estimate();return{usage:e.usage||0,quota:e.quota||0}}}catch(e){console.warn(`Failed to get storage estimate:`,e)}return{usage:0,quota:0}}async function g(){try{if(typeof navigator<`u`&&navigator.storage&&navigator.storage.persisted)return await navigator.storage.persisted()}catch(e){console.warn(`Failed to check persistent storage:`,e)}return!1}async function _(){try{if(typeof navigator<`u`&&navigator.storage&&navigator.storage.persist)return await navigator.storage.persist()}catch(e){console.warn(`Failed to request persistent storage:`,e)}return!1}async function v(t){let n=Reflect.get(globalThis,`showDirectoryPicker`),r=typeof n==`function`?n.bind(globalThis):null;if(!r)throw Error(`Local folder picker is unavailable in this browser/context.`);try{let n=await r({mode:`readwrite`,id:`shadowclaw-storage`});return await c(t,e.STORAGE_HANDLE,n),await o(t),await i(t),!0}catch(e){if(e instanceof Error&&e.name===`AbortError`)return!1;throw e}}const y=new CSSStyleSheet;y.replaceSync(`*,
2
2
  *::before,
3
3
  *::after {
4
4
  font-family: var(--shadow-claw-font-sans);
@@ -1,4 +1,4 @@
1
- import{n as e}from"./txPromise-EBECky1b.js";import{b as t,t as n,y as r}from"./orchestrator-3h9xxHUm.js";import{r as i,t as a}from"./toast-D3gxhZpN.js";import{t as o}from"./shadow-claw-element-DIrv3P6A.js";import{t as s}from"./effect-BEsuusE8.js";const c=new CSSStyleSheet;c.replaceSync(`*,
1
+ import{n as e}from"./txPromise-EBECky1b.js";import{b as t,t as n,y as r}from"./orchestrator-tHWrqi_F.js";import{r as i,t as a}from"./toast-D3gxhZpN.js";import{t as o}from"./shadow-claw-element-DIrv3P6A.js";import{t as s}from"./effect-BEsuusE8.js";const c=new CSSStyleSheet;c.replaceSync(`*,
2
2
  *::before,
3
3
  *::after {
4
4
  font-family: var(--shadow-claw-font-sans);
@@ -1,4 +1,4 @@
1
- import{r as e}from"./config-CrHchneq.js";import{n as t}from"./txPromise-EBECky1b.js";import{t as n}from"./getConfig-D89uJgo5.js";import{m as r,u as i}from"./custom-element-security-NCqQ5lmC.js";import{t as a}from"./orchestrator-3h9xxHUm.js";import{n as o,r as s,t as c}from"./toast-D3gxhZpN.js";import{t as l}from"./shadow-claw-element-DIrv3P6A.js";import"./shadow-claw-empty-state-obMInUIf.js";import{t as u}from"./effect-BEsuusE8.js";import{t as d}from"./config-value-oBfKgLT4.js";import"./shadow-claw-page-header-action-button-Bmua3mAb.js";import"./shadow-claw-page-header-DMKbkv3s.js";import{t as f}from"./markdown-BnpKxSxl.js";import{t as p}from"./file-viewer-D0eflgt6.js";import"./shadow-claw-dialog-BrOwAOdk.js";const m=new CSSStyleSheet;m.replaceSync(`*,
1
+ import{r as e}from"./config-CrHchneq.js";import{n as t}from"./txPromise-EBECky1b.js";import{t as n}from"./getConfig-D89uJgo5.js";import{m as r,u as i}from"./custom-element-security-NCqQ5lmC.js";import{t as a}from"./orchestrator-tHWrqi_F.js";import{n as o,r as s,t as c}from"./toast-D3gxhZpN.js";import{t as l}from"./shadow-claw-element-DIrv3P6A.js";import"./shadow-claw-empty-state-obMInUIf.js";import{t as u}from"./effect-BEsuusE8.js";import{t as d}from"./config-value-oBfKgLT4.js";import"./shadow-claw-page-header-action-button-Bmua3mAb.js";import"./shadow-claw-page-header-DMKbkv3s.js";import{t as f}from"./markdown-SiFq0PTy.js";import{t as p}from"./file-viewer-BVg3B_JH.js";import"./shadow-claw-dialog-BrOwAOdk.js";const m=new CSSStyleSheet;m.replaceSync(`*,
2
2
  *::before,
3
3
  *::after {
4
4
  font-family: var(--shadow-claw-font-sans);
@@ -1,4 +1,4 @@
1
- import{D as e,E as t,T as n,t as r}from"./orchestrator-3h9xxHUm.js";import{t as i}from"./shadow-claw-element-DIrv3P6A.js";function a(e){if(!e)return``;let t=e.split(`
1
+ import{D as e,E as t,T as n,t as r}from"./orchestrator-tHWrqi_F.js";import{t as i}from"./shadow-claw-element-DIrv3P6A.js";function a(e){if(!e)return``;let t=e.split(`
2
2
  `);for(let e=t.length-1;e>=0;--e){let n=t[e]||``;if(/[#$](?:\s|$)/.test(n))return n}return``}function o(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=12}function s(e,t){let n=e[t+1];if(n===void 0)return{action:`ignore`,nextIndex:t+1,incomplete:!0};if(n===`[`){let n=t+2;for(;n<e.length;){let t=e.charCodeAt(n);if(t>=64&&t<=126){let t=e[n];return t===`J`?{action:`clear-screen`,nextIndex:n+1}:t===`K`?{action:`clear-line`,nextIndex:n+1}:{action:`ignore`,nextIndex:n+1}}n+=1}return{action:`ignore`,nextIndex:e.length,incomplete:!0}}if(n===`]`){let n=t+2;for(;n<e.length;){let t=e[n];if(t===`\x07`)return{action:`ignore`,nextIndex:n+1};if(t===`\x1B`&&e[n+1]===`\\`)return{action:`ignore`,nextIndex:n+2};n+=1}return{action:`ignore`,nextIndex:e.length,incomplete:!0}}return{action:`ignore`,nextIndex:Math.min(t+2,e.length)}}function c(e){return e.replace(/(?:^|\n)[^\n]*mkdir -p \/home\/user 2>&1; echo "?__BCDONE_\d+__\$\?"?[^\n]*(?:\n|$)/g,`
3
3
  `).replace(/(?:^|\n)\s*__BCDONE_\d+__(?:\d+|\$\?)?\s*(?:\n|$)/g,`
4
4
  `).replace(/^\n+(?=\S)/,``)}function l(e,t,n=``,r){let i=r?.respectEraseSequences??!0,a=n+t,o=e;for(let e=0;e<a.length;e++){let t=a[e];if(t===`\x1B`){let t=s(a,e);if(t.incomplete)return{text:o,pending:a.slice(e)};if(t.action===`clear-screen`&&i&&(o=``),t.action===`clear-line`&&i){let e=o.lastIndexOf(`
@@ -1,4 +1,4 @@
1
- import{A as e,F as t}from"./config-CrHchneq.js";import{n}from"./txPromise-EBECky1b.js";import{gn as r,mn as i,t as a}from"./orchestrator-3h9xxHUm.js";import{t as o}from"./ulid-BY7rQVLN.js";import{i as s,n as c,t as l}from"./syncWebMcpRegistration-B_M2fCjH.js";import{n as u,r as d,t as f}from"./toast-D3gxhZpN.js";import{t as p}from"./shadow-claw-element-DIrv3P6A.js";import{t as m}from"./effect-BEsuusE8.js";import"./shadow-claw-page-header-action-button-Bmua3mAb.js";import"./shadow-claw-page-header-DMKbkv3s.js";import"./shadow-claw-dialog-BrOwAOdk.js";const h=new CSSStyleSheet;h.replaceSync(`*,
1
+ import{A as e,F as t}from"./config-CrHchneq.js";import{n}from"./txPromise-EBECky1b.js";import{gn as r,mn as i,t as a}from"./orchestrator-tHWrqi_F.js";import{t as o}from"./ulid-BY7rQVLN.js";import{i as s,n as c,t as l}from"./syncWebMcpRegistration-DzC80wVG.js";import{n as u,r as d,t as f}from"./toast-D3gxhZpN.js";import{t as p}from"./shadow-claw-element-DIrv3P6A.js";import{t as m}from"./effect-BEsuusE8.js";import"./shadow-claw-page-header-action-button-Bmua3mAb.js";import"./shadow-claw-page-header-DMKbkv3s.js";import"./shadow-claw-dialog-BrOwAOdk.js";const h=new CSSStyleSheet;h.replaceSync(`*,
2
2
  *::before,
3
3
  *::after {
4
4
  font-family: var(--shadow-claw-font-sans);
@@ -1,4 +1,4 @@
1
- import{f as e,n as t,r as n}from"./config-CrHchneq.js";import{n as r}from"./txPromise-EBECky1b.js";import{t as i}from"./getConfig-D89uJgo5.js";import{A as a,O as o,S as s,k as c,t as l}from"./orchestrator-3h9xxHUm.js";import{a as u,r as d,t as f}from"./toast-D3gxhZpN.js";import{t as p}from"./shadow-claw-element-DIrv3P6A.js";import{t as m}from"./effect-BEsuusE8.js";const h=new CSSStyleSheet;h.replaceSync(`*,
1
+ import{f as e,n as t,r as n}from"./config-CrHchneq.js";import{n as r}from"./txPromise-EBECky1b.js";import{t as i}from"./getConfig-D89uJgo5.js";import{A as a,O as o,S as s,k as c,t as l}from"./orchestrator-tHWrqi_F.js";import{a as u,r as d,t as f}from"./toast-D3gxhZpN.js";import{t as p}from"./shadow-claw-element-DIrv3P6A.js";import{t as m}from"./effect-BEsuusE8.js";const h=new CSSStyleSheet;h.replaceSync(`*,
2
2
  *::before,
3
3
  *::after {
4
4
  font-family: var(--shadow-claw-font-sans);
@@ -1,2 +1,2 @@
1
- import{o as e,r as t}from"./config-CrHchneq.js";import{Lt as n,M as r,gn as i,mn as a,t as o}from"./orchestrator-3h9xxHUm.js";import{t as s}from"./setConfig-DFMYnYLE.js";import{t as c}from"./effect-BEsuusE8.js";const l={name:`activate_skill`,description:`Load the full instructions for a workspace skill when its description matches the current task.`,input_schema:{type:`object`,properties:{name:{type:`string`,description:`The exact skill name from the available skills catalog.`}},required:[`name`]}};function u(e,t){let n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let r=0;r<n;r++)if(!u(e[r],t[r]))return!1;return!0}if(n===`object`){if(!e||!t)return e===t;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!u(e[r],t[r]))return!1;return!0}return e===t}function d(e){return encodeURI(f(e))}function f(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}const p={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},m={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},h={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};let g=typeof self<`u`&&self.location&&self.location.origin!==`null`?new URL(self.location.origin+self.location.pathname+location.search):new URL(`https://github.com/cfworker`);function _(e,t=Object.create(null),n=g,r=``){if(e&&typeof e==`object`&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let a=new URL(i,n.href);a.hash.length>1?t[a.href]=e:(a.hash=``,r===``?n=a:_(e,t,n))}}else if(e!==!0&&e!==!1)return t;let i=n.href+(r?`#`+r:``);if(t[i]!==void 0)throw Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}if(e.$anchor){let r=new URL(`#`+e.$anchor,n.href);t[r.href]=e}for(let i in e){if(h[i])continue;let a=`${r}/${d(i)}`,o=e[i];if(Array.isArray(o)){if(p[i]){let e=o.length;for(let r=0;r<e;r++)_(o[r],t,n,`${a}/${r}`)}}else if(m[i])for(let e in o)_(o[e],t,n,`${a}/${d(e)}`);else _(o,t,n,a)}return t}const v=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,y=[0,31,28,31,30,31,30,31,31,30,31,30,31],ee=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,te=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,b=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,x=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,ne=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,re=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,ie=/^(?:\/(?:[^~/]|~0|~1)*)*$/,ae=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,S=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,C=e=>{if(e[0]===`"`)return!1;let[t,n,...r]=e.split(`@`);return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]===`.`||t.endsWith(`.`)||t.includes(`..`)||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(`.`).every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},w=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,oe=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,se=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function T(e){return e.test.bind(e)}const ce={date:le,time:D.bind(void 0,!1),"date-time":k,duration:se,uri:ue,"uri-reference":T(b),"uri-template":T(x),url:T(ne),email:C,hostname:T(te),ipv4:T(w),ipv6:T(oe),regex:fe,uuid:T(re),"json-pointer":T(ie),"json-pointer-uri-fragment":T(ae),"relative-json-pointer":T(S)};function E(e){return e%4==0&&(e%100!=0||e%400==0)}function le(e){let t=e.match(v);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&E(n)?29:y[r])}function D(e,t){let n=t.match(ee);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=!!n[5];return(r<=23&&i<=59&&a<=59||r==23&&i==59&&a==60)&&(!e||o)}const O=/t|\s/i;function k(e){let t=e.split(O);return t.length==2&&le(t[0])&&D(!0,t[1])}const A=/\/|:/,j=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function ue(e){return A.test(e)&&j.test(e)}const de=/[^\\]\\Z/;function fe(e){if(de.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}function pe(e){let t=0,n=e.length,r=0,i;for(;r<n;)t++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<n&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return t}function M(e,t,n=`2019-09`,r=_(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,f;switch(l){case`boolean`:case`number`:case`string`:f=l;break;case`object`:f=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:p,$recursiveRef:m,$recursiveAnchor:h,type:g,const:v,enum:y,required:ee,not:te,anyOf:b,allOf:x,oneOf:ne,if:re,then:ie,else:ae,format:S,properties:C,patternProperties:w,additionalProperties:oe,unevaluatedProperties:se,minProperties:T,maxProperties:E,propertyNames:le,dependentRequired:D,dependentSchemas:O,dependencies:k,prefixItems:A,items:j,additionalItems:ue,unevaluatedItems:de,contains:fe,minContains:N,maxContains:P,minItems:F,maxItems:I,uniqueItems:L,minimum:R,maximum:z,exclusiveMinimum:B,exclusiveMaximum:V,multipleOf:H,minLength:U,maxLength:W,pattern:me,__absolute_ref__:G,__absolute_recursive_ref__:he}=t,K=[];if(h===!0&&a===null&&(a=t),m===`#`){let l=a===null?r[he]:a,u=`${s}/$recursiveRef`,d=M(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||K.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(p!==void 0){let t=r[G||p];if(t===void 0){let e=`Unresolved $ref "${p}".`;throw G&&G!==p&&(e+=` Absolute URI "${G}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
1
+ import{o as e,r as t}from"./config-CrHchneq.js";import{Lt as n,M as r,gn as i,mn as a,t as o}from"./orchestrator-tHWrqi_F.js";import{t as s}from"./setConfig-DFMYnYLE.js";import{t as c}from"./effect-BEsuusE8.js";const l={name:`activate_skill`,description:`Load the full instructions for a workspace skill when its description matches the current task.`,input_schema:{type:`object`,properties:{name:{type:`string`,description:`The exact skill name from the available skills catalog.`}},required:[`name`]}};function u(e,t){let n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let r=0;r<n;r++)if(!u(e[r],t[r]))return!1;return!0}if(n===`object`){if(!e||!t)return e===t;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!u(e[r],t[r]))return!1;return!0}return e===t}function d(e){return encodeURI(f(e))}function f(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}const p={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},m={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},h={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};let g=typeof self<`u`&&self.location&&self.location.origin!==`null`?new URL(self.location.origin+self.location.pathname+location.search):new URL(`https://github.com/cfworker`);function _(e,t=Object.create(null),n=g,r=``){if(e&&typeof e==`object`&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let a=new URL(i,n.href);a.hash.length>1?t[a.href]=e:(a.hash=``,r===``?n=a:_(e,t,n))}}else if(e!==!0&&e!==!1)return t;let i=n.href+(r?`#`+r:``);if(t[i]!==void 0)throw Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}if(e.$anchor){let r=new URL(`#`+e.$anchor,n.href);t[r.href]=e}for(let i in e){if(h[i])continue;let a=`${r}/${d(i)}`,o=e[i];if(Array.isArray(o)){if(p[i]){let e=o.length;for(let r=0;r<e;r++)_(o[r],t,n,`${a}/${r}`)}}else if(m[i])for(let e in o)_(o[e],t,n,`${a}/${d(e)}`);else _(o,t,n,a)}return t}const v=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,y=[0,31,28,31,30,31,30,31,31,30,31,30,31],ee=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,te=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,b=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,x=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,ne=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,re=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,ie=/^(?:\/(?:[^~/]|~0|~1)*)*$/,ae=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,S=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,C=e=>{if(e[0]===`"`)return!1;let[t,n,...r]=e.split(`@`);return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]===`.`||t.endsWith(`.`)||t.includes(`..`)||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(`.`).every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},w=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,oe=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,se=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function T(e){return e.test.bind(e)}const ce={date:le,time:D.bind(void 0,!1),"date-time":k,duration:se,uri:ue,"uri-reference":T(b),"uri-template":T(x),url:T(ne),email:C,hostname:T(te),ipv4:T(w),ipv6:T(oe),regex:fe,uuid:T(re),"json-pointer":T(ie),"json-pointer-uri-fragment":T(ae),"relative-json-pointer":T(S)};function E(e){return e%4==0&&(e%100!=0||e%400==0)}function le(e){let t=e.match(v);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&E(n)?29:y[r])}function D(e,t){let n=t.match(ee);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=!!n[5];return(r<=23&&i<=59&&a<=59||r==23&&i==59&&a==60)&&(!e||o)}const O=/t|\s/i;function k(e){let t=e.split(O);return t.length==2&&le(t[0])&&D(!0,t[1])}const A=/\/|:/,j=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function ue(e){return A.test(e)&&j.test(e)}const de=/[^\\]\\Z/;function fe(e){if(de.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}function pe(e){let t=0,n=e.length,r=0,i;for(;r<n;)t++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<n&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return t}function M(e,t,n=`2019-09`,r=_(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,f;switch(l){case`boolean`:case`number`:case`string`:f=l;break;case`object`:f=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:p,$recursiveRef:m,$recursiveAnchor:h,type:g,const:v,enum:y,required:ee,not:te,anyOf:b,allOf:x,oneOf:ne,if:re,then:ie,else:ae,format:S,properties:C,patternProperties:w,additionalProperties:oe,unevaluatedProperties:se,minProperties:T,maxProperties:E,propertyNames:le,dependentRequired:D,dependentSchemas:O,dependencies:k,prefixItems:A,items:j,additionalItems:ue,unevaluatedItems:de,contains:fe,minContains:N,maxContains:P,minItems:F,maxItems:I,uniqueItems:L,minimum:R,maximum:z,exclusiveMinimum:B,exclusiveMaximum:V,multipleOf:H,minLength:U,maxLength:W,pattern:me,__absolute_ref__:G,__absolute_recursive_ref__:he}=t,K=[];if(h===!0&&a===null&&(a=t),m===`#`){let l=a===null?r[he]:a,u=`${s}/$recursiveRef`,d=M(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||K.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(p!==void 0){let t=r[G||p];if(t===void 0){let e=`Unresolved $ref "${p}".`;throw G&&G!==p&&(e+=` Absolute URI "${G}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
2
2
  - `)}`,Error(e)}let l=`${s}/$ref`,u=M(e,t,n,r,i,a,o,l,c);if(u.valid||K.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:K.length===0,errors:K}}if(Array.isArray(g)){let t=g.length,n=!1;for(let r=0;r<t;r++)if(f===g[r]||g[r]===`integer`&&f===`number`&&e%1==0&&e===e){n=!0;break}n||K.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${f}" is invalid. Expected "${g.join(`", "`)}".`})}else g===`integer`?(f!==`number`||e%1||e!==e)&&K.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${f}" is invalid. Expected "${g}".`}):g!==void 0&&f!==g&&K.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${f}" is invalid. Expected "${g}".`});if(v!==void 0&&(f===`object`||f===`array`?u(e,v)||K.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(v)}.`}):e!==v&&K.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(v)}.`})),y!==void 0&&(f===`object`||f===`array`?y.some(t=>u(e,t))||K.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`}):y.some(t=>e===t)||K.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`})),te!==void 0){let t=`${s}/not`;M(e,te,n,r,i,a,o,t).valid&&K.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let q=[];if(b!==void 0){let t=`${s}/anyOf`,l=K.length,u=!1;for(let s=0;s<b.length;s++){let l=b[s],d=Object.create(c),f=M(e,l,n,r,i,h===!0?a:null,o,`${t}/${s}`,d);K.push(...f.errors),u||=f.valid,f.valid&&q.push(d)}u?K.length=l:K.splice(l,0,{instanceLocation:o,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(x!==void 0){let t=`${s}/allOf`,l=K.length,u=!0;for(let s=0;s<x.length;s++){let l=x[s],d=Object.create(c),f=M(e,l,n,r,i,h===!0?a:null,o,`${t}/${s}`,d);K.push(...f.errors),u&&=f.valid,f.valid&&q.push(d)}u?K.length=l:K.splice(l,0,{instanceLocation:o,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(ne!==void 0){let t=`${s}/oneOf`,l=K.length,u=ne.filter((s,l)=>{let u=Object.create(c),d=M(e,s,n,r,i,h===!0?a:null,o,`${t}/${l}`,u);return K.push(...d.errors),d.valid&&q.push(u),d.valid}).length;u===1?K.length=l:K.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((f===`object`||f===`array`)&&Object.assign(c,...q),re!==void 0){let t=`${s}/if`;if(M(e,re,n,r,i,a,o,t,c).valid){if(ie!==void 0){let l=M(e,ie,n,r,i,a,o,`${s}/then`,c);l.valid||K.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(ae!==void 0){let l=M(e,ae,n,r,i,a,o,`${s}/else`,c);l.valid||K.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(f===`object`){if(ee!==void 0)for(let t of ee)t in e||K.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(T!==void 0&&t.length<T&&K.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${T} properties.`}),E!==void 0&&t.length>E&&K.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${E} properties.`}),le!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${d(s)}`,c=M(s,le,n,r,i,a,e,t);c.valid||K.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(D!==void 0){let t=`${s}/dependantRequired`;for(let n in D)if(n in e){let r=D[n];for(let i of r)i in e||K.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(O!==void 0)for(let t in O){let l=`${s}/dependentSchemas`;if(t in e){let s=M(e,O[t],n,r,i,a,o,`${l}/${d(t)}`,c);s.valid||K.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(k!==void 0){let t=`${s}/dependencies`;for(let s in k)if(s in e){let c=k[s];if(Array.isArray(c))for(let n of c)n in e||K.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=M(e,c,n,r,i,a,o,`${t}/${d(s)}`);l.valid||K.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(C!==void 0){let t=`${s}/properties`;for(let s in C){if(!(s in e))continue;let f=`${o}/${d(s)}`,p=M(e[s],C[s],n,r,i,a,f,`${t}/${d(s)}`);if(p.valid)c[s]=l[s]=!0;else if(u=i,K.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...p.errors),u)break}}if(!u&&w!==void 0){let t=`${s}/patternProperties`;for(let s in w){let f=new RegExp(s,`u`),p=w[s];for(let m in e){if(!f.test(m))continue;let h=`${o}/${d(m)}`,g=M(e[m],p,n,r,i,a,h,`${t}/${d(s)}`);g.valid?c[m]=l[m]=!0:(u=i,K.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${m}" matches pattern "${s}" but does not match associated schema.`},...g.errors))}}}if(!u&&oe!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let f=`${o}/${d(s)}`,p=M(e[s],oe,n,r,i,a,f,t);p.valid?c[s]=!0:(u=i,K.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...p.errors))}}else if(!u&&se!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${d(s)}`,u=M(e[s],se,n,r,i,a,l,t);u.valid?c[s]=!0:K.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(f===`array`){I!==void 0&&e.length>I&&K.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${I}).`}),F!==void 0&&e.length<F&&K.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${F}).`});let t=e.length,l=0,d=!1;if(A!==void 0){let u=`${s}/prefixItems`,f=Math.min(A.length,t);for(;l<f;l++){let t=M(e[l],A[l],n,r,i,a,`${o}/${l}`,`${u}/${l}`);if(c[l]=!0,!t.valid&&(d=i,K.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:u,error:`Items did not match schema.`},...t.errors),d))break}}if(j!==void 0){let u=`${s}/items`;if(Array.isArray(j)){let s=Math.min(j.length,t);for(;l<s;l++){let t=M(e[l],j[l],n,r,i,a,`${o}/${l}`,`${u}/${l}`);if(c[l]=!0,!t.valid&&(d=i,K.push({instanceLocation:o,keyword:`items`,keywordLocation:u,error:`Items did not match schema.`},...t.errors),d))break}}else for(;l<t;l++){let t=M(e[l],j,n,r,i,a,`${o}/${l}`,u);if(c[l]=!0,!t.valid&&(d=i,K.push({instanceLocation:o,keyword:`items`,keywordLocation:u,error:`Items did not match schema.`},...t.errors),d))break}if(!d&&ue!==void 0){let u=`${s}/additionalItems`;for(;l<t;l++){let t=M(e[l],ue,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||(d=i,K.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:u,error:`Items did not match additional items schema.`},...t.errors))}}}if(fe!==void 0)if(t===0&&N===void 0)K.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(N!==void 0&&t<N)K.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${N}).`});else{let l=`${s}/contains`,u=K.length,d=0;for(let s=0;s<t;s++){let t=M(e[s],fe,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):K.push(...t.errors)}d>=(N||0)&&(K.length=u),N===void 0&&P===void 0&&d===0?K.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):N!==void 0&&d<N?K.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${N} items matching schema. Only ${d} items were found.`}):P!==void 0&&d>P&&K.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${P} items matching schema. ${d} items were found.`})}if(!d&&de!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=M(e[l],de,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||K.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(L)for(let n=0;n<t;n++){let r=e[n],i=typeof r==`object`&&!!r;for(let a=0;a<t;a++){if(n===a)continue;let t=e[a];(r===t||i&&typeof t==`object`&&t&&u(r,t))&&(K.push({instanceLocation:o,keyword:`uniqueItems`,keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${a}.`}),n=2**53-1,a=2**53-1)}}}else if(f===`number`){if(n===`4`?(R!==void 0&&(B===!0&&e<=R||e<R)&&K.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${B?`or equal to `:``} ${R}.`}),z!==void 0&&(V===!0&&e>=z||e>z)&&K.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${V?`or equal to `:``} ${z}.`})):(R!==void 0&&e<R&&K.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${R}.`}),z!==void 0&&e>z&&K.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${z}.`}),B!==void 0&&e<=B&&K.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${B}.`}),V!==void 0&&e>=V&&K.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${V}.`})),H!==void 0){let t=e%H;Math.abs(0-t)>=1.1920929e-7&&Math.abs(H-t)>=1.1920929e-7&&K.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${H}.`})}}else if(f===`string`){let t=U===void 0&&W===void 0?0:pe(e);U!==void 0&&t<U&&K.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${U}).`}),W!==void 0&&t>W&&K.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${W}).`}),me!==void 0&&!new RegExp(me,`u`).test(e)&&K.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),S!==void 0&&ce[S]&&!ce[S](e)&&K.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${S}".`})}return{valid:K.length===0,errors:K}}var N=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=_(e)}validate(e){return M(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),_(e,this.lookup)}};const P=`Failed to parse input arguments`,F=`Tool was executed but the invocation failed. For example, the script function threw an error`,I=`Tool was cancelled`,L={type:`object`,properties:{}},R=[`draft-2020-12`,`draft-07`],z=Symbol(`standardValidator`),B={installed:!1,previousNavigatorModelContextDescriptor:void 0,previousNavigatorModelContextTestingDescriptor:void 0,previousDocumentModelContextDescriptor:void 0,installedNavigatorModelContext:!1,installedNavigatorModelContextTesting:!1,installedDocumentModelContext:!1};var V=class extends EventTarget{tools=new Map;testingShim=null;_ontoolchange=null;unregisterToolDeprecationWarned=!1;get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}registerTool(e,t){let n=t?.signal;if(n?.aborted){console.warn(`[WebMCPPolyfill] registerTool("${e?.name??`<unknown>`}") skipped: options.signal was already aborted.`);return}let r=ye(e,this.tools);this.tools.set(r.name,r),this.notifyToolsChanged(),n&&n.addEventListener(`abort`,()=>{this.tools.delete(r.name)&&this.notifyToolsChanged()},{once:!0})}unregisterTool(e){this.warnUnregisterToolDeprecationOnce();let t=me(e);this.tools.delete(t)&&this.notifyToolsChanged()}getTools(){return Promise.resolve(this.getRegisteredToolInfos())}executeTool(e,t,n){return this.executeToolByName(e.name,t,n,!1)}getTestingShim(){return this.testingShim||=new H(this),this.testingShim}getToolInfos(){return[...this.tools.values()].map(e=>{let t;try{t=JSON.stringify(e.inputSchema??{type:`object`})}catch{t=`{"type":"object"}`}return{name:e.name,description:e.description,inputSchema:t}})}getRegisteredToolInfos(){return this.getToolInfos().map(e=>{let t=this.tools.get(e.name);return{...e,title:t?.title??``,origin:globalThis.location?.origin??``,window:globalThis.window}})}async executeToolForTesting(e,t,n){return this.executeToolByName(e,t,n,!0)}async executeToolByName(e,t,n,r){if(n?.signal?.aborted)throw U(I);let i=this.tools.get(e);if(!i)throw U(`Tool not found: ${e}`);let a=W(t),o=await Ce(a,i);if(o)throw U(o);let s=!0,c={requestUserInteraction:async t=>{if(!s)throw Error(`ModelContextClient for tool "${e}" is no longer active after execute() resolved`);if(typeof t!=`function`)throw TypeError(`requestUserInteraction(callback) requires a function callback`);return t()}};try{let e=i.execute(a,c),t=await Me(Promise.resolve(e),n?.signal);if(r)return je(ke(t));let o=JSON.stringify(t);return o===void 0?null:o}catch(e){throw U(e instanceof Error?`${F}: ${e.message}`:F)}finally{s=!1}}notifyToolsChanged(){queueMicrotask(()=>{let e=new Event(`toolchange`);try{this._ontoolchange?.call(this,e)}catch(e){console.warn(`[WebMCPPolyfill] navigator.modelContext.ontoolchange handler threw:`,e)}this.dispatchEvent(e),this.testingShim?.dispatchToolChange()})}warnUnregisterToolDeprecationOnce(){this.unregisterToolDeprecationWarned||(this.unregisterToolDeprecationWarned=!0,console.warn(`[WebMCPPolyfill] navigator.modelContext.unregisterTool() is deprecated. The April 23, 2026 WebMCP draft removed it in favor of registerTool(tool, { signal }) — pass an AbortSignal and abort it to unregister.`))}},H=class extends EventTarget{context;_ontoolchange=null;constructor(e){super(),this.context=e}listTools(){return this.context.getToolInfos()}executeTool(e,t,n){return this.context.executeToolForTesting(e,t,n)}getCrossDocumentScriptToolResult(){return Promise.resolve(`[]`)}get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}registerToolsChangedCallback(e){if(typeof e!=`function`)throw TypeError(`Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.`);this.addEventListener(`toolchange`,e)}dispatchToolChange(){let e=new Event(`toolchange`);try{this._ontoolchange?.call(this,e)}catch(e){console.warn(`[WebMCPPolyfill] ontoolchange handler threw:`,e)}this.dispatchEvent(e),this.dispatchEvent(new Event(`toolschanged`))}};function U(e){try{return new DOMException(e,`UnknownError`)}catch{let t=Error(e);return t.name=`UnknownError`,t}}function W(e){let t;try{t=JSON.parse(e)}catch{throw U(P)}if(!t||typeof t!=`object`||Array.isArray(t))throw U(P);return t}function me(e){if(typeof e==`string`)return e;if(G(e)&&typeof e.name==`string`)return e.name;throw TypeError(`Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.`)}function G(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function he(e){if(!G(e))return null;let t=e[`~standard`];return G(t)?t:null}function K(e){let t=he(e);return!!(t&&t.version===1&&typeof t.validate==`function`)}function q(e){let t=he(e);return!t||t.version!==1||!G(t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function J(e){return{"~standard":{version:1,vendor:`@mcp-b/webmcp-polyfill-json-schema`,validate(t){if(!G(t))return{issues:[{message:`expected object arguments`}]};let n=be(t,e);return n?{issues:[n]}:{value:t}}}}}function ge(e){for(let t of R)try{let n=e[`~standard`].jsonSchema.input({target:t});return ve(n),n}catch(e){console.warn(`[WebMCPPolyfill] Standard JSON Schema conversion failed for target "${t}":`,e)}throw Error(`Failed to convert Standard JSON Schema inputSchema to a JSON Schema object`)}function _e(e){if(e===void 0){let e=L;return{inputSchema:e,standardValidator:J(e)}}if(q(e)){let t=ge(e);return{inputSchema:t,standardValidator:J(t)}}if(K(e))return{inputSchema:L,standardValidator:e};if(ve(e),Object.keys(e).length===0)return{inputSchema:L,standardValidator:J(L)};let t=e.type===void 0?{type:`object`,...e}:e;return{inputSchema:t,standardValidator:J(t)}}function ve(e){if(!G(e))throw Error(`inputSchema must be a JSON Schema object`);Y(e,`$`)}function Y(e,t){let n=e.type;if(n!==void 0&&typeof n!=`string`&&!(Array.isArray(n)&&n.every(e=>typeof e==`string`&&e.length>0)))throw Error(`Invalid JSON Schema at ${t}: "type" must be a string or string[]`);let r=e.required;if(r!==void 0&&!(Array.isArray(r)&&r.every(e=>typeof e==`string`)))throw Error(`Invalid JSON Schema at ${t}: "required" must be an array of strings`);let i=e.properties;if(i!==void 0){if(!G(i))throw Error(`Invalid JSON Schema at ${t}: "properties" must be an object`);for(let[e,n]of Object.entries(i)){if(!G(n))throw Error(`Invalid JSON Schema at ${t}.properties.${e}: expected object schema`);Y(n,`${t}.properties.${e}`)}}let a=e.items;if(a!==void 0)if(Array.isArray(a))for(let[e,n]of a.entries()){if(!G(n))throw Error(`Invalid JSON Schema at ${t}.items[${e}]: expected object schema`);Y(n,`${t}.items[${e}]`)}else if(G(a))Y(a,`${t}.items`);else throw Error(`Invalid JSON Schema at ${t}: "items" must be an object or object[]`);for(let n of[`allOf`,`anyOf`,`oneOf`]){let r=e[n];if(r!==void 0){if(!Array.isArray(r))throw Error(`Invalid JSON Schema at ${t}: "${n}" must be an array`);for(let[e,i]of r.entries()){if(!G(i))throw Error(`Invalid JSON Schema at ${t}.${n}[${e}]: expected object schema`);Y(i,`${t}.${n}[${e}]`)}}}let o=e.not;if(o!==void 0){if(!G(o))throw Error(`Invalid JSON Schema at ${t}: "not" must be an object schema`);Y(o,`${t}.not`)}try{JSON.stringify(e)}catch{throw Error(`Invalid JSON Schema at ${t}: schema must be JSON-serializable`)}}function ye(e,t){if(!e||typeof e!=`object`)throw TypeError(`registerTool(tool) requires a tool object`);if(typeof e.name!=`string`||e.name.length===0)throw TypeError(`Tool "name" must be a non-empty string`);if(typeof e.description!=`string`||e.description.length===0)throw TypeError(`Tool "description" must be a non-empty string`);if(typeof e.execute!=`function`)throw TypeError(`Tool "execute" must be a function`);if(t.has(e.name))throw Error(`Tool already registered: ${e.name}`);let n=_e(e.inputSchema),r=e.annotations,i=r?{...r,...r.readOnlyHint===`true`?{readOnlyHint:!0}:r.readOnlyHint===`false`?{readOnlyHint:!1}:{},...r.destructiveHint===`true`?{destructiveHint:!0}:r.destructiveHint===`false`?{destructiveHint:!1}:{},...r.idempotentHint===`true`?{idempotentHint:!0}:r.idempotentHint===`false`?{idempotentHint:!1}:{},...r.openWorldHint===`true`?{openWorldHint:!0}:r.openWorldHint===`false`?{openWorldHint:!1}:{}}:void 0;return{...e,...i?{annotations:i}:{},inputSchema:n.inputSchema,[z]:n.standardValidator}}function be(e,t){let n=new N(t,`2020-12`,!0).validate(e);if(n.valid)return null;let r=n.errors[n.errors.length-1];return r?{message:r.error}:{message:`Input validation failed`}}function xe(e){if(!e||e.length===0)return null;let t=e.map(e=>G(e)&&`key`in e?e.key:e).map(e=>String(e)).filter(e=>e.length>0);return t.length===0?null:t.join(`.`)}async function Se(e,t){let n;try{n=await Promise.resolve(t[`~standard`].validate(e))}catch(e){let t=e instanceof Error?`: ${e.message}`:``;return console.error(`[WebMCPPolyfill] Standard Schema validation threw unexpectedly:`,e),`Input validation error: schema validation failed${t}`}if(!n.issues||n.issues.length===0)return null;let r=n.issues[0];if(!r)return`Input validation error`;let i=xe(r?.path);return i?`Input validation error: ${r.message} at ${i}`:`Input validation error: ${r.message}`}async function Ce(e,t){return Se(e,t[z])}function we(e){return G(e)&&Array.isArray(e.content)}function Te(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function Ee(e){return Te(e)?Number.isFinite(e)||typeof e!=`number`:Array.isArray(e)?e.every(e=>Ee(e)):G(e)?Object.values(e).every(e=>Ee(e)):!1}function De(e){if(!(!G(e)||!Ee(e)))return e}function Oe(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function ke(e){if(we(e))return e;let t=De(e);return{content:[{type:`text`,text:Oe(e)}],...t?{structuredContent:t}:{},isError:!1}}function Ae(e){for(let t of e.content??[])if(t.type===`text`&&`text`in t&&typeof t.text==`string`)return t.text;return null}function je(e){if(e.isError)throw U(Ae(e)?.replace(/^Error:\s*/i,``).trim()||F);let t=e.metadata;if(t&&typeof t==`object`&&t.willNavigate)return null;try{return JSON.stringify(e)}catch{throw U(F)}}function Me(e,t){return t?t.aborted?Promise.reject(U(I)):new Promise((n,r)=>{let i=()=>{a(),r(U(I))},a=()=>{t.removeEventListener(`abort`,i)};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{a(),n(e)},e=>{a(),r(e)})}):e}function Ne(){return typeof navigator<`u`?navigator:null}function Pe(){return typeof document<`u`?document:null}function Fe(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!1,value:n})}function Ie(e,t){Object.defineProperty(e,"modelContext",{configurable:!0,enumerable:!0,writable:!1,value:t})}let X=!1;function Le(e,t){Object.defineProperty(e,"modelContext",{configurable:!0,enumerable:!0,get(){return X||(X=!0,console.warn(`[WebMCPPolyfill] navigator.modelContext is deprecated. The May 27, 2026 WebMCP draft moved the modelContext getter from Navigator to Document — use document.modelContext instead. See https://github.com/webmachinelearning/webmcp/pull/184.`)),t}})}function Re(e){let t=Ne(),n=Pe();if(!t&&!n||n?.modelContext)return;let r=t?.modelContext,i=!!r;if(B.installed&&ze(),n&&r){B.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(n,`modelContext`),Ie(n,r),B.installedDocumentModelContext=!0,B.installed=!0;return}if(i)return;let a=new V,o=a;if(o.__isWebMCPPolyfill=!0,n&&(B.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(n,`modelContext`),Ie(n,o),B.installedDocumentModelContext=!0),t){B.previousNavigatorModelContextDescriptor=Object.getOwnPropertyDescriptor(t,`modelContext`),B.previousNavigatorModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(t,`modelContextTesting`),X=!1,Le(t,o),B.installedNavigatorModelContext=!0;let n=e?.installTestingShim??`if-missing`,r=!!t.modelContextTesting;(n===`always`||(n===!0||n===`if-missing`)&&!r)&&(Fe(t,`modelContextTesting`,a.getTestingShim()),B.installedNavigatorModelContextTesting=!0)}B.installed=!0}function ze(){if(!B.installed)return;let e=(e,t,n)=>{if(n){Object.defineProperty(e,t,n);return}delete e[t]},t=Ne(),n=Pe();n&&B.installedDocumentModelContext&&e(n,`modelContext`,B.previousDocumentModelContextDescriptor),t&&B.installedNavigatorModelContext&&e(t,`modelContext`,B.previousNavigatorModelContextDescriptor),t&&B.installedNavigatorModelContextTesting&&e(t,`modelContextTesting`,B.previousNavigatorModelContextTestingDescriptor),B.installed=!1,B.previousDocumentModelContextDescriptor=void 0,B.previousNavigatorModelContextDescriptor=void 0,B.previousNavigatorModelContextTestingDescriptor=void 0,B.installedDocumentModelContext=!1,B.installedNavigatorModelContext=!1,B.installedNavigatorModelContextTesting=!1,X=!1}if(typeof window<`u`&&typeof document<`u`){let e=window.__webMCPPolyfillOptions;if(e?.autoInitialize!==!1)try{Re(e)}catch(e){console.error(`[WebMCPPolyfill] Auto-initialization failed:`,e)}}const Z=new Map,Q=new Set;let Be=`polyfill`;function Ve(e){Be=e}function He(){return Be}function Ue(){try{Re()}catch(e){console.warn(`WebMCP polyfill initialization failed:`,e)}}function We(){if(typeof document>`u`&&typeof navigator>`u`)return null;Be===`polyfill`&&Ue();try{let e=typeof document<`u`&&document.modelContext!==void 0?Reflect.get(document,`modelContext`):typeof navigator<`u`&&navigator.modelContext!==void 0?Reflect.get(navigator,`modelContext`):void 0;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.registerTool==`function`?t:null}catch(e){return console.warn(`WebMCP modelContext access failed:`,e),null}}function Ge(e){if(typeof e==`string`){try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}return{type:`object`,properties:{}}}return e&&typeof e==`object`&&!Array.isArray(e)?e:{type:`object`,properties:{}}}function Ke(e){if(e){if(typeof AbortSignal<`u`&&e instanceof AbortSignal)return e;if(typeof e==`object`&&`signal`in e&&typeof AbortSignal<`u`&&e.signal instanceof AbortSignal)return e.signal}}async function qe(t,n,r=e,a){let o=Array.isArray(a)?a:i;if(o.length===0)return!0;let s=We();if(!s)return!1;for(let e of o){if(Q.has(e.name))continue;let n=new AbortController;Z.set(e.name,n),Q.add(e.name);try{let i={name:e.name,description:e.description,inputSchema:Ge(e.input_schema),annotations:{readOnlyHint:!1,untrustedContentHint:!0},execute:(n,i)=>{if(!t)throw Error(`Cannot execute tool: agent worker is not ready`);let a=Ke(i);return a?.aborted?Promise.reject(Error(`Tool execution aborted`)):new Promise((i,o)=>{let s=Date.now().toString(36)+Math.random().toString(36).slice(2),c=null,l=()=>{c!==null&&(clearTimeout(c),c=null),t?.removeEventListener(`message`,d),a&&u&&a.removeEventListener(`abort`,u)},u=()=>{l(),o(Error(`Tool execution aborted`))};a&&a.addEventListener(`abort`,u,{once:!0}),c=setTimeout(()=>{l(),o(Error(`Timeout waiting for tool execution`))},6e5);let d=e=>{let t=e.data;t&&t.type===`execute-tool-result`&&t.callId===s&&(l(),t.error?o(Error(t.error)):i(t.result))};t.addEventListener(`message`,d),t.postMessage({type:`execute-tool`,callId:s,payload:{name:e.name,input:n||{},groupId:r}})})}};await s.registerTool(i,{signal:n.signal}),await new Promise(e=>setTimeout(e,0))}catch(t){if(Z.delete(e.name),Q.delete(e.name),!(t instanceof Error&&(t.message.includes(`already registered`)||t.message.includes(`Duplicate tool name`))))throw console.error(`Failed to register tool ${e.name}:`,t),t}}return!0}function $(){for(let e of Z.values())try{e.abort()}catch{}Z.clear(),Q.clear()}function Je(e,t){if(typeof e.webMcpEffectCleanup==`function`&&(e.webMcpEffectCleanup(),e.webMcpEffectCleanup=null),!e.webMcpToolsEnabled){$();return}e.webMcpEffectCleanup=c(()=>{let i=o.activeGroupId,s=a.allTools,c=a.enabledTools;a.declarativeTools,a.declarativeToolNamesEnabled;let u=o.groups.find(e=>e.groupId===i);e.webMcpRegistrationLock=e.webMcpRegistrationLock.then(async()=>{$(),await new Promise(e=>setTimeout(e,0));let o=[];try{o=await a.refreshDeclarativeTools(t,i)}catch{}let d=o.filter(e=>a.isDeclarativeToolEnabled(e.name)),f=[...s,...o],p=u?.toolTags&&u.toolTags.length>0?f.filter(e=>u.toolTags.includes(e.name)):[...c,...d],m={skills:[]};try{m=await n(t,i)}catch{}m.skills.length>0&&!p.some(e=>e.name===l.name)&&(p=[...p,l]),await qe(e.agentWorker,async n=>{await r(e,t,n)},i,p)}).catch(e=>{console.error(`WebMCP registration failed:`,e)})})}async function Ye(e,n,r,i){$(),Ve(r),await s(n,t.WEBMCP_MODE,r),Je(i.orchestrator,n)}async function Xe(e,n,r,i){e.webMcpToolsEnabled=!!r,await s(n,t.WEBMCP_TOOLS_ENABLED,e.webMcpToolsEnabled?`true`:`false`),Je(i.orchestrator,n)}export{Ve as a,He as i,Xe as n,$ as o,Je as r,l as s,Ye as t};