@undefineds.co/xpod 0.4.29 → 0.4.30

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 (179) hide show
  1. package/dist/api/ApiServer.js +4 -0
  2. package/dist/api/ai-gateway/AiGatewayService.d.ts +55 -0
  3. package/dist/api/ai-gateway/AiGatewayService.js +145 -6
  4. package/dist/api/ai-gateway/auth/AiConnectionsInvocationKeyIssuer.js +5 -3
  5. package/dist/api/ai-gateway/auth/GatewayApiKeyAuthenticator.d.ts +16 -49
  6. package/dist/api/ai-gateway/auth/GatewayApiKeyAuthenticator.js +6 -71
  7. package/dist/api/ai-gateway/auth/InvocationTokenAuthenticator.js +1 -0
  8. package/dist/api/ai-gateway/auth/InvocationTokenCodec.d.ts +4 -0
  9. package/dist/api/ai-gateway/auth/InvocationTokenCodec.js +8 -1
  10. package/dist/api/ai-gateway/connect/FileSessionImportAdapter.d.ts +3 -0
  11. package/dist/api/ai-gateway/connect/FileSessionImportAdapter.js +23 -3
  12. package/dist/api/ai-gateway/connect/SessionImportProfiles.d.ts +9 -1
  13. package/dist/api/ai-gateway/connect/SessionImportProfiles.js +4 -3
  14. package/dist/api/ai-gateway/connect/index.d.ts +40 -0
  15. package/dist/api/ai-gateway/connect/index.js +194 -4
  16. package/dist/api/ai-gateway/models/PodModelSelectionRepository.js +1 -1
  17. package/dist/api/ai-gateway/pod/OwnerPodAccess.js +5 -0
  18. package/dist/api/ai-gateway/pod/PodBaseUrlResolver.d.ts +11 -2
  19. package/dist/api/ai-gateway/pod/PodBaseUrlResolver.js +72 -10
  20. package/dist/api/ai-gateway/quota/ProviderQuotaAdapter.js +1 -1
  21. package/dist/api/ai-gateway/routing/ModelRouter.d.ts +7 -0
  22. package/dist/api/ai-gateway/routing/ModelRouter.js +13 -10
  23. package/dist/api/ai-gateway/service-access/AiConnectionsServiceAccess.d.ts +1 -5
  24. package/dist/api/ai-gateway/service-access/AiConnectionsServiceAccess.js +8 -63
  25. package/dist/api/auth/AuthContext.d.ts +4 -0
  26. package/dist/api/auth/ClientCredentialsAuthenticator.js +11 -5
  27. package/dist/api/auth/SolidSessionFactory.d.ts +50 -4
  28. package/dist/api/auth/SolidSessionFactory.js +114 -4
  29. package/dist/api/chatkit/pod-store.d.ts +8 -1
  30. package/dist/api/chatkit/pod-store.js +54 -3
  31. package/dist/api/container/common.js +34 -60
  32. package/dist/api/container/index.js +0 -3
  33. package/dist/api/container/routes.js +1 -8
  34. package/dist/api/container/types.d.ts +2 -9
  35. package/dist/api/container/types.js +0 -5
  36. package/dist/api/handlers/AiGatewayManagementHandler.d.ts +4 -12
  37. package/dist/api/handlers/AiGatewayManagementHandler.js +18 -258
  38. package/dist/api/middleware/AuthMiddleware.js +29 -1
  39. package/dist/api/runs/PiAgentRuntimeDriver.js +6 -1
  40. package/dist/cli/index.js +2 -1
  41. package/dist/identity/oidc/PodOwnershipResolver.js +16 -6
  42. package/dist/runtime/ingress-port.d.ts +9 -2
  43. package/dist/runtime/ingress-port.js +7 -2
  44. package/dist/runtime/local-secret-file.d.ts +1 -1
  45. package/dist/runtime/runner/node/CommunitySolidServerCssRunner.d.ts +3 -1
  46. package/dist/runtime/runner/node/CommunitySolidServerCssRunner.js +31 -1
  47. package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.d.ts +3 -1
  48. package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.js +96 -67
  49. package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialPoolSection.d.ts +2 -1
  50. package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialPoolSection.js +2 -2
  51. package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeyRow.d.ts +1 -2
  52. package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeyRow.js +2 -2
  53. package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeysSection.js +81 -23
  54. package/node_modules/@undefineds.co/ai-connections/dist/AiOfferingDetails.d.ts +2 -1
  55. package/node_modules/@undefineds.co/ai-connections/dist/AiOfferingDetails.js +2 -2
  56. package/node_modules/@undefineds.co/ai-connections/dist/AiProviderCard.d.ts +2 -1
  57. package/node_modules/@undefineds.co/ai-connections/dist/AiProviderCard.js +2 -2
  58. package/node_modules/@undefineds.co/ai-connections/dist/AiProviderHeader.js +1 -1
  59. package/node_modules/@undefineds.co/ai-connections/dist/contract/client/fingerprint.d.ts +1 -0
  60. package/node_modules/@undefineds.co/ai-connections/dist/contract/client/fingerprint.js +7 -0
  61. package/node_modules/@undefineds.co/ai-connections/dist/contract/client/normalize.d.ts +1 -2
  62. package/node_modules/@undefineds.co/ai-connections/dist/contract/client/normalize.js +0 -33
  63. package/node_modules/@undefineds.co/ai-connections/dist/contract/client/request.d.ts +1 -1
  64. package/node_modules/@undefineds.co/ai-connections/dist/contract/client/request.js +68 -22
  65. package/node_modules/@undefineds.co/ai-connections/dist/contract/client/types.d.ts +37 -10
  66. package/node_modules/@undefineds.co/ai-connections/dist/controller.js +5 -54
  67. package/node_modules/@undefineds.co/ai-connections/dist/error-wording.js +7 -2
  68. package/node_modules/@undefineds.co/ai-connections/dist/service-access-resources.cjs +405 -0
  69. package/node_modules/@undefineds.co/ai-connections/dist/service-access-resources.d.ts +14 -0
  70. package/node_modules/@undefineds.co/ai-connections/dist/service-access-resources.js +36 -0
  71. package/node_modules/@undefineds.co/ai-connections/dist/service-access.js +5 -26
  72. package/node_modules/@undefineds.co/ai-connections/package.json +10 -2
  73. package/node_modules/@undefineds.co/extension-sdk/dist/solid-permissions.js +131 -13
  74. package/node_modules/@undefineds.co/extension-sdk/dist/web.d.ts +7 -1
  75. package/node_modules/@undefineds.co/extension-sdk/package.json +1 -1
  76. package/node_modules/@undefineds.co/pod-collections/dist/index.cjs +38 -5
  77. package/node_modules/@undefineds.co/pod-collections/dist/mapping.d.ts +8 -0
  78. package/node_modules/@undefineds.co/pod-collections/dist/mapping.js +34 -0
  79. package/node_modules/@undefineds.co/pod-collections/dist/mutations.d.ts +2 -1
  80. package/node_modules/@undefineds.co/pod-collections/dist/mutations.js +6 -4
  81. package/node_modules/@undefineds.co/pod-collections/dist/sync.js +4 -3
  82. package/node_modules/@undefineds.co/pod-collections/package.json +1 -1
  83. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/IdpChrome.d.ts +1 -1
  84. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/IdpChrome.js +2 -2
  85. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/IdpViews.js +2 -2
  86. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/PodSignInFrame.d.ts +3 -3
  87. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/PodSignInFrame.js +5 -5
  88. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/parts.d.ts +5 -5
  89. package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/parts.js +5 -5
  90. package/node_modules/@undefineds.co/shared-ui/dist/theme.css +32 -5
  91. package/node_modules/@undefineds.co/shared-ui/package.json +1 -1
  92. package/package.json +2 -2
  93. package/static/app/assets/main.css +1 -1
  94. package/static/app/assets/main.js +18 -18
  95. package/static/dashboard/assets/{AccountAuthBoundary-Dv52SZc6.js → AccountAuthBoundary-CuqXFEW4.js} +1 -1
  96. package/static/dashboard/assets/{DesktopOidcCallback-DaT_Rumf.js → DesktopOidcCallback-7i-yOvPW.js} +1 -1
  97. package/static/dashboard/assets/DevicePages-D1m_BNtX.js +2 -0
  98. package/static/dashboard/assets/ModelsPage-0qWGa5Y6.js +12 -0
  99. package/static/dashboard/assets/{PaneListHeader-DtvnRmFq.js → PaneListHeader-uWdPgJ0E.js} +1 -1
  100. package/static/dashboard/assets/{PodDeletionAuthorizationPanel-BJk_8rJq.js → PodDeletionAuthorizationPanel-C22bhZeD.js} +3 -3
  101. package/static/dashboard/assets/{PodPage-C4gzEspV.js → PodPage-Dyo3yCb-.js} +1 -1
  102. package/static/dashboard/assets/{SystemSettingsPage-HaNrP1H1.js → SystemSettingsPage-CeX-oG_a.js} +1 -1
  103. package/static/dashboard/assets/{TasksPage-BdO5K2L7.js → TasksPage-B0EoyRYT.js} +1 -1
  104. package/static/dashboard/assets/{WebDesktopEntry-Cj9_ZfJU.js → WebDesktopEntry-DT44RrTa.js} +1 -1
  105. package/static/dashboard/assets/XpodAiConnectionsPodStore-EXCqZPmb.js +3 -0
  106. package/static/dashboard/assets/XpodShellApp-BEzi4f1j.css +1 -0
  107. package/static/dashboard/assets/XpodShellApp-DAFsxamX.js +4 -0
  108. package/static/dashboard/assets/{account-session-DlcKNG7k.js → account-session-rRAOF7nF.js} +1 -1
  109. package/static/dashboard/assets/{button-wslF55uZ.js → button-WVnQUNG-.js} +1 -1
  110. package/static/dashboard/assets/{collection-runtime-uxxgEu13.js → collection-runtime-BAJQ8Qub.js} +1 -1
  111. package/static/dashboard/assets/{createLucideIcon-BJQl82Qk.js → createLucideIcon-BWelSi3L.js} +1 -1
  112. package/static/dashboard/assets/dashboard-hSOBxPcP.css +1 -0
  113. package/static/dashboard/assets/{dashboard-Or0gnkou.js → dashboard-vmne1ZE0.js} +2 -2
  114. package/static/dashboard/assets/{index-BqFeOML9.js → index-HDQQ8asz.js} +1 -1
  115. package/static/dashboard/assets/{index-DgKn1twH.js → index-gtv-MAHl.js} +1 -1
  116. package/static/dashboard/assets/{label-CS6Sx6Zb.js → label-tKuCTJm2.js} +1 -1
  117. package/static/dashboard/assets/{list-UyhlCFKk.js → list-CKq3KHke.js} +1 -1
  118. package/static/dashboard/assets/{nav-item-style-CW1Nnorq.js → nav-item-style-B2gI7c52.js} +1 -1
  119. package/static/dashboard/assets/pod-collections-host-BqOAkacM.js +8 -0
  120. package/static/dashboard/assets/{safe-continuation-ClWAhcma.js → safe-continuation-BsKjDpAA.js} +1 -1
  121. package/static/dashboard/assets/{section-header-CEIEcco-.js → section-header-DM0JU-wk.js} +1 -1
  122. package/static/dashboard/assets/{setting-row-CaYv3dfF.js → setting-row-XiH7UjWy.js} +1 -1
  123. package/static/dashboard/assets/{xpod-remembered-login-BUF9fin1.js → xpod-remembered-login-nv1g1sfC.js} +4 -4
  124. package/static/dashboard/dashboard.html +2 -2
  125. package/static/settings/assets/{AccountAuthBoundary-Chqd38oU.js → AccountAuthBoundary-DAUR0omy.js} +1 -1
  126. package/static/settings/assets/{DesktopOidcCallback-VUrOSM_q.js → DesktopOidcCallback-BNZAZMWY.js} +1 -1
  127. package/static/settings/assets/DevicePages-BO9SrXRp.js +2 -0
  128. package/static/settings/assets/ModelsPage-DREEXdf3.js +12 -0
  129. package/static/settings/assets/{PaneListHeader-B5RkRqr4.js → PaneListHeader-CeUH0JjQ.js} +1 -1
  130. package/static/settings/assets/{PodDeletionAuthorizationPanel-DPM-5Izt.js → PodDeletionAuthorizationPanel-Ch4--l4b.js} +3 -3
  131. package/static/settings/assets/{PodPage-CxND6wwc.js → PodPage-CqJBj3GJ.js} +1 -1
  132. package/static/settings/assets/{SystemSettingsPage-C8EdMkW7.js → SystemSettingsPage-2LSjpqUa.js} +1 -1
  133. package/static/settings/assets/{TasksPage-DuqptEm8.js → TasksPage-DA5IRxlP.js} +1 -1
  134. package/static/settings/assets/{WebDesktopEntry-BRcyktkv.js → WebDesktopEntry-BVelF1q0.js} +1 -1
  135. package/static/settings/assets/XpodAiConnectionsPodStore-O5-2qBsx.js +3 -0
  136. package/static/settings/assets/XpodShellApp-BEzi4f1j.css +1 -0
  137. package/static/settings/assets/XpodShellApp-D1b3kqD0.js +4 -0
  138. package/static/settings/assets/XpodThemeProvider-hSOBxPcP.css +1 -0
  139. package/static/settings/assets/{XpodThemeProvider-DK3pIdRG.js → XpodThemeProvider-rUdAw66p.js} +2 -2
  140. package/static/settings/assets/{account-session-DJOZ03xr.js → account-session-BD1q8D_o.js} +1 -1
  141. package/static/settings/assets/auth-callback-PWS7okI8.js +1 -0
  142. package/static/settings/assets/{button-D3yW-2o1.js → button-ZJYFB218.js} +1 -1
  143. package/static/settings/assets/{collection-runtime-DfGo25mh.js → collection-runtime-C2FHCCXJ.js} +1 -1
  144. package/static/settings/assets/{createLucideIcon-CacwLsmB.js → createLucideIcon-B2wXvYTD.js} +1 -1
  145. package/static/settings/assets/{index-r5KRYsKC.js → index-JFAkaKZH.js} +1 -1
  146. package/static/settings/assets/{label-MJjUmvzG.js → label-BLrTAmGy.js} +1 -1
  147. package/static/settings/assets/{list-Ce-5k1MX.js → list-Cm96vvJO.js} +1 -1
  148. package/static/settings/assets/{nav-item-style-ZUbL8KOZ.js → nav-item-style-C2upI7sr.js} +1 -1
  149. package/static/settings/assets/pod-collections-host-BqOAkacM.js +8 -0
  150. package/static/settings/assets/{safe-continuation-vlBZFSlU.js → safe-continuation-CYaRj3rj.js} +1 -1
  151. package/static/settings/assets/{section-header-DGJdEvQw.js → section-header-BviL5H8E.js} +1 -1
  152. package/static/settings/assets/{setting-row-C7tuFiho.js → setting-row-BYikj0YO.js} +1 -1
  153. package/static/settings/assets/{settings-CyQPih1O.js → settings-CpoDG_Qr.js} +1 -1
  154. package/static/settings/assets/{xpod-remembered-login-D-TzzT5K.js → xpod-remembered-login-BJ4QUSXy.js} +4 -4
  155. package/static/settings/auth-callback.html +3 -3
  156. package/static/settings/settings.html +3 -3
  157. package/dist/api/ai-gateway/auth/GatewayApiKey.d.ts +0 -28
  158. package/dist/api/ai-gateway/auth/GatewayApiKey.js +0 -162
  159. package/dist/api/ai-gateway/auth/GatewayKeyLocatorCodec.d.ts +0 -26
  160. package/dist/api/ai-gateway/auth/GatewayKeyLocatorCodec.js +0 -97
  161. package/dist/api/ai-gateway/auth/PodGatewayAccessKeyRepository.d.ts +0 -67
  162. package/dist/api/ai-gateway/auth/PodGatewayAccessKeyRepository.js +0 -340
  163. package/dist/runtime/gateway-locator-secret.d.ts +0 -5
  164. package/dist/runtime/gateway-locator-secret.js +0 -30
  165. package/static/dashboard/assets/DevicePages-HjclpIVm.js +0 -2
  166. package/static/dashboard/assets/ModelsPage-Be2TPd-x.js +0 -11
  167. package/static/dashboard/assets/XpodAiConnectionsPodStore-B7gmXBmC.js +0 -3
  168. package/static/dashboard/assets/XpodShellApp-Bwom2xL3.css +0 -1
  169. package/static/dashboard/assets/XpodShellApp-D_KY4nCW.js +0 -4
  170. package/static/dashboard/assets/dashboard-CbJ-JkrI.css +0 -1
  171. package/static/dashboard/assets/pod-collections-host-DjK2xf-b.js +0 -8
  172. package/static/settings/assets/DevicePages-C6qwvWwu.js +0 -2
  173. package/static/settings/assets/ModelsPage-Ry_dObRQ.js +0 -11
  174. package/static/settings/assets/XpodAiConnectionsPodStore-CyA_BJVC.js +0 -3
  175. package/static/settings/assets/XpodShellApp-Bwom2xL3.css +0 -1
  176. package/static/settings/assets/XpodShellApp-CsivHJl0.js +0 -4
  177. package/static/settings/assets/XpodThemeProvider-CbJ-JkrI.css +0 -1
  178. package/static/settings/assets/auth-callback-GIBYEz_7.js +0 -1
  179. package/static/settings/assets/pod-collections-host-DjK2xf-b.js +0 -8
@@ -1 +1 @@
1
- import{j as e,r as c}from"./dashboard-Or0gnkou.js";import{A as C,r as w,a as A,b as v,c as g,d as y,e as I}from"./safe-continuation-ClWAhcma.js";import{u as E,a as N,s as b,X as T}from"./account-session-DlcKNG7k.js";import{B as i}from"./button-wslF55uZ.js";function X(){const a=E(),s=w(a.controls,a.identity),x=N(a.idpIndex),[p,d]=c.useState(null),[f,m]=c.useState(""),[l,h]=c.useState(!1),u=a.bindAccountCapability,o=p?.record.accountId===s?p:null;c.useEffect(()=>{if(document.title="Xpod · 桌面管理",!s||!u)return;let t=!0;const n=u();return(async()=>{const r=await A({accountId:s},{assertCurrent:n,headers:b({Accept:"application/json"})});if(t)try{n();const j=r??v({accountId:s});d(j?{record:j,assertCurrent:n}:null)}catch{d(null)}})(),()=>{t=!1}},[s,u]);const k=async()=>{if(!o||l)return;h(!0),m("");const{record:t,assertCurrent:n}=o;try{if(n(),t.kind==="consent"){if(!await g(t,{assertCurrent:n,headers:b({Accept:"application/json"})})||!y(t,{accountId:t.accountId},{assertCurrent:n}))throw new Error("expired-task")}else{const r=v({accountId:t.accountId});if(!r||r.createdAt!==t.createdAt||r.returnTo!==t.returnTo)throw new Error("expired-task");if(!I({accountId:t.accountId}))throw new Error("expired-task")}n(),window.location.assign(t.returnTo)}catch{d(null),h(!1),m("原任务已失效,请回到账号或应用重新发起。")}};return e.jsxs("main",{className:"mx-auto flex min-h-screen w-full max-w-2xl flex-col justify-center gap-6 px-6 py-12",children:[e.jsx(T,{size:56}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h1",{className:"text-2xl font-semibold",children:"在桌面 Xpod 中管理"}),e.jsx("p",{className:"text-muted-foreground",children:"Web 提供登录、应用授权、账号管理和快速创建 Pod。管理自己的部署、AI 连接和系统设置,请使用桌面 Xpod。"})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(i,{asChild:!0,children:e.jsx("a",{href:"https://github.com/undefinedsco/xpod/releases/latest",target:"_blank",rel:"noopener noreferrer",children:"下载桌面 Xpod"})}),x?e.jsx(i,{asChild:!0,variant:"outline",children:e.jsx("a",{href:x,children:"账号页面"})}):e.jsx(i,{variant:"outline",disabled:!0,children:"账号页面"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"已安装?打开桌面 Xpod,在其中管理本机部署。"}),o?e.jsxs("section",{"aria-label":"原任务",className:"space-y-3 rounded-xl border border-border bg-card p-4",children:[e.jsx("p",{children:"当前任务保留在这个浏览器标签页中。完成桌面操作后,回到这里继续。"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:o.record.kind==="consent"?"返回授权后重新选择 Pod,再确认授权;也可以在那里取消本次请求。":"返回原来的账号页面查看 Pod。"}),e.jsx(i,{variant:"outline",disabled:l,onClick:()=>{k()},children:l?"正在确认…":o.record.kind==="consent"?"回到授权":"返回账号"})]}):null,f?e.jsx("p",{role:"alert",className:"text-sm text-destructive",children:f}):null]})}function B(){return e.jsx(C,{children:e.jsx(X,{})})}export{X as DesktopEntryContent,B as default};
1
+ import{j as e,r as c}from"./dashboard-vmne1ZE0.js";import{A as C,r as w,a as A,b as v,c as g,d as y,e as I}from"./safe-continuation-BsKjDpAA.js";import{u as E,a as N,s as b,X as T}from"./account-session-rRAOF7nF.js";import{B as i}from"./button-WVnQUNG-.js";function X(){const a=E(),s=w(a.controls,a.identity),x=N(a.idpIndex),[p,d]=c.useState(null),[f,m]=c.useState(""),[l,h]=c.useState(!1),u=a.bindAccountCapability,o=p?.record.accountId===s?p:null;c.useEffect(()=>{if(document.title="Xpod · 桌面管理",!s||!u)return;let t=!0;const n=u();return(async()=>{const r=await A({accountId:s},{assertCurrent:n,headers:b({Accept:"application/json"})});if(t)try{n();const j=r??v({accountId:s});d(j?{record:j,assertCurrent:n}:null)}catch{d(null)}})(),()=>{t=!1}},[s,u]);const k=async()=>{if(!o||l)return;h(!0),m("");const{record:t,assertCurrent:n}=o;try{if(n(),t.kind==="consent"){if(!await g(t,{assertCurrent:n,headers:b({Accept:"application/json"})})||!y(t,{accountId:t.accountId},{assertCurrent:n}))throw new Error("expired-task")}else{const r=v({accountId:t.accountId});if(!r||r.createdAt!==t.createdAt||r.returnTo!==t.returnTo)throw new Error("expired-task");if(!I({accountId:t.accountId}))throw new Error("expired-task")}n(),window.location.assign(t.returnTo)}catch{d(null),h(!1),m("原任务已失效,请回到账号或应用重新发起。")}};return e.jsxs("main",{className:"mx-auto flex min-h-screen w-full max-w-2xl flex-col justify-center gap-6 px-6 py-12",children:[e.jsx(T,{size:56}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h1",{className:"text-2xl font-semibold",children:"在桌面 Xpod 中管理"}),e.jsx("p",{className:"text-muted-foreground",children:"Web 提供登录、应用授权、账号管理和快速创建 Pod。管理自己的部署、AI 连接和系统设置,请使用桌面 Xpod。"})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsx(i,{asChild:!0,children:e.jsx("a",{href:"https://github.com/undefinedsco/xpod/releases/latest",target:"_blank",rel:"noopener noreferrer",children:"下载桌面 Xpod"})}),x?e.jsx(i,{asChild:!0,variant:"outline",children:e.jsx("a",{href:x,children:"账号页面"})}):e.jsx(i,{variant:"outline",disabled:!0,children:"账号页面"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"已安装?打开桌面 Xpod,在其中管理本机部署。"}),o?e.jsxs("section",{"aria-label":"原任务",className:"space-y-3 rounded-xl border border-border bg-card p-4",children:[e.jsx("p",{children:"当前任务保留在这个浏览器标签页中。完成桌面操作后,回到这里继续。"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:o.record.kind==="consent"?"返回授权后重新选择 Pod,再确认授权;也可以在那里取消本次请求。":"返回原来的账号页面查看 Pod。"}),e.jsx(i,{variant:"outline",disabled:l,onClick:()=>{k()},children:l?"正在确认…":o.record.kind==="consent"?"回到授权":"返回账号"})]}):null,f?e.jsx("p",{role:"alert",className:"text-sm text-destructive",children:f}):null]})}function B(){return e.jsx(C,{children:e.jsx(X,{})})}export{X as DesktopEntryContent,B as default};
@@ -0,0 +1,3 @@
1
+ import{ad as bt,ae as P,af as gt,F as g,aa as _,a9 as me,ag as wt,E as Pe,ah as It,a7 as At,ai as _t}from"./xpod-remembered-login-nv1g1sfC.js";const X=["openai","anthropic","kimi","bailian","deepseek","zhipu","ollama","custom"],je={smart:{id:"linx"},fast:{id:"linx-lite"}};function Pt(e,t){const r=e.toLowerCase(),n=je[t].id;return r===n||r===`undefineds/${n}`}const Be={openai:"OpenAI",anthropic:"Anthropic",kimi:"Kimi",bailian:"百炼",deepseek:"DeepSeek",zhipu:"智谱 AI",ollama:"Ollama",custom:"Custom"},He=[{id:"api-platform",label:"API Platform",kind:"api-platform",lifecycle:"active",authModes:["apiKey"]}],Ct={id:"api-key",authMode:"apiKey",lifecycle:"active"},St={id:"browser-login",authMode:"apiKey",connectMode:"browserAssistedApiKey",lifecycle:"active"},D=[Ct,St],B=[{id:"openai-compatible",label:"OpenAI Compatible",kind:"api-platform",lifecycle:"active",authModes:["apiKey"],runtimeProviderIds:["custom"],consoleUrl:"https://undefineds.co",subscriptionUrl:"https://undefineds.co",endpoints:[{protocol:"chatCompletions",baseUrl:"https://example.invalid/v1"}],modelDiscovery:{strategy:"openaiCompatible",path:"/models",endpointProtocol:"chatCompletions"},quota:{strategy:"unsupported",url:"https://undefineds.co"}},{id:"anthropic-compatible",label:"Anthropic Compatible",kind:"api-platform",lifecycle:"active",authModes:["apiKey"],runtimeProviderIds:["custom"],consoleUrl:"https://undefineds.co",subscriptionUrl:"https://undefineds.co",endpoints:[{protocol:"anthropic",baseUrl:"https://example.invalid/v1"}],modelDiscovery:{strategy:"anthropic",path:"/models",endpointProtocol:"anthropic"},quota:{strategy:"unsupported",url:"https://undefineds.co"}}],Ce="https://www.kimi.com/code",Ut="https://www.kimi.com/code/console",Et="https://www.kimi.com/user/agreement",Mt="https://api.kimi.com/coding/v1",kt="https://api.kimi.com/coding/",Rt="https://platform.moonshot.cn/console/api-keys",Se="https://platform.moonshot.cn/console/account",Tt="https://platform.moonshot.cn/docs/intro",Ot="https://api.moonshot.ai/v1",Y="https://bailian.console.aliyun.com/",Z="https://help.aliyun.com/zh/model-studio/",Ue="https://open.bigmodel.cn/usercenter/apikeys",Ee="https://open.bigmodel.cn/",xt="https://open.bigmodel.cn/api/paas/v4",Lt="https://open.bigmodel.cn/api/coding/paas/v4",Ge={openai:[{id:"official-subscription",label:"OpenAI Subscription",kind:"oauth-subscription",lifecycle:"unavailable",authModes:["oauth","local"],productLabel:"OpenAI",runtimeProviderIds:["openai"],credentialPrefixHints:[],consoleUrl:"https://chatgpt.com/codex",subscriptionUrl:"https://chatgpt.com/codex",endpoints:[{protocol:"responses",baseUrl:"https://chatgpt.com/backend-api/codex"}],modelDiscovery:{strategy:"unsupported",path:"/models",endpointProtocol:"responses"},quota:{strategy:"subscription",url:"https://chatgpt.com/codex"},usagePolicyUrl:"https://openai.com/policies/usage-policies/",region:"global"},{id:"api-platform",label:"API Platform",kind:"api-platform",lifecycle:"active",authModes:["apiKey"],authorizationMethods:D,productLabel:"OpenAI",runtimeProviderIds:["openai"],credentialPrefixHints:["sk-"],consoleUrl:"https://platform.openai.com/api-keys",subscriptionUrl:"https://platform.openai.com/settings/organization/billing/overview",endpoints:[{protocol:"responses",baseUrl:"https://api.openai.com/v1"},{protocol:"chatCompletions",baseUrl:"https://api.openai.com/v1"}],modelDiscovery:{strategy:"openaiCompatible",path:"/models",endpointProtocol:"responses"},quota:{strategy:"providerApi",url:"https://platform.openai.com/usage"},usagePolicyUrl:"https://openai.com/policies/usage-policies/",region:"global"}],anthropic:[{id:"official-subscription",label:"Claude Pro / Max",kind:"oauth-subscription",lifecycle:"unavailable",authModes:["oauth"],authorizationMethods:[],productLabel:"Claude Code",runtimeProviderIds:["anthropic"],credentialPrefixHints:[],consoleUrl:"https://claude.ai/",subscriptionUrl:"https://claude.com/pricing",endpoints:[],modelDiscovery:{strategy:"unsupported",path:"/models",endpointProtocol:"anthropic"},quota:{strategy:"subscription",url:"https://claude.ai/settings/usage"},usagePolicyUrl:"https://www.anthropic.com/legal/aup",region:"global"},{id:"api-platform",label:"API Platform",kind:"api-platform",lifecycle:"active",authModes:["apiKey"],authorizationMethods:D,productLabel:"Anthropic",runtimeProviderIds:["anthropic"],credentialPrefixHints:["sk-ant-"],consoleUrl:"https://console.anthropic.com/settings/keys",subscriptionUrl:"https://console.anthropic.com/settings/plans",endpoints:[{protocol:"anthropic",baseUrl:"https://api.anthropic.com/v1"}],modelDiscovery:{strategy:"anthropic",path:"/models",endpointProtocol:"anthropic"},quota:{strategy:"console",url:"https://console.anthropic.com/settings/limits"},usagePolicyUrl:"https://www.anthropic.com/legal/aup",region:"global"}],kimi:[Me({id:"subscription-key",label:"Token Plan",kind:"token-plan",authModes:["apiKey"],productLabel:"Kimi Coding",runtimeProviderIds:["kimi"],credentialPrefixHints:["sk-kimi-"],baseUrl:Mt,anthropicBaseUrl:kt,quotaStrategy:"subscription",quotaUrl:Ce,consoleUrl:Ut,subscriptionUrl:Ce,usagePolicyUrl:Et,supportsDeveloperMessages:!1}),Me({id:"api-platform",label:"API Platform",kind:"api-platform",authModes:["apiKey"],productLabel:"Moonshot AI",runtimeProviderIds:["kimi"],credentialPrefixHints:["sk-"],baseUrl:Ot,quotaStrategy:"console",quotaUrl:Se,consoleUrl:Rt,subscriptionUrl:Se,usagePolicyUrl:Tt})],bailian:[Q({id:"pay-as-you-go",label:"Pay as You Go",kind:"api-platform",runtimeProviderIds:["bailian"],credentialPrefixHints:["sk-"],region:"cn",baseUrl:"https://dashscope.aliyuncs.com/compatible-mode/v1",anthropicBaseUrl:"https://dashscope.aliyuncs.com/apps/anthropic",quotaStrategy:"console",consoleUrl:Y,usagePolicyUrl:Z}),Q({id:"token-plan",label:"Token Plan Personal",kind:"token-plan",runtimeProviderIds:["bailian-token-plan"],credentialPrefixHints:["sk-"],region:"cn-beijing",baseUrl:"https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",anthropicBaseUrl:"https://token-plan.cn-beijing.maas.aliyuncs.com/apps/anthropic",quotaStrategy:"subscription",consoleUrl:Y,usagePolicyUrl:Z}),Q({id:"token-plan-team",label:"Token Plan Team",kind:"token-plan",runtimeProviderIds:["bailian-token-plan"],credentialPrefixHints:["sk-"],region:"cn-beijing",baseUrl:"https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",anthropicBaseUrl:"https://token-plan.cn-beijing.maas.aliyuncs.com/apps/anthropic",quotaStrategy:"subscription",consoleUrl:Y,usagePolicyUrl:Z}),Q({id:"coding-plan",label:"Coding Plan Pro",kind:"token-plan",runtimeProviderIds:["bailian-coding-plan"],credentialPrefixHints:["sk-sp-"],region:"cn",baseUrl:"https://coding.dashscope.aliyuncs.com/v1",anthropicBaseUrl:"https://coding.dashscope.aliyuncs.com/apps/anthropic",quotaStrategy:"subscription",consoleUrl:Y,usagePolicyUrl:Z})],deepseek:[{id:"api-platform",label:"API Platform",kind:"api-platform",lifecycle:"active",authModes:["apiKey"],productLabel:"DeepSeek",runtimeProviderIds:["deepseek"],credentialPrefixHints:["sk-"],consoleUrl:"https://platform.deepseek.com/api_keys",subscriptionUrl:"https://platform.deepseek.com/usage",endpoints:[{protocol:"chatCompletions",baseUrl:"https://api.deepseek.com/v1"}],modelDiscovery:{strategy:"openaiCompatible",path:"/models",endpointProtocol:"chatCompletions"},quota:{strategy:"console",url:"https://platform.deepseek.com/usage"},usagePolicyUrl:"https://cdn.deepseek.com/policies/en-US/deepseek-open-platform-terms-of-use.html",region:"global"}],ollama:[{id:"local",label:"Local Ollama",kind:"local",lifecycle:"active",authModes:["local"],productLabel:"Ollama",runtimeProviderIds:["ollama"],credentialPrefixHints:[],consoleUrl:"https://ollama.com",subscriptionUrl:"https://ollama.com",endpoints:[{protocol:"chatCompletions",baseUrl:"http://localhost:11434/v1"}],modelDiscovery:{strategy:"openaiCompatible",path:"/models",endpointProtocol:"chatCompletions"},quota:{strategy:"unsupported",url:"https://ollama.com"},usagePolicyUrl:"https://ollama.com",region:"local"}],zhipu:[{id:"api-platform",label:"API Platform",kind:"api-platform",lifecycle:"active",authModes:["apiKey"],authorizationMethods:D,productLabel:"智谱 AI",runtimeProviderIds:["zhipu"],credentialPrefixHints:["id."],consoleUrl:Ue,subscriptionUrl:"https://open.bigmodel.cn/finance-center/expense-manage",endpoints:[{protocol:"chatCompletions",baseUrl:xt,region:"cn"}],modelDiscovery:{strategy:"openaiCompatible",path:"/models",endpointProtocol:"chatCompletions"},quota:{strategy:"console",url:"https://open.bigmodel.cn/finance-center/expense-manage"},usagePolicyUrl:Ee,region:"cn"},{id:"coding-plan",label:"GLM Coding Plan",kind:"token-plan",lifecycle:"active",authModes:["apiKey"],authorizationMethods:D,productLabel:"智谱 AI",runtimeProviderIds:["zhipu"],credentialPrefixHints:["id."],consoleUrl:Ue,subscriptionUrl:"https://bigmodel.cn/glm-coding",endpoints:[{protocol:"chatCompletions",baseUrl:Lt,region:"cn"}],modelDiscovery:{strategy:"openaiCompatible",path:"/models",endpointProtocol:"chatCompletions"},quota:{strategy:"subscription",url:"https://bigmodel.cn/glm-coding"},usagePolicyUrl:Ee,region:"cn"}]};function Me(e){return{id:e.id,label:e.label,kind:e.kind,lifecycle:"active",authModes:e.authModes,authorizationMethods:D,productLabel:e.productLabel,runtimeProviderIds:e.runtimeProviderIds,credentialPrefixHints:e.credentialPrefixHints,consoleUrl:e.consoleUrl,subscriptionUrl:e.subscriptionUrl,endpoints:Ve(e.baseUrl,e.anthropicBaseUrl,"cn",e.supportsDeveloperMessages),modelDiscovery:{strategy:"openaiCompatible",path:"/models",endpointProtocol:"chatCompletions"},quota:{strategy:e.quotaStrategy,url:e.quotaUrl},usagePolicyUrl:e.usagePolicyUrl,region:"cn"}}function Q(e){return{id:e.id,label:e.label,lifecycle:"active",productLabel:"Alibaba Bailian",kind:e.kind,authModes:["apiKey"],authorizationMethods:D,runtimeProviderIds:e.runtimeProviderIds,credentialPrefixHints:e.credentialPrefixHints,consoleUrl:e.consoleUrl,subscriptionUrl:e.consoleUrl,endpoints:Ve(e.baseUrl,e.anthropicBaseUrl,e.region),modelDiscovery:{strategy:"openaiCompatible",path:"/models",endpointProtocol:"chatCompletions"},quota:{strategy:e.quotaStrategy,url:e.consoleUrl},usagePolicyUrl:e.usagePolicyUrl,region:e.region}}function Ve(e,t,r,n){return[{protocol:"chatCompletions",baseUrl:e,region:r,...n===void 0?{}:{supportsDeveloperMessages:n}},...t?[{protocol:"anthropic",baseUrl:t,region:r}]:[]]}function We(e,t=!1){return(Ge[e]??He).map(r=>e==="openai"&&r.id==="official-subscription"&&t?{...r,lifecycle:"active",authModes:Array.from(new Set([...r.authModes??[],"local"])),authorizationMethods:[{id:"device-code",authMode:"deviceCode",connectMode:"deviceCodeOAuth",lifecycle:"active"},{id:"local-session-import",authMode:"local",lifecycle:"active"}]}:{...r})}const pn=X.flatMap(e=>[e,...$t(e).map(t=>`${e}-${t.id}`)]);function $t(e){return e==="custom"?B:Ge[e]??He}function vt(e,t){return e==="anthropic"||t==="anthropic-compatible"?"anthropic":"openai"}function G(e,t){return e==="openai"&&(t==="local"||t==="oauth"||t==="deviceCode")?"official-subscription":e==="kimi"&&(t==="oauth"||t==="deviceCode")?"subscription-key":e==="bailian"?"pay-as-you-go":e==="ollama"?"local":e==="custom"?"openai-compatible":"api-platform"}function ke(e,t){const r=We(e).find(i=>i.id===(t??G(e,"apiKey")));if(!r)return;const n=r.modelDiscovery?.endpointProtocol;return r.endpoints?.find(i=>i.protocol===n)?.baseUrl??r.endpoints?.[0]?.baseUrl}function ee(e,t){const r=t.trim().toLowerCase();if(e==="bailian"){if(r==="token-plan-personal")return"token-plan";if(r==="coding-plan-pro")return"coding-plan"}return r}function te(e){return{offeringId:e.offeringId,priority:e.priority??100,enabled:e.enabled??!0,health:e.health??"unknown",...e.baseUrl?{baseUrl:e.baseUrl}:{}}}function fn(e){if(e==null||!e.trim())return;let t;try{t=new URL(e.trim())}catch{throw new Error("invalid_proxy_url")}if(!["http:","https:"].includes(t.protocol)||t.username||t.password||t.hash)throw new Error("invalid_proxy_url");if(!t.hostname)throw new Error("invalid_proxy_url");return t.href.replace(/\/$/u,"")}class F extends Error{constructor(t,r,n={}){const i=Je(t);super(i?`AI Connection request failed: ${i}`:`AI Connection request failed (HTTP ${r})`),this.name="AiConnectionsRequestError",this.code=i,this.status=r,this.providerStatus=I(t)&&typeof t.providerStatus=="number"?t.providerStatus:void 0,this.payload=t,this.provider=n.provider,this.authMode=n.authMode}}function Je(e){if(I(e)){if(typeof e.code=="string")return e.code;if(typeof e.errorCode=="string")return e.errorCode;if(typeof e.error=="string"&&/^[a-z][a-z0-9_:-]{0,80}$/i.test(e.error))return e.error}}async function Re(e){const t=await e.text();if(t)try{return JSON.parse(t)}catch{throw new Error(`AI Connection returned invalid JSON (${e.status})`)}}function Nt(e){if(!X.includes(e))throw new Error(`Unsupported AI provider: ${e}`)}function Te(e){if(!Array.isArray(e))throw new Error("AI Connection returned an invalid custom models response");const t=[];for(const r of e)!I(r)||typeof r.id!="string"||!r.id||t.push(A({id:r.id,displayName:y(r.displayName),inputModalities:V(r.inputModalities),outputModalities:V(r.outputModalities),capabilities:V(r.capabilities)}));return t}function V(e){if(!Array.isArray(e))return;const t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}function Xe(e){if(!I(e)||typeof e.id!="string"||Dt(e.id))return;const t=k(e.provider)??k(e.providerId)??k(e.owned_by)??Ft(e.id);if(!t)return;const r=I(e.capabilities)?e.capabilities.imageInput:void 0;return A({id:e.id,provider:t,offeringId:y(e.offeringId),resourceId:y(e.resourceId),displayName:y(e.displayName)??y(e.display_name)??y(e.name),modelType:typeof e.modelType=="string"&&Object.prototype.hasOwnProperty.call(bt,e.modelType)?e.modelType:void 0,contextWindow:le(e.contextWindow)??le(e.context_window),dimension:typeof e.dimension=="number"&&Number.isInteger(e.dimension)&&e.dimension>0?e.dimension:void 0,protocols:Array.isArray(e.protocols)?e.protocols.filter(n=>typeof n=="string"):void 0,custom:e.custom===!0?!0:void 0,inputModalities:Oe(e.modalities,"input")??(r===!0?["text","image"]:r===!1?["text"]:void 0),outputModalities:Oe(e.modalities,"output"),capabilities:qt(e)})}function zt(e){if(!(!I(e)||typeof e.id!="string"||!e.id))return A({id:e.id,displayName:y(e.displayName)??y(e.display_name)??y(e.name),provider:y(e.provider)??y(e.providerId)??y(e.owned_by)})}function Oe(e,t){if(!I(e))return;const r=e[t];if(!Array.isArray(r))return;const n=r.filter(i=>typeof i=="string");return n.length>0?n:void 0}function qt(e){if(Array.isArray(e.custom_capabilities)){const r=e.custom_capabilities.filter(n=>typeof n=="string");if(r.length>0)return r}if(!I(e.capabilities))return;const t=[];return e.capabilities.imageInput===!0&&t.push("image"),e.capabilities.toolCalls===!0&&t.push("tool_call"),e.capabilities.reasoningEffort===!0&&t.push("reasoning"),e.capabilities.fast===!0&&t.push("fast"),e.capabilities.embedding===!0&&t.push("embedding"),t.length>0?t:void 0}function Dt(e){return Object.keys(je).some(t=>Pt(e,t))}function k(e){if(typeof e!="string")return;const t=e.toLowerCase().trim();return t==="alibaba"||t==="dashscope"||t==="alibaba-bailian"||t==="bailian-coding-plan"||t==="bailian-token-plan"?"bailian":X.includes(t)?t:void 0}function Ft(e){const t=e.split("/",1)[0];return e.includes("/")?k(t):void 0}function le(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Kt(e){const t=new Map;for(const r of e){const n=jt(r);if(!n)continue;const i=t.get(n.id);t.set(n.id,i?Qt(i,n):n)}return[...t.values()]}function jt(e){return Ht(e)??Bt(e)}function Bt(e){if(!I(e)||typeof e.provider!="string"||!yr(e.status)||!I(e.connect)||!Array.isArray(e.connect.modes)||!e.connect.modes.every(he)||typeof e.connect.configured!="boolean")return;const t=k(e.provider);if(!t)return;const r=nr(e,t);return{id:t,name:nt(t),offerings:[],credentials:r?[r]:[],selectedModels:[],status:tr(e.status)}}function Ht(e){if(!I(e))return;const t=k(e.id)??k(e.provider);if(!t||!sr(e.status))return;const r=R(e.offerings,Gt),n=R(e.credentials,H),i=R(e.selectedModels,Xe);return{id:t,name:y(e.name)??nt(t),offerings:r,credentials:n,selectedModels:i,status:e.status}}function Gt(e){if(!I(e)||typeof e.id!="string"||!e.id)return;const t=R(e.authModes,tt);return A({id:e.id,label:y(e.label),kind:y(e.kind),lifecycle:Jt(e.lifecycle),authModes:t,authorizationMethods:R(e.authorizationMethods,Ye),runtimeProviderIds:V(e.runtimeProviderIds),productLabel:y(e.productLabel),credentialPrefixHints:V(e.credentialPrefixHints),consoleUrl:y(e.consoleUrl),subscriptionUrl:y(e.subscriptionUrl),endpoints:R(e.endpoints,Ze),modelDiscovery:Xt(e.modelDiscovery),quota:Yt(e.quota),usagePolicyUrl:y(e.usagePolicyUrl),region:y(e.region)})}function Vt(e){if(!I(e)||typeof e.offeringId!="string"||!e.offeringId)return;const t=k(e.provider);if(!t)return;const r=R(e.authorizationMethods,Ye);return{provider:t,offeringId:e.offeringId,...Array.isArray(e.endpoints)?{endpoints:R(e.endpoints,Ze)}:{},authorizationMethods:r}}function Ye(e){if(!I(e)||typeof e.id!="string"||!e.id)return;const t=tt(e.authMode),r=Wt(e.lifecycle);if(!t||!r)return;const n=he(e.connectMode)?e.connectMode:void 0;return A({id:e.id,authMode:t,connectMode:n,label:y(e.label),lifecycle:r,reason:y(e.reason)})}function Wt(e){return e==="active"||e==="unavailable"?e:void 0}function Jt(e){return e==="active"||e==="legacy"||e==="unavailable"?e:void 0}function Ze(e){if(!I(e))return;const t=y(e.protocol),r=y(e.baseUrl);if(!(!t||!r))return A({protocol:t,baseUrl:r,region:y(e.region)})}function Xt(e){if(!I(e))return;const t=y(e.strategy),r=y(e.path),n=y(e.endpointProtocol);return t&&r&&n?{strategy:t,path:r,endpointProtocol:n}:void 0}function Yt(e){if(!I(e))return;const t=y(e.strategy),r=y(e.url);return t&&r?{strategy:t,url:r}:void 0}function H(e){if(!(!I(e)||typeof e.id!="string"||!e.id||typeof e.offeringId!="string"||!e.offeringId||!rt(e.authMode)||typeof e.enabled!="boolean"||typeof e.priority!="number"||!Number.isFinite(e.priority)||!ar(e.health)||typeof e.version!="number"||!Number.isFinite(e.version)))return A({id:e.id,provider:k(e.provider),offeringId:e.offeringId,authMode:e.authMode,label:y(e.label),enabled:e.enabled,priority:e.priority,health:e.health,maskedHint:y(e.maskedHint),baseUrl:y(e.baseUrl),proxyUrl:y(e.proxyUrl),expiresAt:y(e.expiresAt),lastFailureCode:y(e.lastFailureCode),lastFailureAt:y(e.lastFailureAt),rateLimitResetAt:y(e.rateLimitResetAt),failCount:le(e.failCount),version:e.version})}function Qe(e){return I(e)?Object.fromEntries(Object.entries(e).filter(([t])=>!Zt(t)).map(([t,r])=>[t,et(r)])):{}}function et(e){return Array.isArray(e)?e.map(et):I(e)?Qe(e):e}function Zt(e){const t=e.toLocaleLowerCase();return t.includes("secret")||t.includes("token")||t.includes("apikey")||t==="api_key"||t==="key"||t==="authorization"}function Qt(e,t){const r=oe([...e.credentials,...t.credentials],o=>o.id),n=oe([...e.offerings,...t.offerings],o=>o.id),i=oe([...e.selectedModels,...t.selectedModels],er);return{id:e.id,name:e.name??t.name,offerings:n,credentials:r,selectedModels:i,status:rr(e.status,t.status)}}function er(e){return e.resourceId??`${e.provider}:${e.offeringId??""}:${e.id}`}function tr(e){return e==="connected"?"available":e==="reauthRequired"?"attention":"unconfigured"}function rr(e,t){return e==="available"||t==="available"?"available":e==="attention"||t==="attention"?"attention":e==="configured"||t==="configured"?"configured":e==="unconfigured"||t==="unconfigured"?"unconfigured":"unavailable"}function nr(e,t){if(e.status==="disconnected")return;const r=ir(e.authMode);return A({id:y(e.credentialIri)??`${t}:current`,offeringId:or(t,r),authMode:r,label:y(e.accountLabel),enabled:e.status==="connected",priority:0,health:e.status==="reauthRequired"||e.reauthRequired===!0?"expired":"healthy",maskedHint:y(e.maskedHint),baseUrl:y(e.baseUrl),proxyUrl:y(e.proxyUrl),expiresAt:y(e.expiresAt),version:typeof e.version=="number"?e.version:0})}function ir(e){return e==="deviceCodeOAuth"?"deviceCode":"apiKey"}function or(e,t){return e==="kimi"&&(t==="deviceCode"||t==="oauth")?"subscription-key":t==="deviceCode"||t==="oauth"?"official-subscription":"api-platform"}function tt(e){return rt(e)?e:void 0}function rt(e){return e==="oauth"||e==="deviceCode"||e==="apiKey"||e==="local"}function ar(e){return e==="healthy"||e==="expired"||e==="invalid"||e==="unknown"}function sr(e){return e==="unconfigured"||e==="configured"||e==="available"||e==="attention"||e==="unavailable"}function R(e,t){return Array.isArray(e)?e.map(t).filter(W):[]}function oe(e,t){const r=new Set,n=[];for(const i of e){const o=t(i);r.has(o)||(r.add(o),n.push(i))}return n}function nt(e){return Be[e]}function cr(e){if(!I(e)||typeof e.id!="string"||typeof e.credentialIri!="string"||typeof e.webId!="string"||typeof e.provider!="string"||typeof e.authMode!="string"||typeof e.status!="string")return;const t=k(e.provider);if(t)return A({id:e.id,credentialIri:e.credentialIri,webId:e.webId,provider:t,authMode:e.authMode,status:e.status,accountLabel:y(e.accountLabel),expiresAt:y(e.expiresAt),version:typeof e.version=="number"?e.version:void 0,reauthRequired:typeof e.reauthRequired=="boolean"?e.reauthRequired:void 0})}function dr(e,t){if(!I(e)||!he(e.mode)||!fr(e.status)||e.provider!==t)throw new Error("AI Connection returned an invalid Connect response");return A({mode:e.mode,status:e.status,provider:t,attemptId:y(e.attemptId),state:y(e.state),signature:y(e.signature),expiresAt:y(e.expiresAt),authorizationUrl:ae(e.authorizationUrl),userCode:y(e.userCode),verificationUri:ae(e.verificationUri),verificationUriComplete:ae(e.verificationUriComplete),intervalSeconds:typeof e.intervalSeconds=="number"?e.intervalSeconds:void 0,apiKeyManagementSupported:typeof e.apiKeyManagementSupported=="boolean"?e.apiKeyManagementSupported:void 0,credentialId:y(e.credentialId),offeringId:y(e.offeringId),authorizationMethodId:y(e.authorizationMethodId),oauthCredential:lr(e.oauthCredential),message:y(e.message)})}function lr(e){if(e!==void 0){if(!I(e)||typeof e.accessToken!="string"||!e.accessToken||typeof e.refreshToken!="string"||!e.refreshToken)throw new Error("AI Connection returned an invalid OAuth credential payload");return A({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:y(e.expiresAt),scope:y(e.scope),idToken:y(e.idToken),accountSubject:y(e.accountSubject),accountId:y(e.accountId),accountLabel:y(e.accountLabel),offeringId:y(e.offeringId),authorizationMethodId:y(e.authorizationMethodId),expectedVersion:typeof e.expectedVersion=="number"?e.expectedVersion:void 0})}}function ur(e,t){if(!I(e)||!Array.isArray(e.models))throw new Error("AI Connection returned an invalid model discovery response");const r=e.models.map(n=>{if(!I(n)||typeof n.id!="string"||!n.id)return;const i=Array.isArray(n.capabilities)?n.capabilities.filter(c=>typeof c=="string"):void 0,o=pr(n.modelType);return A({id:n.id,displayName:y(n.displayName),capabilities:i??(o==="embedding"?["embedding"]:void 0),modelType:o})}).filter(W);return{provider:t,credential:typeof e.credential=="string"?e.credential:"",models:r,observedAt:typeof e.observedAt=="string"?e.observedAt:new Date(0).toISOString(),source:typeof e.source=="string"?e.source:""}}function A(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function pr(e){return e==="chat"||e==="embedding"?e:void 0}function y(e){return typeof e=="string"?e:void 0}function ae(e){if(typeof e=="string")try{const t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"?t.href:void 0}catch{return}}function he(e){return e==="browserAssistedApiKey"||e==="deviceCodeOAuth"||e==="authorizationCodeOAuth"||e==="connectUnsupported"}function fr(e){return e==="pending"||e==="authorization_pending"||e==="slow_down"||e==="completed"||e==="expired"||e==="cancelled"||e==="unsupported"}function yr(e){return e==="connected"||e==="disconnected"||e==="reauthRequired"}function I(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function W(e){return e!==void 0}async function mr(e){const t=globalThis.crypto?.subtle;if(!t)return;const r=await t.digest("SHA-256",new TextEncoder().encode(e));return[...new Uint8Array(r)].map(n=>n.toString(16).padStart(2,"0")).join("")}function be(e){const t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw new Error("Current Pod URL must use HTTP or HTTPS");return t.origin}function hr({webId:e,podBaseUrl:t,authenticatedFetch:r,clientCredentials:n}){const i=be(t),o=()=>{if(!n)throw new F({code:"account_client_credentials_unavailable"},0);return n},c=new Map,l=(a,s={})=>({id:a.clientId,kind:"client-credentials",credentialResource:a.resource,clientCredentialId:a.clientId,...s.fingerprint?{fingerprint:s.fingerprint}:{},owner:a.webId??e,name:s.name??a.label??a.clientId,plaintextAvailable:!1}),p=async(a,s,m,w={})=>{const C=await r(`${i}${a}`,{method:s,credentials:"omit",mode:"cors",headers:{accept:"application/json","X-Xpod-Pod-Url":t,...m?{"content-type":"application/json"}:{}},...m?{body:JSON.stringify(m)}:{}}),U=await Re(C);if(!C.ok)throw new F(U,C.status,w);return U},d=a=>(Nt(a),`/api/ai/gateway/providers/${a}`),u=async(a,s,m,w)=>{const C=await p(`${d(a)}${s}`,m,w,{provider:a});return dr(C,a)},b=()=>p("/v1/models","GET"),h=async()=>{const a=await b();return Array.isArray(a.data)?a.data.map(Xe).filter(W):[]};return{webId:e,apiBase:i,getServiceAccess(){return p("/api/applets/service-access/ai-connections","GET")},async listProviders(){const a=await p("/api/ai/providers","GET");return Array.isArray(a.data)?Kt(a.data):[]},async listAuthorizationMethods(){const a=await r(`${i}/api/ai/connections/authorization-methods`,{method:"GET",credentials:"omit",mode:"cors",headers:{accept:"application/json"}});if(a.status===404)return[];const s=await Re(a);if(!a.ok)throw new F(s,a.status);return I(s)&&Array.isArray(s.data)?s.data.map(Vt).filter(W):[]},listModels:h,listGatewayModels:h,async listGatewayCatalogModels(){const a=await b();if(!I(a)||!Array.isArray(a.data))throw new Error("AI Connection returned an invalid Gateway model catalog response");return a.data.map(zt).filter(W)},async listGatewayKeys(){return(await o().list()).filter(s=>s.webId===e).map(s=>l(s,{fingerprint:c.get(s.clientId)}))},async createGatewayKey(a){const s=await o().create({name:a.name,webId:e}),m=await mr(s.apiKey);return m&&c.set(s.clientId,m),{plaintext:s.apiKey,record:{...l({clientId:s.clientId,label:a.name,resource:s.resource,webId:e},{name:a.name,fingerprint:m}),plaintextAvailable:void 0,...a.appliedTo?{appliedTo:a.appliedTo}:{}}}},async deleteGatewayKey(a){const s=o(),m=(await s.list()).find(w=>w.clientId===a&&w.webId===e);if(!m)throw new F({code:"account_client_credential_not_found"},0);await s.revoke({clientId:m.clientId,resource:m.resource,webId:e})},async beginConnect(a,s,m){return await u(a,"/connect/begin","POST",A({mode:s,offeringId:m?.offeringId,authorizationMethodId:m?.authorizationMethodId}))},connectStatus(a,s){if(!s.attemptId)throw new Error("Connect attempt id is required");const m=new URLSearchParams({state:s.state??"",signature:s.signature??""});return s.mode&&m.set("mode",s.mode),u(a,`/connect/status/${encodeURIComponent(s.attemptId)}?${m}`,"GET")},completeApiKey(a,s,m,w,C){return u(a,"/connect/complete-api-key","POST",A({attemptId:s.attemptId,state:s.state,signature:s.signature,offeringId:s.offeringId,apiKey:m,accountLabel:w,baseUrl:C}))},pollDevice(a,s){return u(a,"/connect/poll","POST",A({mode:s.mode,attemptId:s.attemptId,state:s.state,signature:s.signature,offeringId:s.offeringId}))},cancelConnect(a,s){return u(a,"/connect/cancel","POST",A({mode:s.mode,attemptId:s.attemptId,state:s.state,signature:s.signature,offeringId:s.offeringId}))},refreshOAuthCredential(a,s,m,w,C,U){return u(a,"/connect/refresh","POST",{credentialId:s,refreshToken:m,expectedVersion:w,...C?{offeringId:C}:{},...U?{mode:U}:{}})},async disconnect(a,s){const m=s?`?${new URLSearchParams({credentialId:s})}`:"",w=await p(`${d(a)}/connect${m}`,"DELETE");return cr(w.record)},async createApiKeyCredential(a,s){const m=await p(`/api/ai/providers/${a}/credentials/api-key`,"POST",A({...s}),{provider:a}),w=H(m.credential);if(!w)throw new Error("AI Connection returned an invalid Provider credential");return w},async createLocalCredential(a,s){const m=await p(`/api/ai/providers/${a}/credentials/local`,"POST",A(s),{provider:a}),w=H(m.credential);if(!w)throw new Error("AI Connection returned an invalid Provider credential");return w},async updateProviderCredential(a,s,m){const w=await p(`/api/ai/providers/${a}/credentials/${encodeURIComponent(s)}`,"PATCH",A({...m}),{provider:a}),C=H(w.credential);if(!C)throw new Error("AI Connection returned an invalid Provider credential");return C},async deleteProviderCredential(a,s){const m=await p(`/api/ai/providers/${a}/credentials/${encodeURIComponent(s)}`,"DELETE",void 0,{provider:a});return H(m.credential)},async testProviderCredential(a,s){const m=await p(`/api/ai/providers/${a}/credentials/test`,"POST",A({...s}),{provider:a});return Qe(m.result)},quota(a,s=!1,m){const w=!s&&m?.credentialIri?`?credentialIri=${encodeURIComponent(m.credentialIri)}${m.offeringId?`&offeringId=${encodeURIComponent(m.offeringId)}`:""}`:"";return p(`${d(a)}/quota/${s?"refresh":"status"}${w}`,s?"POST":"GET",s?A({offeringId:m?.offeringId,credentialId:m?.credentialId,credentialIri:m?.credentialIri}):void 0,{provider:a})},quotaFromSecret(a,s){return p(`${d(a)}/quota/refresh`,"POST",A(s),{provider:a})},async discoverModels(a,s){const m=await p(`${d(a)}/models/refresh`,"POST",A({...s}),{provider:a,authMode:s?.authMode});return ur(m,a)},async saveProviderModel(a,s){const m=await p(d(a)+"/models","POST",A({id:s.id,displayName:s.displayName,inputModalities:s.inputModalities,outputModalities:s.outputModalities,capabilities:s.capabilities}),{provider:a});return Te(m.data)},async deleteProviderModel(a,s){const m=await p(`${d(a)}/models/${encodeURIComponent(s)}`,"DELETE",void 0,{provider:a});return Te(m.data)}}}function br(e){const t=new TextEncoder().encode(JSON.stringify(e));let r="";for(const n of t)r+=String.fromCharCode(n);return btoa(r)}function gr(e){const t=atob(e),r=Uint8Array.from(t,n=>n.charCodeAt(0));return JSON.parse(new TextDecoder().decode(r))}function wr(e){return JSON.stringify({algorithm:"PLAINTEXT",encoding:"base64",ciphertext:br(e.secret),webId:e.webId,credentialIri:e.credentialIri,provider:e.provider})}function Ir(e){if(!(typeof e.envelope!="string"||!e.envelope.trim()))try{const t=JSON.parse(e.envelope);if(t.algorithm!=="PLAINTEXT"||t.webId!==e.webId||t.provider!==e.provider||t.credentialIri!==e.credentialIri)return;const r=t.encoding==="base64"?gr(String(t.ciphertext)):JSON.parse(String(t.ciphertext));return typeof r=="object"&&r!==null&&!Array.isArray(r)?r:void 0}catch{return}}function Ar(e){return P.buildId({id:e})}function _r(e){return P.buildId({id:`custom-instance-${encodeURIComponent(e)}.ttl#this`})}function xe(e,t){const r=crypto.randomUUID();return t==="local"?`${e}-local-${r}`:`${e}-${r}`}function yn(e){const t=(e.split("#",1)[0]??e).split("/").filter(Boolean).at(-1)??"",r=t.endsWith(".ttl")?t.slice(0,-4):t;if(r)return r.startsWith("custom-")||r==="custom"?"custom":X.find(n=>r===n||r.startsWith(`${n}-`))}function $(e){if(!e)return;const t=e.split("#",1)[0]??e,r=t.split("/").filter(Boolean).at(-1)??t;if(!r)return;const n=r.endsWith(".ttl")?r:`${r}.ttl`,i=e.indexOf("#");return i<0?n:`${n}${e.slice(i)}`}function T(e){const t=$(e);if(t)return(t.split("#",1)[0]??t).replace(/\.ttl$/u,"")}const it="AI Connection request failed. Please try again.";function re(e){return typeof e=="object"&&e!==null}const ot="订阅登录态自动刷新失败,请稍后重试。",at="订阅登录态已失效,请在原客户端重新登录后重读,或使用设备码登录。",st="模型服务请求超时。请检查网络或代理设置,稍后重试同步模型。",ct="订阅登录态不可用,请重读登录态或重新登录后再同步模型。",dt=new Set([st,ct,ot,at,"密钥不可用。请检查密钥是否填写正确,或换一个密钥后重试。","模型服务地址不正确。请检查服务地址后重试。","请求太频繁。请稍等一会儿再试。","模型服务暂时没有响应。请稍后重试。","模型列表获取失败。请检查密钥、服务地址或网络后重试。"]);function Le(e){if(e.startsWith("provider_models_response_error:"))return ge(e.slice(31))??"模型列表获取失败。请检查密钥、服务地址或网络后重试。";const t=ne(e);if(t)return t;const r=e.split(":",1)[0]?.trim(),n=r?ne(r):void 0;return n||(e==="AI Connection service identity is unavailable"||dt.has(e)||Er(e)?e:e.startsWith("invalid_")?"AI Connection returned an invalid response.":it)}function Pr(e){return e instanceof F?Cr(e.payload,e.status,{provider:e.provider,authMode:e.authMode}):e instanceof Error?Le(e.message):Le(String(e))}function Cr(e,t,r={}){const n=Je(e);if(n==="provider_models_response_error"){const c=re(e)&&typeof e.message=="string"?ge(e.message):void 0;return c||"模型列表获取失败。请检查密钥、服务地址或网络后重试。"}if(n==="provider_models_fetch_failed"){const c=re(e)&&typeof e.providerStatus=="number"?e.providerStatus:void 0,l=re(e)&&typeof e.providerMessage=="string"?e.providerMessage.trim():void 0;return Ur(Sr(c,r.authMode),l)}const i=n?ne(n,r.provider):void 0;if(i)return i;const o=re(e)&&typeof e.error=="string"?e.error:void 0;if(o){const c=ne(o,r.provider);if(c)return c;if(o==="AI Connection service identity is unavailable")return o;if(o==="Provider credential not found for current identity")return"当前身份没有可用的额度凭证。";if(o==="Provider quota adapter not found"||o==="Provider quota lookup failed")return"该接入方式不支持查询官方额度。"}return t===401?"Please sign in again to continue.":t===403?"AI Connection permission was denied.":t===404&&r.provider?`${ue(r.provider)} connection is not configured.`:t===429?"AI Connection is rate limited. Please try again later.":t===503?"AI Connection service is unavailable.":it}function ne(e,t){switch(e.trim().toLowerCase().replace(/-/g,"_")){case"not_configured":case"notconfigured":return t?`${ue(t)} connection is not configured.`:"AI provider connection is not configured.";case"unsupported":return t?`${ue(t)} does not support this operation.`:"This AI Connection operation is not supported.";case"service_access_missing":case"pod_interface_key_missing":case"pod_interface_key_rejected":case"caller_dpop_replay_unsupported":return"Xpod 尚未获准访问这个 Pod,请到 Pod 的授权应用中允许 Xpod 访问。";case"unauthorized":return"Please sign in again to continue.";case"forbidden":case"permission_denied":return"AI Connection permission was denied.";case"rate_limited":return"AI Connection is rate limited. Please try again later.";case"service_unavailable":return"AI Connection service is unavailable.";case"unsafe_provider_base_url":return"该服务地址指向 Xpod 不允许访问的网络,请改用公网 HTTPS 地址。";case"provider_request_timeout":return st;case"invalid_proxy_url":return"代理地址必须是无账号密码的 HTTP 或 HTTPS 地址。";case"oauth_refresh_failed":case"oauth_refresh_unavailable":case"local_session_refresh_failed":return ot;case"oauth_session_reauth_required":case"oauth_refresh_token_required":case"local_session_reauth_required":case"local_session_missing_refresh_token":return at;case"models_persistence_failed":return"模型已获取,但保存到 Pod 失败。请重试同步模型。";case"quota_credential_not_found":return"当前身份没有可用的额度凭证。";case"account_client_credentials_unavailable":return"Xpod 密钥 需要当前 Account 登录状态:这个客户端没有 Account 客户端凭据能力。";case"account_client_credential_not_found":return"账号服务中已找不到该客户端凭据,请刷新后重试。";case"credential_secret_unavailable":return"当前凭证密钥不可用,请重新保存后再查询额度。";case"quota_adapter_not_found":return"该接入方式不支持查询官方额度。";default:return}}function Sr(e,t){return e===401||e===403?t==="deviceCodeOAuth"?ct:"密钥不可用。请检查密钥是否填写正确,或换一个密钥后重试。":e===404?"模型服务地址不正确。请检查服务地址后重试。":e===429?"请求太频繁。请稍等一会儿再试。":e!==void 0&&e>=500?"模型服务暂时没有响应。请稍后重试。":"模型列表获取失败。请检查密钥、服务地址或网络后重试。"}function Ur(e,t){const r=t?ge(t):void 0;return r?`${e} 上游返回:${r}`:e}function Er(e){const r=e.indexOf(" 上游返回:");return r<=0?!1:dt.has(e.slice(0,r))}function ge(e){return e.replace(/[\u0000-\u001f\u007f]/gu," ").replace(/\bBearer\s+[^\s,;]+/giu,"Bearer [REDACTED]").replace(/(?:sk|id)[._-][A-Za-z0-9._-]{8,}/gu,"[REDACTED]").replace(/https?:\/\/[^\s]+/giu,"[URL]").trim().slice(0,240)||void 0}function ue(e){switch(e){case"openai":return"OpenAI";case"anthropic":return"Anthropic";case"kimi":return"Kimi";case"bailian":return"Bailian";case"deepseek":return"DeepSeek";case"zhipu":return"Zhipu";case"ollama":return"Ollama";case"custom":return"Custom"}}function Mr(e){const t={...e};for(const[r,n]of Object.entries(e))typeof n=="function"&&(t[r]=async(...i)=>{try{return await n.apply(e,i)}catch(o){throw o instanceof F&&(o.message=Pr(o)),o}});return t}const kr={"api-key":"添加 API Key","browser-login":"打开控制台","browser-oauth":"浏览器登录","device-code":"设备码登录","local-session-import":"已有登录态","local-service":"本地服务"};function Rr(e){return e.label??kr[e.id]}function mn(e){return e.map(t=>{const r=Rr(t);return r===t.label?t:{...t,label:r}})}function ie(e){return Be[e]}const Tr=3e4;function hn({webId:e,podUrl:t,authenticatedFetch:r}){return Mr(hr({webId:e,podBaseUrl:t,authenticatedFetch:Or(r)}))}function Or(e){return(async(t,r)=>pe(await e(t,r)))}function xr({podUrl:e,authenticatedFetch:t,invocationFetch:r=t,now:n=()=>new Date,invocationSelector:i=Nr}){const o=be(e);let c,l;const p=async(h,a)=>{const s=new Headers(a?.headers);s.set("X-Xpod-Pod-Url",e);const m=await t(h,{...a,headers:s});return c=await vr(m.clone(),i),m},d=async()=>{if(qr(c,n()))return c;if(l)return l;l=u();try{return await l}finally{l=void 0}},u=async()=>{if(!(await p(`${o}/api/applets/service-access/ai-connections`,{method:"GET",credentials:"include",headers:{accept:"application/json"}})).ok)throw new Error("AI Connection request failed. Please try again.");const a=c;if(!a?.token)throw new Error("AI Connection request failed. Please try again.");return a},b=async(h,a)=>{const s=await d(),m=Dr(s);if(!m)throw new Error("AI Connection request failed. Please try again.");const w=new Headers(a?.headers);return w.set("Authorization",`Bearer ${m}`),w.set("X-Xpod-Pod-Url",e),r(h,{...a,credentials:"omit",headers:w})};return(async(h,a)=>{if(Lr(h,o))return p(h,a);if(!$r(h,o))return t(h,a);const s=await b(h,a);if(s.status!==401)return pe(s);await s.arrayBuffer(),c=void 0;const m=await b(h,a);return pe(m)})}function bn({podUrl:e,controlPlaneOrigin:t,authenticatedFetch:r,invocationFetch:n,now:i}){const o=be(e),c=n??r,p=xr({podUrl:e,authenticatedFetch:r,invocationFetch:(d,u)=>{const b=new URL(d instanceof Request?d.url:String(d),o);if(t&&b.origin===o&&b.pathname.startsWith("/api/ai/client-configuration/")){const h=new URL(`${b.pathname}${b.search}`,t);return c(d instanceof Request?new Request(h,d):h.href,u)}return c(d,u)},now:i,invocationSelector:zr});return{inspect:async d=>{const u=await p(N(o,d),{method:"GET",credentials:"omit",headers:{accept:"application/json"}});return u.status===403||u.status===404||u.status===503?(await u.arrayBuffer(),$e()):z(u)},plan:async d=>z(await p(`${N(o,d.client)}/plan`,{method:"POST",credentials:"omit",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({endpoint:t?new URL(t).origin:d.endpoint,...d.activeModels!==void 0?{activeModels:d.activeModels}:{}})})),apply:async d=>z(await p(`${N(o,d.client)}/apply`,{method:"POST",credentials:"omit",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({planId:d.planId,apiKey:d.apiKey,confirmation:d.confirmation})})),verify:async d=>z(await p(`${N(o,d.client)}/verify`,{method:"POST",credentials:"omit",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({planId:d.planId})})),launch:async d=>z(await p(`${N(o,d)}/launch`,{method:"POST",credentials:"omit",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({})})),restore:async d=>{const u=await p(`${N(o,d)}/restore`,{method:"POST",credentials:"omit",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({})});return u.status===403||u.status===404||u.status===503?(await u.arrayBuffer(),$e()):z(u)}}}function Lr(e,t){try{const r=new URL(String(e),t),n=new URL(t);return r.origin===n.origin&&r.pathname==="/api/applets/service-access/ai-connections"}catch{return!1}}function $r(e,t){try{const r=new URL(String(e),t),n=new URL(t);return r.origin===n.origin&&(r.pathname.startsWith("/api/ai/")||r.pathname.startsWith("/v1/"))}catch{return!1}}async function vr(e,t){if(!(!e.ok||!e.headers.get("content-type")?.includes("application/json")))try{const r=await e.json();return Fr(t(r))}catch{return}}function Nr(e){return e.invocation}function zr(e){const t=e.aiClientConfiguration;return we(t)?t.invocation:void 0}function qr(e,t){if(!e?.token)return!1;if(!e.expiresAt)return!0;const r=Date.parse(e.expiresAt);return Number.isFinite(r)&&r-t.getTime()>Tr}function Dr(e){return e?.token}function Fr(e){if(!we(e))return;const t=["gateway","Key"].join("");return{token:typeof e.token=="string"?e.token:typeof e.apiKey=="string"?e.apiKey:typeof e[t]=="string"?e[t]:void 0,baseUrl:typeof e.baseUrl=="string"?e.baseUrl:void 0,expiresAt:typeof e.expiresAt=="string"?e.expiresAt:void 0}}async function pe(e){return e.ok?e:e.headers.get("content-type")?.includes("application/json")?jr(e):(await e.arrayBuffer(),new Response(JSON.stringify({error:"internal_error"}),{status:e.status,statusText:e.statusText,headers:{"content-type":"application/json"}}))}function N(e,t){return`${e}/api/ai/client-configuration/${encodeURIComponent(t)}`}async function z(e){if(!e.ok)throw await Kr(e);if(!e.headers.get("content-type")?.includes("application/json"))throw await e.arrayBuffer(),new Error("AI client configuration request failed. Please try again.");return await e.json()}async function Kr(e){let t;try{t=e.headers.get("content-type")?.includes("application/json")?await e.json():void 0}catch{t=void 0}if(we(t)){const r=typeof t.code=="string"?t.code:typeof t.error=="string"?t.error:void 0,n=typeof t.message=="string"?t.message:"AI client configuration request failed. Please try again.",i=new Error(n);return i.code=r,i.status=e.status,i.details=t.details,i}return await e.arrayBuffer().catch(()=>{}),new Error("AI client configuration request failed. Please try again.")}function $e(){return{status:"unavailable",message:"Host does not support local client configuration. Use the manual setup instructions for your client."}}async function jr(e){let t;try{t=await e.clone().json()}catch{return e}return Br(t)?new Response(JSON.stringify({code:t.error.code,error:t.error.message}),{status:e.status,statusText:e.statusText,headers:{"content-type":"application/json"}}):e}function Br(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e.error;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.code=="string"&&typeof t.message=="string"&&typeof t.status=="number")}function we(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}const J=Array.from(new Set([...X,"zhipu","ollama","custom"])),ve=new WeakMap,Hr=Pe.storage.base.slice(Pe.storage.base.lastIndexOf("/")+1);function Gr(e){const t=e.indexOf("#");return t<0?e:e.slice(0,t)}function gn(e){gt();const t=new URL("settings/-/sparql",e.podUrl).toString();return g.setSparqlEndpoint(t),P.setSparqlEndpoint(t),_.setSparqlEndpoint(t),{credentialsTableDocument(){return g.buildIri(e.podUrl,{id:Hr})},providerTableDocument(r,n){const i=E(r);if(!i)throw new Error("unsupported_provider");const o=i==="custom"&&n?fe(n):O(i);return P.buildIri(e.podUrl,{id:Gr(o)})},async listModels(){return await e.database.init?.(_),(await e.database.select().from(_).execute()).map(Zr).filter(L)},async listProviders(){await e.database.init?.(g,P,_);const r=await e.database.select().from(g).execute(),n=await e.database.select().from(P).execute(),i=await e.database.select().from(_).execute();return Wr(e,r,n,i)},async createApiKeyCredential(r,n){const i=E(r);if(!i)throw new Error("unsupported_provider");await e.database.init?.(g,P);const o=f(n.id),c=o??g.buildId({id:xe(i,"apiKey")}),l=1,p=ee(i,n.offeringId??G(i,"apiKey")),d=n.baseUrl??ke(i,p),u=se(n.proxyUrl),b={id:c,provider:i==="custom"?fe(c):O(i),service:"ai",authMode:"apiKey",offeringId:p,status:"active",accountLabel:n.label,label:n.label,baseUrl:d,proxyUrl:u,keyVersion:String(l),reauthRequired:!1,encryptedSecret:j(e,i,c,{type:"apiKey",apiKey:n.apiKey}),encryptionAlgorithm:"PLAINTEXT",metadata:{...te({offeringId:p,baseUrl:d,priority:n.priority}),...n.compatibility?{compatibility:n.compatibility}:{}}};return await ze(e,c,b,o!==void 0),S(e,i,b)},async createLocalCredential(r,n){const i=E(r);if(!i)throw new Error("unsupported_provider");await e.database.init?.(g,P);const o=f(n.id),c=o??g.buildId({id:xe(i,"local")}),l=ee(i,n.offeringId??G(i,"local")),p=n.baseUrl??ke(i,l),d={id:c,provider:O(i),service:"ai",authMode:"local",offeringId:l,status:"active",accountLabel:n.label??"Local",label:n.label??"Local",baseUrl:p,keyVersion:"1",reauthRequired:!1,encryptedSecret:j(e,i,c,{type:"local"}),encryptionAlgorithm:"PLAINTEXT",metadata:te({offeringId:l,baseUrl:p,priority:n.priority})};return await ze(e,c,d,o!==void 0),S(e,i,d)},async saveOAuthCredential(r,n){const i=E(r);if(!i)throw new Error("unsupported_provider");const c=(ve.get(e.database)??Promise.resolve()).then(async()=>{await e.database.init?.(g,P);const l=ee(i,n.offeringId??G(i,"deviceCode")),d=(await e.database.select().from(g).execute()).find(U=>{const v=S(e,i,U);if(!v||v.authMode!=="deviceCode"&&v.authMode!=="oauth"||De(i,v.offeringId)!==De(i,l)||U.status!=="active"&&U.status!=="disabled")return!1;const ht=q(e,i,v.id,U.encryptedSecret);return Jr(n,M(U.metadata),ht)}),u=d&&S(e,i,d),b=M(d?.metadata),h=u&&q(e,i,u.id,d?.encryptedSecret),a=u?.id??g.buildId({id:`${i}-oauth-${crypto.randomUUID()}`}),s=n.accountLabel??"OAuth",m=n.accountId??f(b?.accountId)??f(h?.accountId),w=n.accountSubject??f(b?.authoritativeSubject)??f(h?.accountSubject)??f(h?.authoritativeSubject),C={...d,id:a,provider:O(i),service:"ai",authMode:"deviceCodeOAuth",offeringId:l,status:u?.enabled===!1?"disabled":"active",accountLabel:d?.accountLabel??s,label:d?.label??s,expiresAt:n.expiresAt,scopes:n.scope?n.scope.split(/\s+/u).filter(Boolean):void 0,keyVersion:String((u?.version??0)+1),reauthRequired:!1,failCount:0,lastFailureCode:null,lastFailureAt:null,rateLimitResetAt:null,encryptedSecret:j(e,i,a,{type:"deviceCodeOAuth",accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:n.expiresAt,scope:n.scope,idToken:n.idToken,accountId:m,accountSubject:w,accountLabel:n.accountLabel,offeringId:l,authorizationMethodId:n.authorizationMethodId}),encryptionAlgorithm:"PLAINTEXT",metadata:{...b,...te({offeringId:l,priority:u?.priority,enabled:u?.enabled,health:"healthy"}),authoritativeSubject:w,accountId:m,authorizationMethodId:n.authorizationMethodId}};if(d){const U={...C};if(delete U.id,!await e.database.updateById(g,a,U))throw new Error("credential_version_conflict")}else await e.database.insert(g).values(C).execute();return S(e,i,C)});return ve.set(e.database,c.then(()=>{},()=>{})),c},async updateOAuthCredential(r,n,i,o){const c=E(r);if(!c)throw new Error("unsupported_provider");await e.database.init?.(g,P);const l=await e.database.findById(g,n),p=l&&S(e,c,l);if(!l||!p||p.authMode!=="deviceCode")throw new Error("oauth_credential_not_found");if(p.version!==i)throw new Error("credential_version_conflict");const d=q(e,c,n,l.encryptedSecret),u=o.accountId??f(M(l.metadata)?.accountId)??f(d?.accountId),b=o.accountSubject??f(M(l.metadata)?.authoritativeSubject)??f(d?.accountSubject)??f(d?.authoritativeSubject),h=ee(c,o.offeringId??p.offeringId),a={expiresAt:o.expiresAt,scopes:o.scope?o.scope.split(/\s+/u).filter(Boolean):void 0,keyVersion:String(i+1),reauthRequired:!1,failCount:0,lastFailureCode:null,lastFailureAt:null,rateLimitResetAt:null,status:"active",encryptedSecret:j(e,c,n,{type:"deviceCodeOAuth",accessToken:o.accessToken,refreshToken:o.refreshToken,expiresAt:o.expiresAt,scope:o.scope,idToken:o.idToken,accountId:u,accountSubject:b,accountLabel:o.accountLabel??f(l.accountLabel),offeringId:h,authorizationMethodId:o.authorizationMethodId??f(M(l.metadata)?.authorizationMethodId)}),accountLabel:o.accountLabel??f(l.accountLabel),label:o.accountLabel??f(l.label),offeringId:h,metadata:{...M(l.metadata),...te({offeringId:h,health:"healthy"}),authoritativeSubject:b,accountId:u,authorizationMethodId:o.authorizationMethodId??f(M(l.metadata)?.authorizationMethodId)}},s=await e.database.updateById(g,n,a);if(!s)throw new Error("credential_version_conflict");return S(e,c,s)},async updateProviderCredential(r,n,i){const o=E(r);if(!o)throw new Error("unsupported_provider");await e.database.init?.(g,P);const c=await e.database.findById(g,n),l=c&&S(e,o,c);if(!c||!l)throw new Error("credential_not_found");if(l.version!==i.expectedVersion)throw new Error("credential_version_conflict");if(i.apiKey!==void 0&&(l.authMode!=="apiKey"||typeof i.apiKey!="string"||!i.apiKey.trim()))throw new Error("invalid_api_key_replacement");const p=i.apiKey!==void 0&&q(e,o,n,c.encryptedSecret)?.apiKey!==i.apiKey,d={...M(c.metadata),...i.priority===void 0?{}:{priority:i.priority},...i.enabled===void 0?{}:{enabled:i.enabled},...i.baseUrl===void 0?{}:{baseUrl:i.baseUrl},...i.proxyUrl===void 0?{}:{proxyUrl:se(i.proxyUrl)},...p?{health:"unknown"}:{}},u={...i.label===void 0?{}:{accountLabel:i.label,label:i.label},...i.baseUrl===void 0?{}:{baseUrl:i.baseUrl},...i.proxyUrl===void 0?{}:{proxyUrl:se(i.proxyUrl)},...i.enabled===void 0?{}:{status:i.enabled?"active":"disabled"},...p?{encryptedSecret:j(e,o,n,{type:"apiKey",apiKey:i.apiKey}),encryptionAlgorithm:"PLAINTEXT",reauthRequired:!1,failCount:0,lastFailureCode:null,lastFailureAt:null,rateLimitResetAt:null}:{},keyVersion:String(l.version+1),metadata:d},b=await e.database.updateById(g,n,u);if(!b)throw new Error("credential_update_failed");const h=S(e,o,b);if(!h)throw new Error("credential_update_failed");return h},async markCredentialHealth(r,n,i,o){const c=E(r);if(!c)throw new Error("unsupported_provider");await e.database.init?.(g);const l=await e.database.findById(g,n),p=l&&S(e,c,l);if(!l||!p)throw new Error("credential_not_found");if(p.version!==o)throw new Error("credential_version_conflict");const d=await e.database.updateById(g,n,{keyVersion:String(p.version+1),metadata:{...M(l.metadata),health:i},...i==="healthy"?{failCount:0,lastFailureCode:null,lastFailureAt:null,rateLimitResetAt:null,reauthRequired:!1}:{}});if(!d)throw new Error("credential_update_failed");const u=S(e,c,d);if(!u)throw new Error("credential_update_failed");return u},async deleteProviderCredential(r,n){const i=E(r);if(!i)throw new Error("unsupported_provider");await e.database.init?.(g,P);const o=await e.database.findById(g,n),c=o&&S(e,i,o);if(c)return await e.database.deleteById(g,n),c},async readCredentialSecret(r,n){const i=E(r);if(!i)throw new Error("unsupported_provider");const o=await e.database.findById(g,n);if(!o||!S(e,i,o))throw new Error("credential_not_found");const c=q(e,i,n,o.encryptedSecret);if(!c)throw new Error("credential_secret_unavailable");return c},async saveDiscoveredModels(r,n,i){const o=E(r);if(!o)throw new Error("unsupported_provider");await e.database.init?.(g,P,_);const c=await Ne(e,n),l=qe(o,c);await Fe(e.database,l,ie(o));const p=await e.database.select().from(_).execute(),d=new Set(p.map(h=>f(h.id)).filter(L)),u=i.map(Qr).filter(L),b=new Set(u.map(h=>h.id));for(const h of p.filter(a=>en(a,l,o))){const a=x(f(h.id),l)??ft(f(h.id));a&&!b.has(a)&&f(h.status)!=="unavailable"&&await e.database.updateById(_,String(h.id),{status:"unavailable"})}for(const h of u)await tn(e,l,h,d)},async saveModelSelection(r,n,i){const o=E(r);if(!o)throw new Error("unsupported_provider");await e.database.init?.(P,_);const c=o==="custom"&&i?await Ne(e,i):null;if(o==="custom"&&i&&!c)throw new Error("credential_not_found");const l=c?qe(o,c):O(o);await Fe(e.database,l,ie(o));const d=(await e.database.select().from(P).execute()).find(a=>K(f(a.id),l)),u=f(d?.id)??l,b=await e.database.select().from(_).execute(),h=[...new Set(n.map(a=>nn(o,a,b,c?l:void 0)))];await Vr(e,u,h)}}}async function lt(e,t,r,n){if(n.length===0)return;if(!e.authenticatedFetch)throw new Error("uri_array_authenticated_fetch_required");const i=ut(t,e.podUrl,r),o=p=>{if(!/^[a-z][a-z0-9+.-]*:/iu.test(p)||/[\s<>"{}|^`\\]/u.test(p))throw new Error("uri_array_invalid_iri");return`<${p}>`},c=n.flatMap(({column:p,values:d})=>{const u=p.options.predicate;if(!p.options.isArray||p.options.baseType!=="uri"||!u)throw new Error("uri_array_column_required");const b=`${o(i)} ${o(u)}`,h=[...new Set(d)].map(a=>`${b} ${o(a)} .`).join(`
2
+ `);return[`DELETE WHERE { ${b} ?previous . }`,...h?[`INSERT DATA { ${h} }`]:[]]}),l=await e.authenticatedFetch(i.split("#",1)[0],{method:"PATCH",headers:{"content-type":"application/sparql-update"},body:c.join(`;
3
+ `)});if(!l.ok)throw new Error(`uri_array_persist_failed:${l.status}`)}async function Vr(e,t,r){await lt(e,P,t,[{column:P.columns.hasModel,values:r.map(n=>ut(_,e.podUrl,n))}])}function ut(e,t,r){return/^https?:\/\//u.test(r)?r:e.buildIri(t,{id:r})}async function Ne(e,t){const r=await e.database.findById(g,t);return r||((await e.database.select().from(g).execute()).find(i=>{const o=f(i.id);return o===t||(o?g.buildIri(e.podUrl,{id:o})===t:!1)})??null)}function Wr(e,t,r,n){const i=t.filter(o=>f(o.service)==="ai").filter(o=>f(o.status)!=="revoked");return J.map(o=>{const c=i.map(u=>S(e,o,u)).filter(L).sort((u,b)=>u.priority-b.priority||u.id.localeCompare(b.id)),l=r.find(u=>T(f(u.id))===o),d=yt(l?.hasModel).map(u=>Yr(o,u,n));return{id:o,name:o==="custom"?c.find(u=>u.label)?.label??ie(o):ie(o),offerings:o==="custom"?on(i.filter(u=>S(e,o,u))):We(o,e.openAiSubscriptionImportAvailable===!0),credentials:c,selectedModels:d,status:an(c)}})}async function ze(e,t,r,n){if(!(n?await e.database.findById(g,t):null)){await e.database.insert(g).values(r).execute();return}const o={...r};if(delete o.id,!await e.database.updateById(g,t,o))throw new Error("credential_create_failed")}function j(e,t,r,n){return wr({webId:e.webId,provider:t,credentialIri:g.buildIri(e.podUrl,{id:r}),secret:n})}function Jr(e,t,r){let n=!1;for(const[i,o]of[[e.accountId,[t?.accountId,r?.accountId]],[e.accountSubject,[t?.authoritativeSubject,r?.accountSubject,r?.authoritativeSubject]]]){const c=[...new Set(o.map(f).filter(L).filter(l=>l.trim()))];if(c.length>1)return!1;if(!(!i?.trim()||!c.length)){if(c[0]!==i)return!1;n=!0}}return n}function S(e,t,r){const n=f(r.id);if(!n)return;const i=Ae(f(r.provider))??cn(n);if(i!==t)return;const o=M(r.metadata),c=mt(r.authMode);if(c)return{id:n,provider:i,offeringId:pt(r,i,c),authMode:c,label:f(r.accountLabel)??f(r.label),enabled:Ke(o?.enabled)??f(r.status)==="active",priority:ce(o?.priority)??100,health:ln(o?.health)??(Ke(r.reauthRequired)?"expired":"healthy"),lastFailureCode:f(r.lastFailureCode),lastFailureAt:de(r.lastFailureAt),rateLimitResetAt:de(r.rateLimitResetAt),failCount:ce(r.failCount),maskedHint:sn(e,i,n,r.encryptedSecret),baseUrl:f(r.baseUrl),proxyUrl:dn(f(r.proxyUrl)??f(o?.proxyUrl)),compatibility:Xr(o?.compatibility),expiresAt:de(r.expiresAt),version:ce(r.keyVersion)??0}}function Xr(e){return e==="auto"||e==="openai"||e==="anthropic"?e:void 0}function pt(e,t,r){return f(e.offeringId)??f(M(e.metadata)?.offeringId)??_e(f(e.provider))??G(t,r)}function Yr(e,t,r){const n=r.find(l=>$(f(l.id))===$(t)),i=f(n?.isProvidedBy),o=n?x(t,i??e)??t:x(t,e)??t,c=n??r.find(l=>{const p=f(l.id),d=f(l.isProvidedBy);return p===t||x(p,e)===o||Ae(d)===e&&x(p,d??e)===o});return{id:o,provider:e,offeringId:_e(f(c?.isProvidedBy)),credentialId:Ie(i),resourceId:f(c?.id)??t,displayName:f(c?.displayName),availability:f(c?.status)==="unavailable"||!c?"unavailable":"available"}}function Zr(e){const t=f(e.isProvidedBy),r=Ae(t),n=r&&x(f(e.id),t??r);if(!(!r||!n))return{id:n,provider:r,offeringId:_e(t),credentialId:Ie(t),resourceId:f(e.id),displayName:f(e.displayName),availability:f(e.status)==="unavailable"?"unavailable":"available",...rn(e)}}function Qr(e){const t=M(e),r=f(t?.id);if(!r)return;const n=f(t?.modelType)?.trim(),i=n?me(n):void 0;return{id:r,displayName:f(t?.displayName),...i?{rdfType:[_.getType(),i]}:{},...Array.isArray(t?.capabilities)?{capabilities:wt(t.capabilities)}:{}}}function qe(e,t){const r=Ie(f(t?.provider));return r?fe(r):O(e)}function O(e){return Ar(e)}function fe(e){return _r(e)}function Ie(e){const t=T(e),r=t?.startsWith("custom-instance-")?t.slice(16):void 0;if(r)try{return decodeURIComponent(r)}catch{return}}function De(e,t){if(!t)return;const r=t.trim().toLowerCase();if(e==="bailian"){if(r==="token-plan")return"token-plan-personal";if(r==="coding-plan")return"coding-plan-pro";if(r==="payg")return"pay-as-you-go"}return r}function K(e,t){const r=$(e),n=$(t);return r!==void 0&&r===n}function en(e,t,r){const n=f(e.isProvidedBy);return K(n,t)?!0:r==="custom"?!1:T(n)?.startsWith(`${r}-`)===!0}function ft(e){if(!e)return;const t=e.lastIndexOf("#");if(t<0||t===e.length-1)return;const r=e.slice(t+1);try{return decodeURIComponent(r)}catch{return r}}async function Fe(e,t,r){(await e.select().from(P).execute()).some(i=>K(f(i.id),t))||await e.insert(P).values({id:t,displayName:r}).execute()}async function tn(e,t,r,n){const i=ye(t,r.id),o=n.has(i),c=o?await e.database.findById(_,i):void 0,l={displayName:r.displayName??r.id,isProvidedBy:t,status:"active"};if(o)await e.database.updateById(_,i,l);else{const d=e.database.insert(_).values({id:i,...l}).toIR();for(const u of d.rows)delete u.rdfType,delete u.capabilities;await e.database.session.execute({type:"insert",table:_,values:d.rows[0],plan:d})}const p=[];if(!o||r.rdfType){const d=yt(c?.rdfType).filter(u=>/^[a-z][a-z0-9+.-]*:/iu.test(u)&&me(u)!==u);p.push({column:_.columns.rdfType,values:[...new Set([_.getType(),...d,...r.rdfType??[]])]})}r.capabilities!==void 0&&p.push({column:_.columns.capabilities,values:r.capabilities}),await lt(e,_,i,p),n.add(i)}function rn(e){const t=Array.isArray(e.rdfType)?e.rdfType:[e.rdfType],r=t.find(i=>typeof i=="string"&&me(i)===i),n=It({rdfType:t,capabilities:e.capabilities}).capabilities.map(At).filter(L);return{...r?{modelType:_t(r)}:{},...n.length>0?{capabilities:n}:{}}}function ye(e,t){const r=$(e)??`${e}.ttl`;return`${r.split("#",1)[0]??r}#${encodeURIComponent(t)}`}function nn(e,t,r,n){const i=f(t.resourceId),o=n??O(e),c=f(t.id),l=c?r.filter(d=>{const u=f(d.isProvidedBy),b=T(u);return(n?K(u,n):b===e||b?.startsWith(`${e}-`)===!0)&&x(f(d.id),u??o)===c}):[],p=n||l.length===1?l[0]:void 0;if(i){const d=r.find(a=>f(a.id)===i);if(!d&&p)return String(p.id);const u=f(d?.isProvidedBy),b=T(u),h=n?K(u,n):b===e||b?.startsWith(`${e}-`)===!0;if(d&&!h)throw new Error("invalid_model_selection_resource");if(!d){const a=c??ft(i),s=T(i),m=n?K(s,n):s===e||s?.startsWith(`${e}-`)===!0;if(!a||!m)throw new Error("invalid_model_selection_resource");return ye(o,a)}return i}if(!c)throw new Error("invalid_model_selection_resource");return f(p?.id)??ye(o,c)}function x(e,t){if(!e)return;const n=$(t)?.split("#",1)[0]??t,i=n.endsWith(".ttl")?`${n}#`:`${n}.ttl#`,o=e.lastIndexOf(i);if(!(o<0))try{return decodeURIComponent(e.slice(o+i.length))}catch{return e.slice(o+i.length)}}function yt(e){if(Array.isArray(e))return e.map(f).filter(L);const t=f(e);return t?[t]:[]}function on(e){const t=new Map;for(const r of e){const n=M(r.metadata),i=pt(r,"custom",mt(r.authMode)??"apiKey"),o=vt(n?.compatibility,i),c=f(r.baseUrl)??f(n?.baseUrl),l=B.find(p=>p.id===i)??B.find(p=>p.id===`${o}-compatible`)??B[0];t.set(i,{...l,id:i,endpoints:c?[{protocol:o==="anthropic"?"anthropic":"chatCompletions",baseUrl:c}]:l.endpoints,modelDiscovery:o==="anthropic"?{strategy:"anthropic",path:"/models",endpointProtocol:"anthropic"}:{strategy:"openaiCompatible",path:"/models",endpointProtocol:"chatCompletions"}})}return t.size>0?[...t.values()]:B}function an(e){return e.some(t=>t.health==="expired"||t.health==="invalid")?"attention":e.some(t=>t.enabled)?"available":e.length>0?"configured":"unconfigured"}function sn(e,t,r,n){const i=q(e,t,r,n),o=f(i?.apiKey);if(o)return o.length<=8?`${o.slice(0,2)}…`:`${o.slice(0,3)}...${o.slice(-4)}`}function q(e,t,r,n){return Ir({webId:e.webId,provider:t,credentialIri:g.buildIri(e.podUrl,{id:r}),envelope:n})}function Ae(e){const t=T(e),r=E(t);return r||J.find(n=>t?.startsWith(`${n}-`))}function _e(e){const t=T(e);if(t&&!t.startsWith("custom-instance-")){if(t==="bailian-token-plan-personal")return"token-plan";if(t==="bailian-token-plan-team")return"token-plan-team";if(t==="bailian-coding-plan-pro")return"coding-plan";if(t==="bailian-pay-as-you-go")return"pay-as-you-go";for(const r of J)if(t.startsWith(`${r}-`))return t.slice(r.length+1)}}function cn(e){const t=/\/([^/#]+)\.ttl#/u.exec(e);return E(t?.[1])}function E(e){if(typeof e!="string"||!e.trim())return;const t=e.trim().toLowerCase();if(t==="zhipu"||t.startsWith("zhipu-"))return"zhipu";if(J.includes(t))return t;for(const r of J)if(t.startsWith(`${r}-`)||r==="bailian"&&(t==="bailian-token-plan"||t==="bailian-coding-plan"))return r}function se(e){if(e==null||!e.trim())return;let t;try{t=new URL(e.trim())}catch{throw new Error("invalid_proxy_url")}if(!["http:","https:"].includes(t.protocol)||t.username||t.password||t.hash||!t.hostname)throw new Error("invalid_proxy_url");return t.toString().replace(/\/$/u,"")}function dn(e){if(e==null||!e.trim())return;let t;try{t=new URL(e.trim())}catch{return}if(!(!["http:","https:"].includes(t.protocol)||!t.hostname))return t.username="",t.password="",t.search="",t.hash="",t.toString().replace(/\/$/u,"")}function mt(e){if(e==="oauth"||e==="deviceCode"||e==="apiKey"||e==="local")return e;if(e==="deviceCodeOAuth")return"deviceCode"}function ln(e){if(e==="healthy"||e==="expired"||e==="invalid"||e==="unknown")return e;if(e==="reauthRequired")return"expired";if(e==="disabled")return"unknown"}function M(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function f(e){return typeof e=="string"&&e.trim()?e:void 0}function ce(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()){const t=Number(e);return Number.isFinite(t)?t:void 0}}function Ke(e){if(typeof e=="boolean")return e;if(e==="true")return!0;if(e==="false")return!1}function de(e){return e instanceof Date?e.toISOString():f(e)}function L(e){return e!==void 0}export{F as A,Be as P,te as a,_r as b,xe as c,G as d,Ar as e,hn as f,gn as g,pn as h,X as i,yn as j,hr as k,Pr as l,Pt as m,fn as n,ke as o,T as p,bn as q,ee as s,mn as w};
@@ -0,0 +1 @@
1
+ .xpod-desktop-shell{display:grid;grid-template-columns:64px minmax(0,1fr);height:var(--xpod-shell-height,100dvh);min-height:0;background:hsl(var(--background))}.xpod-rail{display:flex;flex-direction:column;align-items:center;gap:24px;padding:16px 0;min-height:0;border-right:1px solid hsl(var(--border));background:hsl(var(--layout-sidebar))}.xpod-rail-profile{flex-shrink:0}.xpod-rail-host{margin-top:auto;width:100%}.xpod-rail-profile [data-testid=xpod-user-card-trigger],.xpod-rail-profile>a{width:36px;height:36px}.xpod-rail-profile [data-testid=xpod-user-card-trigger]>span:first-child{width:32px;height:32px}.xpod-rail nav a>svg{width:20px;height:20px}.xpod-shell-content{display:flex;flex-direction:column;min-width:0;min-height:0;overflow:hidden}.xpod-narrow-header,.xpod-drawer-close,.xpod-drawer-backdrop{display:none}.xpod-desktop-shell [data-workspace-layout=two-pane]>[data-workspace-object-column=shown]{grid-template-columns:270px minmax(0,1fr)!important}.xpod-desktop-shell [data-workspace-pane=list],.xpod-desktop-shell [data-workspace-pane=main]{min-width:0}@media(max-width:767px){.xpod-desktop-shell{grid-template-columns:minmax(0,1fr);grid-template-rows:48px minmax(0,1fr)}.xpod-narrow-header{display:flex;align-items:center;gap:8px;border-bottom:1px solid hsl(var(--border));min-width:0;padding:0 12px;font-size:14px}.xpod-narrow-header button{display:flex;align-items:center;justify-content:center;width:36px;height:36px;flex-shrink:0}.xpod-narrow-header span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.xpod-rail{display:none}.xpod-desktop-shell [data-workspace-layout=two-pane]>[data-workspace-layout-mode]{grid-template-columns:minmax(0,1fr)!important}.xpod-desktop-shell [data-workspace-pane=list]{display:none}.xpod-desktop-shell[data-drawer-open=true] .xpod-rail{display:flex;position:fixed;inset:0 auto 0 0;width:64px;z-index:61;background:hsl(var(--background))}.xpod-desktop-shell[data-drawer-open=true] [data-workspace-pane=list]{display:flex;position:fixed;inset:0 auto 0 64px;width:min(280px,calc(100vw - 104px));z-index:61;background:hsl(var(--background));border-right:1px solid hsl(var(--border))}.xpod-drawer-backdrop{display:block;position:fixed;inset:0;z-index:60;background:#00000059}.xpod-drawer-close{display:flex;align-items:center;justify-content:center;position:fixed;right:4px;top:6px;width:36px;height:36px;z-index:62;border-radius:8px;background:hsl(var(--background))}}.xpod-navigation-toggle{display:flex;align-items:center;justify-content:center;width:36px;height:36px;flex-shrink:0}.xpod-header-parent{max-width:80px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:14px;color:hsl(var(--muted-foreground))}@media(max-width:767px){.xpod-desktop-shell:has([data-workspace-main-header]){grid-template-rows:minmax(0,1fr)}.xpod-desktop-shell:has([data-workspace-main-header])>.xpod-narrow-header{display:none}.xpod-desktop-shell [data-workspace-header-leading]{padding-left:8px}}
@@ -0,0 +1,4 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-gtv-MAHl.js","assets/dashboard-vmne1ZE0.js","assets/dashboard-hSOBxPcP.css","assets/xpod-remembered-login-nv1g1sfC.js","assets/createLucideIcon-BWelSi3L.js","assets/button-WVnQUNG-.js","assets/PodDeletionAuthorizationPanel-C22bhZeD.js","assets/account-session-rRAOF7nF.js","assets/safe-continuation-BsKjDpAA.js","assets/nav-item-style-B2gI7c52.js","assets/PodPage-Dyo3yCb-.js","assets/XpodAiConnectionsPodStore-EXCqZPmb.js","assets/section-header-DM0JU-wk.js","assets/setting-row-XiH7UjWy.js","assets/ModelsPage-0qWGa5Y6.js","assets/list-CKq3KHke.js","assets/label-tKuCTJm2.js","assets/DevicePages-D1m_BNtX.js","assets/PaneListHeader-uWdPgJ0E.js","assets/TasksPage-B0EoyRYT.js","assets/TasksPage-DPpAgn4C.css"])))=>i.map(i=>d[i]);
2
+ import{r as d,j as n,_ as ae,u as cr,X as hs,e as fs,L as Ze,a as ps,b as $e,O as ht,f as ms,N as gs,d as be,B as bs,g as xs}from"./dashboard-vmne1ZE0.js";import{aj as Nt,ak as lr,al as dr,am as vs,an as _s,ao as Me,ap as St,aq as ws,ar as ys,as as je,at as kt,au as js,av as Rt,aw as ur,ax as Is,I as Ns,H as Ss,ay as ks,az as Rs,aA as Q,aB as hr,a1 as Ps,aC as Be,Z as Ls,_ as fr,aD as Cs,aE as Es,aF as As,aG as ft,aH as Ts,L as Us,K as et,V as Ds,aI as tt,aJ as Pt,aK as Os,M as Lt,aL as Fs,aM as $s,aN as Bs,aO as zs,aP as Ms,aQ as Xs,aR as pr,aS as Ct,aT as Et,a5 as At,aU as Tt,aV as Ut,aW as Dt,aX as Ot,Y as rt,aY as mr,aZ as qs,a_ as Gs,X as Ws}from"./xpod-remembered-login-nv1g1sfC.js";import{c as M,e as Ft,i as gr,a as Hs,B as pe,f as Vs}from"./button-WVnQUNG-.js";import{p as ze,i as Qs,I as br,P as Ks,X as Js,R as xr,r as Ys,q as Zs}from"./PodDeletionAuthorizationPanel-C22bhZeD.js";import{X as pt,u as vr,a as _r,r as mt,s as gt,A as bt}from"./account-session-rRAOF7nF.js";import{f as en,g as tn,r as rn,A as sn}from"./safe-continuation-BsKjDpAA.js";import{i as nn,T as wr,u as an,D as yr,W as on,h as cn,j as ln}from"./nav-item-style-B2gI7c52.js";import{c as W}from"./createLucideIcon-BWelSi3L.js";const dn=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],un=ze("circle-check",dn);const hn=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],fn=ze("circle-x",hn);const pn=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],mn=ze("search",pn);const gn=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],xt=ze("triangle-alert",gn),jr=d.forwardRef(({className:t,multiple:e,size:r,...s},a)=>n.jsx("select",{ref:a,multiple:e,size:r,className:M(Qs,!e&&(!r||r<=1)&&"min-h-10",t),...s}));jr.displayName="NativeSelect";const Ir=d.forwardRef(({className:t,placeholder:e="搜索",...r},s)=>n.jsxs("div",{className:"relative min-w-0 w-full",children:[n.jsx(mn,{"aria-hidden":"true",className:"pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),n.jsx(br,{...r,ref:s,type:"search",placeholder:e,className:M("h-auto min-h-8 rounded-lg border-border bg-card py-1 pl-8 pr-2.5 text-[13px] leading-normal",t)})]}));Ir.displayName="SearchInput";const bn={success:"bg-success",warning:"bg-warning",destructive:"bg-destructive",info:"bg-primary",neutral:"border border-muted-foreground bg-transparent"},xn={sm:"h-1.5 w-1.5",md:"h-2 w-2"};function vt({tone:t,label:e,size:r="md",className:s,"aria-label":a,...i}){const o=e??a,c=o?{role:"img","aria-label":o,title:o}:{"aria-hidden":!0};return n.jsx("span",{className:M("inline-block shrink-0 rounded-full",xn[r],bn[t],s),...i,...c})}function vn({tone:t,children:e,dotSize:r="sm",className:s,...a}){return n.jsxs("span",{className:M("inline-flex items-center gap-1.5",s),...a,children:[n.jsx(vt,{tone:t,size:r}),n.jsx("span",{children:e})]})}const _n={info:"border-primary/30 bg-primary/10 text-foreground",success:"border-success/30 bg-success/10 text-foreground",warning:"border-warning/30 bg-warning/10 text-foreground",destructive:"border-destructive/30 bg-destructive/10 text-foreground",neutral:"border-border bg-muted/30 text-foreground"},wn={info:"text-primary",success:"text-success",warning:"text-warning",destructive:"text-destructive",neutral:"text-muted-foreground"},yn={info:Nt,success:un,warning:xt,destructive:fn,neutral:Nt};function Nr({tone:t="info",title:e,icon:r,action:s,role:a="status",className:i,children:o,...c}){const l=yn[t];return n.jsxs("div",{role:a,className:M("flex items-start gap-2.5 rounded-md border px-3 py-2.5 text-sm leading-normal",_n[t],i),...c,children:[n.jsx("span",{"aria-hidden":"true",className:M("mt-0.5 shrink-0",wn[t]),children:r??n.jsx(l,{className:"h-4 w-4"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[e?n.jsx("p",{className:"font-medium",children:e}):null,o]}),s?n.jsx("div",{className:"shrink-0",children:s}):null]})}const jn={label:"Restoring session…"},Xe={title:"Connecting…",detail:"Waiting for the provider",cancelLabel:"Cancel"},qe={title:"Sign-in failed",primaryLabel:"Retry",secondaryLabel:"Back"};function fe(t,e){return t?.trim()?t:e}function In({name:t,avatarUrl:e,size:r="lg",marker:s}){const a=r==="lg"?"h-16 w-16 text-xl":"h-10 w-10 text-sm";return n.jsxs("div",{className:"relative shrink-0",children:[e?n.jsx("img",{src:e,alt:t,className:M(a,"rounded-[18%] border border-border/50 object-cover shadow-sm")}):n.jsx("div",{"aria-hidden":"true",className:M(a,"flex items-center justify-center rounded-[18%] bg-primary/10 font-semibold text-primary shadow-sm"),children:t.slice(0,1).toUpperCase()}),s?n.jsx("div",{className:"absolute -bottom-1 -right-1",children:s}):null]})}function Nn({accountName:t,avatarUrl:e,label:r}){const s=fe(r,jn.label);return n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-4 p-6",role:"status",children:[t?n.jsxs(n.Fragment,{children:[n.jsx(In,{name:t,avatarUrl:e,size:"lg"}),n.jsx("p",{className:"text-sm font-medium text-foreground",children:t})]}):null,n.jsx(lr,{className:"h-6 w-6 animate-spin text-muted-foreground","aria-hidden":"true"}),n.jsx("p",{className:"text-xs text-muted-foreground",children:s})]})}function zo({title:t,detail:e,providerLabel:r,providerHost:s,onCancel:a,cancelLabel:i}){const o=fe(t,Xe.title),c=fe(e,Xe.detail),l=fe(i,Xe.cancelLabel);return n.jsxs("div",{className:"flex h-full flex-1 flex-col",children:[n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center px-6 py-8 text-center",role:"status",children:[n.jsx(lr,{className:"mb-4 h-8 w-8 animate-spin text-primary","aria-hidden":"true"}),n.jsx("p",{className:"text-sm font-medium text-foreground",children:o}),n.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:c}),r||s?n.jsxs("div",{className:"mt-4 w-full max-w-[18rem] rounded-lg border border-border/60 bg-muted/30 px-3 py-2",children:[r?n.jsx("p",{className:"truncate text-xs font-medium text-foreground",children:r}):null,s?n.jsx("p",{className:"mt-0.5 truncate text-[11px] text-muted-foreground",children:s}):null]}):null]}),a?n.jsx("div",{className:"shrink-0 px-5 pb-5",children:n.jsx("button",{type:"button",onClick:a,className:M("h-9 w-full cursor-pointer rounded-md text-xs text-muted-foreground transition-colors hover:bg-muted/40 hover:text-foreground",gr),children:l})}):null]})}function Mo({title:t,description:e,primaryLabel:r,onPrimary:s,secondaryLabel:a,onSecondary:i}){const o=fe(t,qe.title),c=fe(r,qe.primaryLabel),l=fe(a,qe.secondaryLabel);return n.jsxs("div",{className:"flex h-full flex-1 flex-col",children:[n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-3 px-6 pb-5 pt-7 text-center",children:[n.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-destructive/10",children:n.jsx(xt,{className:"h-6 w-6 text-destructive","aria-hidden":"true"})}),n.jsx("p",{className:"text-base font-semibold text-foreground",children:o}),e?n.jsx("p",{className:"max-w-[19rem] text-sm leading-6 text-muted-foreground",role:"alert",children:e}):null]}),n.jsxs("div",{className:"shrink-0 space-y-2 px-4 pb-5",children:[n.jsx("button",{type:"button",onClick:s,className:M("h-9 w-full cursor-pointer rounded-md bg-primary text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus-visible:bg-primary/80 disabled:cursor-not-allowed disabled:opacity-50",Ft),children:c}),i?n.jsx("button",{type:"button",onClick:i,className:M("h-9 w-full cursor-pointer rounded-md border border-border/60 bg-muted/30 text-sm font-medium text-foreground transition-colors hover:bg-muted/50 focus-visible:border-ring focus-visible:bg-muted/50",Ft),children:l}):null]})]})}var Sn=Object.defineProperty,Sr=(t,e)=>Sn(t,"name",{value:e,configurable:!0}),$t="horizontal",kn=["horizontal","vertical"],Rn=d.forwardRef(Sr(function(e,r){const{decorative:s,orientation:a=$t,...i}=e,o=kr(a)?a:$t,l=s?{role:"none"}:{"aria-orientation":o==="vertical"?o:void 0,role:"separator"};return n.jsx(Ks.div,{"data-orientation":o,...l,...i,ref:r})},"Separator"));function kr(t){return kn.includes(t)}Sr(kr,"isValidOrientation");var Rr=Rn;const Pr=d.forwardRef(({className:t,orientation:e="horizontal",decorative:r=!0,...s},a)=>n.jsx(Rr,{ref:a,decorative:r,orientation:e,className:M("shrink-0 bg-border",e==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",t),...s}));Pr.displayName=Rr.displayName;const Pn=3e3,Ln=Hs("pointer-events-auto relative flex w-full items-start justify-between gap-3 overflow-hidden rounded-md border px-4 py-3 text-sm shadow-lg transition-opacity",{variants:{variant:{default:"border-border bg-background text-foreground",destructive:"border-destructive/30 bg-destructive/10 text-destructive",success:"border-green-500/20 bg-green-500/15 text-green-600"}},defaultVariants:{variant:"default"}});let Ge=0,he=[];const st=new Set;function Lr(){for(const t of st)t()}function Cr(t){const e=he.findIndex(r=>r.id===t);e<0||(clearTimeout(he[e].timer),he=he.filter(r=>r.id!==t),Lr())}function Cn(t){Cr(t)}function Xo(t){Ge=(Ge+1)%Number.MAX_SAFE_INTEGER;const e=Ge.toString(),r=t.duration??Pn,s={id:e,title:t.title,description:t.description,variant:t.variant??"default",className:t.className,timer:setTimeout(()=>Cr(e),r)};return he=[...he.slice(-2),s],Lr(),e}function En(t){return st.add(t),()=>{st.delete(t)}}function Bt(){return he}function An({className:t}){const e=d.useSyncExternalStore(En,Bt,Bt);return n.jsx("div",{"aria-live":"polite",role:"status",className:M("pointer-events-none fixed bottom-4 right-4 z-[var(--layer-toast)] flex w-full max-w-sm flex-col gap-2",t),children:e.map(r=>n.jsxs("div",{className:M(Ln({variant:r.variant}),r.className),children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[r.title?n.jsx("p",{className:"font-medium",children:r.title}):null,r.description?n.jsx("p",{className:M(r.title?"mt-0.5":void 0),children:r.description}):null]}),n.jsx("button",{type:"button","aria-label":"关闭通知",className:M("shrink-0 rounded-sm opacity-60 transition-opacity hover:opacity-100",gr),onClick:()=>Cn(r.id),children:n.jsx(Js,{"aria-hidden":"true",className:"h-3.5 w-3.5"})})]},r.id))})}const Tn=300;function Un({notice:t,developerMode:e,copy:r}){const[s,a]=d.useState(!1),i=n.jsxs("span",{className:"inline-flex items-start gap-1.5",children:[t.tone==="warning"?n.jsx(xt,{"aria-hidden":"true",className:"mt-0.5 h-3.5 w-3.5 shrink-0"}):null,n.jsx("span",{children:t.text})]}),o=t.tone==="warning"?"text-warning":"text-muted-foreground",c=t.tone==="warning"?"alert":"status",l=e?t.developerDetail:void 0;return n.jsx("div",{role:c,"data-pod-sign-in":"notice","data-tone":t.tone,className:M("text-[13px] leading-5",o),children:l?n.jsxs("details",{children:[n.jsx("summary",{title:r.noticeDetailsToggle,className:"cursor-pointer rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring",children:i}),n.jsxs("div",{className:"mt-1 rounded-lg bg-muted p-2 text-foreground",children:[n.jsx("pre",{className:"whitespace-pre-wrap break-all font-mono text-xs",children:l}),n.jsx("button",{type:"button",className:"mt-1 h-9 rounded-lg px-2 text-[13px] font-medium text-primary hover:bg-accent focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring",onClick:()=>{navigator.clipboard?.writeText(l).then(()=>a(!0),()=>{})},children:s?r.noticeCopied:r.noticeCopy})]})]}):i})}function Dn({copy:t,error:e,busy:r,onSubmit:s}){const[a,i]=d.useState(""),o=c=>{c.preventDefault();const l=a.trim();l&&s&&s(l)};return n.jsxs("form",{onSubmit:o,className:"flex flex-col gap-3","data-pod-sign-in":"custom-service",children:[n.jsx(Is,{label:t.customLabel,error:e,children:c=>n.jsx(br,{...c,name:"service",type:"text",inputMode:"url",autoComplete:"url",autoCapitalize:"none",spellCheck:!1,placeholder:t.customPlaceholder,value:a,disabled:r,className:"h-11 rounded-lg bg-card text-sm",onChange:l=>i(l.target.value)})}),n.jsx(je,{type:"submit",variant:"outline",className:ur,busy:r,disabled:!a.trim(),children:t.customSubmit})]})}function On({app:t,brand:e,state:r,notice:s,locale:a="zh-CN",copy:i,developerMode:o=!1,primaryIcon:c,capabilities:l,onPrimary:h,onUseAnother:u,onCustomService:g,onRegister:f,onToggleCustom:v}){const p=dr(a,i),m=vs(Tn),[b,S]=d.useState(!1),N=e?n.jsx("div",{"data-pod-sign-in":"source",children:e}):n.jsx(_s,{icon:t.icon,name:t.name});if(r.kind==="restoring"){const _=m?r.identity:void 0;return n.jsxs(Me,{"data-pod-sign-in-state":"restoring",children:[N,n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-3 text-center",children:[_?n.jsxs(n.Fragment,{children:[n.jsx(St,{name:_.displayName,avatarUrl:_.avatarUrl,storage:_.storage}),n.jsx("h1",{className:"text-[17px] font-semibold text-foreground",children:_.displayName})]}):n.jsx("h1",{className:"sr-only",children:t.name}),n.jsx("div",{role:"status","aria-live":"polite",children:m?n.jsxs("p",{className:"flex items-center gap-2 text-[13px] text-muted-foreground",children:[n.jsx(ws,{}),p.restoring]}):null})]})]})}const x=r.busy===!0,I=s?.primaryLabel??(r.kind==="remembered"?ys(p.enterApp,{app:t.name}):r.kind==="expired"?p.reauthenticate:p.useXpod),k=s?n.jsx(Un,{notice:s,developerMode:o,copy:p}):null;if(r.kind==="remembered"||r.kind==="expired")return n.jsxs(Me,{"data-pod-sign-in-state":r.kind,actions:n.jsxs(n.Fragment,{children:[k,n.jsx(je,{className:kt,busy:x,"data-pod-sign-in-primary":"true",onClick:h,children:I}),u?n.jsx(je,{variant:"ghost",className:M(js,"w-full"),disabled:x,onClick:u,children:p.useAnother}):null]}),children:[N,n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-3 text-center",children:[n.jsx(St,{name:r.identity.displayName,avatarUrl:r.identity.avatarUrl,storage:r.identity.storage}),n.jsx("h1",{className:"text-[17px] font-semibold text-foreground",children:r.identity.displayName}),r.kind==="expired"?n.jsx("p",{className:"text-sm text-muted-foreground",children:p.expiredLine}):null]})]});const R=l?.customService!==!1,y=l?.register!==!1&&!!f,A=R&&(r.customOpen??b),j=()=>{const _=!A;S(_),v?.(_)};return n.jsxs(Me,{"data-pod-sign-in-state":"choose-service",actions:n.jsxs(n.Fragment,{children:[k,n.jsxs(je,{className:kt,busy:x,"data-pod-sign-in-primary":"true",onClick:h,children:[!s?.primaryLabel&&c!==null?n.jsx("span",{"aria-hidden":"true",className:"mr-2 flex",children:c??n.jsx(pt,{size:20})}):null,I]}),R?n.jsxs(n.Fragment,{children:[n.jsx(je,{variant:"outline",className:ur,disabled:x,"aria-expanded":A,onClick:j,children:p.useOtherSolid}),A?n.jsx(Dn,{copy:p,error:r.customError,busy:x,onSubmit:g}):null]}):null,y?n.jsxs("p",{className:"text-center text-[13px] text-muted-foreground",children:[p.noAccount,n.jsx("button",{type:"button",className:"ml-1 h-9 rounded px-1 font-medium text-primary hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring",disabled:x,onClick:f,children:p.register})]}):null]}),children:[N,n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx("h1",{className:"text-[17px] font-semibold text-foreground",children:p.chooseTitle}),n.jsx("p",{className:"text-sm leading-[22px] text-muted-foreground",children:p.chooseLead}),n.jsxs("div",{className:"flex flex-col",children:[n.jsx(Rt,{summary:p.whatIsWebId,children:p.whatIsWebIdBody}),n.jsx(Rt,{summary:p.whatIsPod,children:p.whatIsPodBody})]})]})]})}function Fn(t){try{const e=new URL(t),r=e.pathname.split("/").filter(s=>s&&!["profile","card"].includes(s));return r[r.length-1]??e.hostname}catch{return t}}const $n=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],Bn=W("bell",$n);const zn=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Mn=W("chevron-right",zn);const Xn=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],qn=W("circle-check",Xn);const Gn=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Wn=W("copy",Gn);const Hn=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],Vn=W("external-link",Hn);const Qn=[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]],Kn=W("inbox",Qn);const Jn=[["path",{d:"m10 17 5-5-5-5",key:"1bsop3"}],["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}]],Yn=W("log-in",Jn);const Zn=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],ea=W("log-out",Zn);const ta=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],ra=W("menu",ta);const sa=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],na=W("monitor",sa);const aa=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],Er=W("refresh-cw",aa);const ia=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],oa=W("settings",ia);const ca=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],la=W("sparkles",ca);const da=[["path",{d:"M21 10.656V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.344",key:"2acyp4"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],ua=W("square-check-big",da);const ha=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],fa=W("user-round",ha);const pa=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ar=W("x",pa);function ma({title:t="操作未完成",description:e,primaryLabel:r="重试",onPrimary:s,primaryDisabled:a=!1,secondaryLabel:i="返回",onSecondary:o,tertiaryLabel:c,onTertiary:l,pending:h=!1,children:u}){return n.jsxs("div",{className:"flex min-h-44 flex-col items-center justify-center gap-4 px-5 py-8 text-center",children:[n.jsx("div",{className:"flex h-11 w-11 items-center justify-center rounded-full bg-destructive/10",children:n.jsx(Ns,{"aria-hidden":"true",className:"h-5 w-5 text-destructive"})}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-base font-semibold text-foreground",children:t}),e?n.jsx("p",{role:"alert",className:"text-sm leading-6 text-muted-foreground",children:e}):null]}),u?n.jsx("div",{className:"w-full space-y-2 text-left sm:max-w-xs",children:u}):null,n.jsxs("div",{className:"flex w-full flex-col gap-2 sm:max-w-xs",children:[n.jsx("button",{type:"button",disabled:h||a,onClick:s,className:"h-10 rounded-xl bg-primary px-4 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus:outline-none focus-visible:bg-primary/80 disabled:cursor-not-allowed disabled:opacity-50",children:r}),o?n.jsx("button",{type:"button",disabled:h,onClick:o,className:"h-9 rounded-lg border border-border bg-background px-4 text-sm font-medium text-foreground transition-colors hover:bg-muted/50 focus:outline-none focus-visible:border-ring disabled:cursor-not-allowed disabled:opacity-50",children:i}):null,l&&c?n.jsx("button",{type:"button",disabled:h,onClick:l,className:"h-9 rounded-lg px-4 text-sm text-muted-foreground transition-colors hover:bg-muted/40 hover:text-foreground focus:outline-none focus-visible:bg-muted/40 disabled:cursor-not-allowed disabled:opacity-50",children:c}):null]})]})}let Tr=!1,Ur={status:"idle"},Fe,ue;const nt=new Set,ga=()=>Tr,zt=()=>Ur;function Dr(t){return nt.add(t),()=>{nt.delete(t)}}function Ee(t){Ur=t,nt.forEach(e=>e())}function at(t,e,r={}){return ue||(Tr=!0,Fe={account:t,runtime:e,solidCleared:!1,onComplete:r.onComplete},Or())}function Or(){if(ue)return ue;if(!Fe)return Promise.resolve();const t=Fe;return ue=(async()=>{let r=t.solidCleared?"account":"solid";Ee({status:"running",step:r});try{if(t.solidCleared||(await t.runtime?.logout(),t.solidCleared=!0),r="account",Ee({status:"running",step:r}),await t.account.logout(),t.account.isAnonymous&&!t.account.isAnonymous())throw new Error("Account sign-out did not complete")}catch(s){throw Ee({status:"error",step:r}),s}Fe=void 0,Ee({status:"idle"}),t.onComplete?.()})().finally(()=>{ue=void 0}),ue}const Mt=d.createContext(!1);function Fr({children:t}){const e=d.useContext(Mt),r=d.useSyncExternalStore(Dr,zt,zt);if(e)return n.jsx(n.Fragment,{children:t});const s=r.status!=="idle";return n.jsxs(Mt.Provider,{value:!0,children:[s&&n.jsx(Ss,{mode:"page",title:"退出 Xpod",children:r.status==="running"?n.jsx(Nn,{label:"正在退出…"}):n.jsx(ma,{title:"退出未完成",description:r.step==="account"?"账号会话尚未退出,请重试完成退出。":"WebID 会话尚未退出,请重试完成退出。",primaryLabel:"重试退出",onPrimary:()=>{Or().catch(()=>{})}})}),n.jsx("div",{className:s?"hidden":"contents","aria-hidden":s||void 0,inert:s||void 0,children:t})]})}function ba(t){try{const r=new URL(t).pathname.split("/").filter(Boolean).map(i=>decodeURIComponent(i)),s=r.indexOf("profile");if(s>0)return r[s-1];const a=r.find(i=>i!=="profile"&&i!=="card");if(a)return a}catch{}return"there"}const _e="http://www.w3.org/1999/02/22-rdf-syntax-ns#",we="http://www.w3.org/2001/XMLSchema#",Ae="http://www.w3.org/2000/10/swap/",Z={xsd:{decimal:`${we}decimal`,boolean:`${we}boolean`,double:`${we}double`,integer:`${we}integer`,string:`${we}string`},rdf:{type:`${_e}type`,nil:`${_e}nil`,first:`${_e}first`,rest:`${_e}rest`,langString:`${_e}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${Ae}reify#forSome`,forAll:`${Ae}reify#forAll`},log:{implies:`${Ae}log#implies`,isImpliedBy:`${Ae}log#isImpliedBy`}},{xsd:Te}=Z,xa=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,Xt={"\\":"\\","'":"'",'"':'"',n:`
3
+ `,r:"\r",t:" ",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},va=/[\x00-\x20<>\\"\{\}\|\^\`]/,_a={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_newline:!0,_comment:!0,_whitespace:!0,_endOfFile:!0},wa=/$0^/;class ya{constructor(e){if(this._iri=/^<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/,this._unescapedIri=/^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/,this._simpleQuotedString=/^"([^"\\\r\n]*)"(?=[^"])/,this._simpleApostropheString=/^'([^'\\\r\n]*)'(?=[^'])/,this._langcode=/^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i,this._prefix=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:(?=[#\s<])/,this._prefixed=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:((?:(?:[0-:A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])(?:(?:[\.\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])*(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~]))?)?)(?:[ \t]+|(?=\.?[,;!\^\s#()\[\]\{\}"'<>]))/,this._variable=/^\?(?:(?:[A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?=[.,;!\^\s#()\[\]\{\}"'<>])/,this._blank=/^_:((?:[0-9A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?:[ \t]+|(?=\.?[,;:\s#()\[\]\{\}"'<>]))/,this._number=/^[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?|\d*(\.)?)\d+(?=\.?[,;:\s#()\[\]\{\}"'<>])/,this._boolean=/^(?:true|false)(?=[.,;\s#()\[\]\{\}"'<>])/,this._keyword=/^@[a-z]+(?=[\s#<:])/i,this._sparqlKeyword=/^(?:PREFIX|BASE|GRAPH)(?=[\s#<])/i,this._shortPredicates=/^a(?=[\s#()\[\]\{\}"'<>])/,this._newline=/^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/,this._comment=/#([^\n\r]*)/,this._whitespace=/^[ \t]+/,this._endOfFile=/^(?:#[^\n\r]*)?$/,e=e||{},this._isImpliedBy=e.isImpliedBy,this._lineMode=!!e.lineMode){this._n3Mode=!1;for(const r in this)!(r in _a)&&this[r]instanceof RegExp&&(this[r]=wa)}else this._n3Mode=e.n3!==!1;this.comments=!!e.comments,this._literalClosingPos=0}_tokenizeToEnd(e,r){let s=this._input,a=s.length;for(;;){let c,l;for(;c=this._newline.exec(s);)this.comments&&(l=this._comment.exec(c[0]))&&i("comment",l[1],"",this._line,c[0].length),s=s.substr(c[0].length,s.length),a=s.length,this._line++;if(!c&&(c=this._whitespace.exec(s))&&(s=s.substr(c[0].length,s.length)),this._endOfFile.test(s))return r&&(this.comments&&(l=this._comment.exec(s))&&i("comment",l[1],"",this._line,s.length),s=null,i("eof","","",this._line,0)),this._input=s;const h=this._line,u=s[0];let g="",f="",v="",p=null,m=0,b=!1;switch(u){case"^":if(s.length<3)break;if(s[1]==="^"){if(this._previousMarker="^^",s=s.substr(2),s[0]!=="<"){b=!0;break}}else{this._n3Mode&&(m=1,g="^");break}case"<":if(p=this._unescapedIri.exec(s))g="IRI",f=p[1];else if(p=this._iri.exec(s)){if(f=this._unescape(p[1]),f===null||va.test(f))return o(this);g="IRI"}else s.length>1&&s[1]==="<"?(g="<<",m=2):this._n3Mode&&s.length>1&&s[1]==="="&&(m=2,this._isImpliedBy?(g="abbreviation",f="<"):(g="inverse",f=">"));break;case">":s.length>1&&s[1]===">"&&(g=">>",m=2);break;case"_":((p=this._blank.exec(s))||r&&(p=this._blank.exec(`${s} `)))&&(g="blank",v="_",f=p[1]);break;case'"':if(p=this._simpleQuotedString.exec(s))f=p[1];else if({value:f,matchLength:m}=this._parseLiteral(s),f===null)return o(this);(p!==null||m!==0)&&(g="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(p=this._simpleApostropheString.exec(s))f=p[1];else if({value:f,matchLength:m}=this._parseLiteral(s),f===null)return o(this);(p!==null||m!==0)&&(g="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(p=this._variable.exec(s))&&(g="var",f=p[0]);break;case"@":this._previousMarker==="literal"&&(p=this._langcode.exec(s))?(g="langcode",f=p[1]):(p=this._keyword.exec(s))&&(g=p[0]);break;case".":if(s.length===1?r:s[1]<"0"||s[1]>"9"){g=".",m=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":(p=this._number.exec(s)||r&&(p=this._number.exec(`${s} `)))&&(g="literal",f=p[0],v=typeof p[1]=="string"?Te.double:typeof p[2]=="string"?Te.decimal:Te.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":(p=this._sparqlKeyword.exec(s))?g=p[0].toUpperCase():b=!0;break;case"f":case"t":(p=this._boolean.exec(s))?(g="literal",f=p[0],v=Te.boolean):b=!0;break;case"a":(p=this._shortPredicates.exec(s))?(g="abbreviation",f="a"):b=!0;break;case"=":this._n3Mode&&s.length>1&&(g="abbreviation",s[1]!==">"?(m=1,f="="):(m=2,f=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(m=1,g=u);break;case"{":!this._lineMode&&s.length>=2&&(s[1]==="|"?(g="{|",m=2):(g=u,m=1));break;case"|":s.length>=2&&s[1]==="}"&&(g="|}",m=2);break;default:b=!0}if(b&&((this._previousMarker==="@prefix"||this._previousMarker==="PREFIX")&&(p=this._prefix.exec(s))?(g="prefix",f=p[1]||""):((p=this._prefixed.exec(s))||r&&(p=this._prefixed.exec(`${s} `)))&&(g="prefixed",v=p[1]||"",f=this._unescape(p[2]))),this._previousMarker==="^^")switch(g){case"prefixed":g="type";break;case"IRI":g="typeIRI";break;default:g=""}if(!g)return r||!/^'''|^"""/.test(s)&&/\n|\r/.test(s)?o(this):this._input=s;const S=m||p[0].length,N=i(g,f,v,h,S);this.previousToken=N,this._previousMarker=g,s=s.substr(S,s.length)}function i(c,l,h,u,g){const f=s?a-s.length:a,v=f+g,p={type:c,value:l,prefix:h,line:u,start:f,end:v};return e(null,p),p}function o(c){e(c._syntaxError(/^\S*/.exec(s)[0]))}}_unescape(e){let r=!1;const s=e.replace(xa,(a,i,o,c)=>{if(typeof i=="string")return String.fromCharCode(Number.parseInt(i,16));if(typeof o=="string"){let l=Number.parseInt(o,16);return l<=65535?String.fromCharCode(Number.parseInt(o,16)):String.fromCharCode(55296+((l-=65536)>>10),56320+(l&1023))}return c in Xt?Xt[c]:(r=!0,"")});return r?null:s}_parseLiteral(e){if(e.length>=3){const r=e.match(/^(?:"""|"|'''|'|)/)[0],s=r.length;let a=Math.max(this._literalClosingPos,s);for(;(a=e.indexOf(r,a))>0;){let i=0;for(;e[a-i-1]==="\\";)i++;if(i%2===0){const o=e.substring(s,a),c=o.split(/\r\n|\r|\n/).length-1,l=a+s;if(s===1&&c!==0||s===3&&this._lineMode)break;return this._line+=c,{value:this._unescape(o),matchLength:l}}a++}this._literalClosingPos=e.length-s+1}return{value:"",matchLength:0}}_syntaxError(e){this._input=null;const r=new Error(`Unexpected "${e}" on line ${this._line}.`);return r.context={token:void 0,line:this._line,previousToken:this.previousToken},r}_readStartingBom(e){return e.startsWith("\uFEFF")?e.substr(1):e}tokenize(e,r){if(this._line=1,typeof e=="string")if(this._input=this._readStartingBom(e),typeof r=="function")queueMicrotask(()=>this._tokenizeToEnd(r,!0));else{const s=[];let a;if(this._tokenizeToEnd((i,o)=>i?a=i:s.push(o),!0),a)throw a;return s}else this._pendingBuffer=null,typeof e.setEncoding=="function"&&e.setEncoding("utf8"),e.on("data",s=>{this._input!==null&&s.length!==0&&(this._pendingBuffer&&(s=ks.Buffer.concat([this._pendingBuffer,s]),this._pendingBuffer=null),s[s.length-1]&128?this._pendingBuffer=s:(typeof this._input>"u"?this._input=this._readStartingBom(typeof s=="string"?s:s.toString()):this._input+=s,this._tokenizeToEnd(r,!1)))}),e.on("end",()=>{typeof this._input=="string"&&this._tokenizeToEnd(r,!0)}),e.on("error",r)}}const{rdf:ja,xsd:me}=Z;let Pe,Ia=0;const Na={namedNode:zr,blankNode:Mr,variable:qr,literal:Xr,defaultGraph:Pa,quad:it,triple:it,fromTerm:Ie,fromQuad:Gr};class ie{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof ie?this.id===e.id:!!e&&this.termType===e.termType&&this.value===e.value}hashCode(){return 0}toJSON(){return{termType:this.termType,value:this.value}}}class $r extends ie{get termType(){return"NamedNode"}}class ke extends ie{get termType(){return"Literal"}get value(){return this.id.substring(1,this.id.lastIndexOf('"'))}get language(){const e=this.id;let r=e.lastIndexOf('"')+1;return r<e.length&&e[r++]==="@"?e.substr(r).toLowerCase():""}get datatype(){return new $r(this.datatypeString)}get datatypeString(){const e=this.id,r=e.lastIndexOf('"')+1,s=r<e.length?e[r]:"";return s==="^"?e.substr(r+2):s!=="@"?me.string:ja.langString}equals(e){return e instanceof ke?this.id===e.id:!!e&&!!e.datatype&&this.termType===e.termType&&this.value===e.value&&this.language===e.language&&this.datatype.value===e.datatype.value}toJSON(){return{termType:this.termType,value:this.value,language:this.language,datatype:{termType:"NamedNode",value:this.datatypeString}}}}class Sa extends ie{constructor(e){super(`_:${e}`)}get termType(){return"BlankNode"}get value(){return this.id.substr(2)}}class ka extends ie{constructor(e){super(`?${e}`)}get termType(){return"Variable"}get value(){return this.id.substr(1)}}class Ra extends ie{constructor(){return super(""),Pe||this}get termType(){return"DefaultGraph"}equals(e){return this===e||!!e&&this.termType===e.termType}}Pe=new Ra;class Br extends ie{constructor(e,r,s,a){super(""),this._subject=e,this._predicate=r,this._object=s,this._graph=a||Pe}get termType(){return"Quad"}get subject(){return this._subject}get predicate(){return this._predicate}get object(){return this._object}get graph(){return this._graph}toJSON(){return{termType:this.termType,subject:this._subject.toJSON(),predicate:this._predicate.toJSON(),object:this._object.toJSON(),graph:this._graph.toJSON()}}equals(e){return!!e&&this._subject.equals(e.subject)&&this._predicate.equals(e.predicate)&&this._object.equals(e.object)&&this._graph.equals(e.graph)}}function zr(t){return new $r(t)}function Mr(t){return new Sa(t||`n3-${Ia++}`)}function Xr(t,e){if(typeof e=="string")return new ke(`"${t}"@${e.toLowerCase()}`);let r=e?e.value:"";return r===""&&(typeof t=="boolean"?r=me.boolean:typeof t=="number"&&(Number.isFinite(t)?r=Number.isInteger(t)?me.integer:me.double:(r=me.double,Number.isNaN(t)||(t=t>0?"INF":"-INF")))),r===""||r===me.string?new ke(`"${t}"`):new ke(`"${t}"^^${r}`)}function qr(t){return new ka(t)}function Pa(){return Pe}function it(t,e,r,s){return new Br(t,e,r,s)}function Ie(t){if(t instanceof ie)return t;switch(t.termType){case"NamedNode":return zr(t.value);case"BlankNode":return Mr(t.value);case"Variable":return qr(t.value);case"DefaultGraph":return Pe;case"Literal":return Xr(t.value,t.language||t.datatype);case"Quad":return Gr(t);default:throw new Error(`Unexpected termType: ${t.termType}`)}}function Gr(t){if(t instanceof Br)return t;if(t.termType!=="Quad")throw new Error(`Unexpected termType: ${t.termType}`);return it(Ie(t.subject),Ie(t.predicate),Ie(t.object),Ie(t.graph))}let qt=0;class Wr{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&Hr(this,e.factory);const r=typeof e.format=="string"?e.format.match(/\w*$/)[0].toLowerCase():"",s=/turtle/.test(r),a=/trig/.test(r),i=/triple/.test(r),o=/quad/.test(r),c=this._n3Mode=/n3/.test(r),l=i||o;(this._supportsNamedGraphs=!(s||c))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(s||a||i||c),this._isImpliedBy=e.isImpliedBy,this._supportsRDFStar=r===""||/star|\*$/.test(r),l&&(this._resolveRelativeIRI=h=>null),this._blankNodePrefix=typeof e.blankNodePrefix!="string"?"":e.blankNodePrefix.replace(/^(?!_:)/,"_:"),this._lexer=e.lexer||new ya({lineMode:l,n3:c,isImpliedBy:this._isImpliedBy}),this._explicitQuantifiers=!!e.explicitQuantifiers}static _resetBlankNodePrefix(){qt=0}_setBase(e){if(!e)this._base="",this._basePath="";else{const r=e.indexOf("#");r>=0&&(e=e.substr(0,r)),this._base=e,this._basePath=e.indexOf("/")<0?e:e.replace(/[^\/?]*(?:\?.*)?$/,""),e=e.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i),this._baseRoot=e[0],this._baseScheme=e[1]}}_saveContext(e,r,s,a,i){const o=this._n3Mode;this._contextStack.push({type:e,subject:s,predicate:a,object:i,graph:r,inverse:o?this._inversePredicate:!1,blankPrefix:o?this._prefixes._:"",quantified:o?this._quantified:null}),o&&(this._inversePredicate=!1,this._prefixes._=this._graph?`${this._graph.value}.`:".",this._quantified=Object.create(this._quantified))}_restoreContext(e,r){const s=this._contextStack.pop();if(!s||s.type!==e)return this._error(`Unexpected ${r.type}`,r);this._subject=s.subject,this._predicate=s.predicate,this._object=s.object,this._graph=s.graph,this._n3Mode&&(this._inversePredicate=s.inverse,this._prefixes._=s.blankPrefix,this._quantified=s.quantified)}_readInTopContext(e){switch(e.type){case"eof":return this._graph!==null?this._error("Unclosed graph",e):(delete this._prefixes._,this._callback(null,null,this._prefixes));case"PREFIX":this._sparqlStyle=!0;case"@prefix":return this._readPrefix;case"BASE":this._sparqlStyle=!0;case"@base":return this._readBaseIRI;case"{":if(this._supportsNamedGraphs)return this._graph="",this._subject=null,this._readSubject;case"GRAPH":if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return this._readSubject(e)}}_readEntity(e,r){let s;switch(e.type){case"IRI":case"typeIRI":const a=this._resolveIRI(e.value);if(a===null)return this._error("Invalid IRI",e);s=this._factory.namedNode(a);break;case"type":case"prefixed":const i=this._prefixes[e.prefix];if(i===void 0)return this._error(`Undefined prefix "${e.prefix}:"`,e);s=this._factory.namedNode(i+e.value);break;case"blank":s=this._factory.blankNode(this._prefixes[e.prefix]+e.value);break;case"var":s=this._factory.variable(e.value.substr(1));break;default:return this._error(`Expected entity but got ${e.type}`,e)}return!r&&this._n3Mode&&s.id in this._quantified&&(s=this._quantified[s.id]),s}_readSubject(e){switch(this._predicate=null,e.type){case"[":return this._saveContext("blank",this._graph,this._subject=this._factory.blankNode(),null,null),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this.RDF_NIL,null,null),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._graph=this._factory.blankNode(),null,null),this._readSubject):this._error("Unexpected graph",e);case"}":return this._readPunctuation(e);case"@forSome":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORSOME,this._quantifier="blankNode",this._readQuantifierList):this._error('Unexpected "@forSome"',e);case"@forAll":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORALL,this._quantifier="variable",this._readQuantifierList):this._error('Unexpected "@forAll"',e);case"literal":if(!this._n3Mode)return this._error("Unexpected literal",e);if(e.prefix.length===0)return this._literalValue=e.value,this._completeSubjectLiteral;this._subject=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,null,null,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if((this._subject=this._readEntity(e))===void 0)return;if(this._n3Mode)return this._getPathReader(this._readPredicateOrNamedGraph)}return this._readPredicateOrNamedGraph}_readPredicate(e){const r=e.type;switch(r){case"inverse":this._inversePredicate=!0;case"abbreviation":this._predicate=this.ABBREVIATIONS[e.value];break;case".":case"]":case"}":return this._predicate===null?this._error(`Unexpected ${r}`,e):(this._subject=null,r==="]"?this._readBlankNodeTail(e):this._readPunctuation(e));case";":return this._predicate!==null?this._readPredicate:this._error("Expected predicate but got ;",e);case"[":if(this._n3Mode)return this._saveContext("blank",this._graph,this._subject,this._subject=this._factory.blankNode(),null),this._readBlankNodeHead;case"blank":if(!this._n3Mode)return this._error("Disallowed blank node as predicate",e);default:if((this._predicate=this._readEntity(e))===void 0)return}return this._readObject}_readObject(e){switch(e.type){case"literal":if(e.prefix.length===0)return this._literalValue=e.value,this._readDataTypeOrLang;this._object=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"[":return this._saveContext("blank",this._graph,this._subject,this._predicate,this._subject=this._factory.blankNode()),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this._subject,this._predicate,this.RDF_NIL),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,this._subject,this._predicate,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if((this._object=this._readEntity(e))===void 0)return;if(this._n3Mode)return this._getPathReader(this._getContextEndReader())}return this._getContextEndReader()}_readPredicateOrNamedGraph(e){return e.type==="{"?this._readGraph(e):this._readPredicate(e)}_readGraph(e){return e.type!=="{"?this._error(`Expected graph but got ${e.type}`,e):(this._graph=this._subject,this._subject=null,this._readSubject)}_readBlankNodeHead(e){return e.type==="]"?(this._subject=null,this._readBlankNodeTail(e)):(this._predicate=null,this._readPredicate(e))}_readBlankNodeTail(e){if(e.type!=="]")return this._readBlankNodePunctuation(e);this._subject!==null&&this._emit(this._subject,this._predicate,this._object,this._graph);const r=this._predicate===null;return this._restoreContext("blank",e),this._object!==null?this._getContextEndReader():this._predicate!==null?this._readObject:r?this._readPredicateOrNamedGraph:this._readPredicateAfterBlank}_readPredicateAfterBlank(e){switch(e.type){case".":case"}":return this._subject=null,this._readPunctuation(e);default:return this._readPredicate(e)}}_readListItem(e){let r=null,s=null,a=this._readListItem;const i=this._subject,o=this._contextStack,c=o[o.length-1];switch(e.type){case"[":this._saveContext("blank",this._graph,s=this._factory.blankNode(),this.RDF_FIRST,this._subject=r=this._factory.blankNode()),a=this._readBlankNodeHead;break;case"(":this._saveContext("list",this._graph,s=this._factory.blankNode(),this.RDF_FIRST,this.RDF_NIL),this._subject=null;break;case")":if(this._restoreContext("list",e),o.length!==0&&o[o.length-1].type==="list"&&this._emit(this._subject,this._predicate,this._object,this._graph),this._predicate===null){if(a=this._readPredicate,this._subject===this.RDF_NIL)return a}else if(a=this._getContextEndReader(),this._object===this.RDF_NIL)return a;s=this.RDF_NIL;break;case"literal":e.prefix.length===0?(this._literalValue=e.value,a=this._readListItemDataTypeOrLang):(r=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),a=this._getContextEndReader());break;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);default:if((r=this._readEntity(e))===void 0)return}if(s===null&&(this._subject=s=this._factory.blankNode()),i===null?c.predicate===null?c.subject=s:c.object=s:this._emit(i,this.RDF_REST,s,this._graph),r!==null){if(this._n3Mode&&(e.type==="IRI"||e.type==="prefixed"))return this._saveContext("item",this._graph,s,this.RDF_FIRST,r),this._subject=r,this._predicate=null,this._getPathReader(this._readListItem);this._emit(s,this.RDF_FIRST,r,this._graph)}return a}_readDataTypeOrLang(e){return this._completeObjectLiteral(e,!1)}_readListItemDataTypeOrLang(e){return this._completeObjectLiteral(e,!0)}_completeLiteral(e){let r=this._factory.literal(this._literalValue);switch(e.type){case"type":case"typeIRI":const s=this._readEntity(e);if(s===void 0)return;r=this._factory.literal(this._literalValue,s),e=null;break;case"langcode":r=this._factory.literal(this._literalValue,e.value),e=null;break}return{token:e,literal:r}}_completeSubjectLiteral(e){return this._subject=this._completeLiteral(e).literal,this._readPredicateOrNamedGraph}_completeObjectLiteral(e,r){const s=this._completeLiteral(e);if(s)return this._object=s.literal,r&&this._emit(this._subject,this.RDF_FIRST,this._object,this._graph),s.token===null?this._getContextEndReader():(this._readCallback=this._getContextEndReader(),this._readCallback(s.token))}_readFormulaTail(e){return e.type!=="}"?this._readPunctuation(e):(this._subject!==null&&this._emit(this._subject,this._predicate,this._object,this._graph),this._restoreContext("formula",e),this._object===null?this._readPredicate:this._getContextEndReader())}_readPunctuation(e){let r,s=this._graph;const a=this._subject,i=this._inversePredicate;switch(e.type){case"}":if(this._graph===null)return this._error("Unexpected graph closing",e);if(this._n3Mode)return this._readFormulaTail(e);this._graph=null;case".":this._subject=null,r=this._contextStack.length?this._readSubject:this._readInTopContext,i&&(this._inversePredicate=!1);break;case";":r=this._readPredicate;break;case",":r=this._readObject;break;case"{|":if(!this._supportsRDFStar)return this._error("Unexpected RDF-star syntax",e);const o=this._predicate,c=this._object;this._subject=this._factory.quad(a,o,c,this.DEFAULTGRAPH),r=this._readPredicate;break;case"|}":if(this._subject.termType!=="Quad")return this._error("Unexpected asserted triple closing",e);this._subject=null,r=this._readPunctuation;break;default:if(this._supportsQuads&&this._graph===null&&(s=this._readEntity(e))!==void 0){r=this._readQuadPunctuation;break}return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}if(a!==null){const o=this._predicate,c=this._object;i?this._emit(c,o,a,s):this._emit(a,o,c,s)}return r}_readBlankNodePunctuation(e){let r;switch(e.type){case";":r=this._readPredicate;break;case",":r=this._readObject;break;default:return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}return this._emit(this._subject,this._predicate,this._object,this._graph),r}_readQuadPunctuation(e){return e.type!=="."?this._error("Expected dot to follow quad",e):this._readInTopContext}_readPrefix(e){return e.type!=="prefix"?this._error("Expected prefix to follow @prefix",e):(this._prefix=e.value,this._readPrefixIRI)}_readPrefixIRI(e){if(e.type!=="IRI")return this._error(`Expected IRI to follow prefix "${this._prefix}:"`,e);const r=this._readEntity(e);return this._prefixes[this._prefix]=r.value,this._prefixCallback(this._prefix,r),this._readDeclarationPunctuation}_readBaseIRI(e){const r=e.type==="IRI"&&this._resolveIRI(e.value);return r?(this._setBase(r),this._readDeclarationPunctuation):this._error("Expected valid IRI to follow base declaration",e)}_readNamedGraphLabel(e){switch(e.type){case"IRI":case"blank":case"prefixed":return this._readSubject(e),this._readGraph;case"[":return this._readNamedGraphBlankLabel;default:return this._error("Invalid graph label",e)}}_readNamedGraphBlankLabel(e){return e.type!=="]"?this._error("Invalid graph label",e):(this._subject=this._factory.blankNode(),this._readGraph)}_readDeclarationPunctuation(e){return this._sparqlStyle?(this._sparqlStyle=!1,this._readInTopContext(e)):e.type!=="."?this._error("Expected declaration to end with a dot",e):this._readInTopContext}_readQuantifierList(e){let r;switch(e.type){case"IRI":case"prefixed":if((r=this._readEntity(e,!0))!==void 0)break;default:return this._error(`Unexpected ${e.type}`,e)}return this._explicitQuantifiers?(this._subject===null?this._emit(this._graph||this.DEFAULTGRAPH,this._predicate,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH):this._emit(this._subject,this.RDF_REST,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH),this._emit(this._subject,this.RDF_FIRST,r,this.QUANTIFIERS_GRAPH)):this._quantified[r.id]=this._factory[this._quantifier](this._factory.blankNode().value),this._readQuantifierPunctuation}_readQuantifierPunctuation(e){return e.type===","?this._readQuantifierList:(this._explicitQuantifiers&&(this._emit(this._subject,this.RDF_REST,this.RDF_NIL,this.QUANTIFIERS_GRAPH),this._subject=null),this._readCallback=this._getContextEndReader(),this._readCallback(e))}_getPathReader(e){return this._afterPath=e,this._readPath}_readPath(e){switch(e.type){case"!":return this._readForwardPath;case"^":return this._readBackwardPath;default:const r=this._contextStack,s=r.length&&r[r.length-1];if(s&&s.type==="item"){const a=this._subject;this._restoreContext("item",e),this._emit(this._subject,this.RDF_FIRST,a,this._graph)}return this._afterPath(e)}}_readForwardPath(e){let r,s;const a=this._factory.blankNode();if((s=this._readEntity(e))!==void 0)return this._predicate===null?(r=this._subject,this._subject=a):(r=this._object,this._object=a),this._emit(r,s,a,this._graph),this._readPath}_readBackwardPath(e){const r=this._factory.blankNode();let s,a;if((s=this._readEntity(e))!==void 0)return this._predicate===null?(a=this._subject,this._subject=r):(a=this._object,this._object=r),this._emit(r,s,a,this._graph),this._readPath}_readRDFStarTailOrGraph(e){return e.type!==">>"?this._supportsQuads&&this._graph===null&&(this._graph=this._readEntity(e))!==void 0?this._readRDFStarTail:this._error(`Expected >> to follow "${this._object.id}"`,e):this._readRDFStarTail(e)}_readRDFStarTail(e){if(e.type!==">>")return this._error(`Expected >> but got ${e.type}`,e);const r=this._factory.quad(this._subject,this._predicate,this._object,this._graph||this.DEFAULTGRAPH);return this._restoreContext("<<",e),this._subject===null?(this._subject=r,this._readPredicate):(this._object=r,this._getContextEndReader())}_getContextEndReader(){const e=this._contextStack;if(!e.length)return this._readPunctuation;switch(e[e.length-1].type){case"blank":return this._readBlankNodeTail;case"list":return this._readListItem;case"formula":return this._readFormulaTail;case"<<":return this._readRDFStarTailOrGraph}}_emit(e,r,s,a){this._callback(null,this._factory.quad(e,r,s,a||this.DEFAULTGRAPH))}_error(e,r){const s=new Error(`${e} on line ${r.line}.`);s.context={token:r,line:r.line,previousToken:this._lexer.previousToken},this._callback(s),this._callback=Ue}_resolveIRI(e){return/^[a-z][a-z0-9+.-]*:/i.test(e)?e:this._resolveRelativeIRI(e)}_resolveRelativeIRI(e){if(!e.length)return this._base;switch(e[0]){case"#":return this._base+e;case"?":return this._base.replace(/(?:\?.*)?$/,e);case"/":return(e[1]==="/"?this._baseScheme:this._baseRoot)+this._removeDotSegments(e);default:return/^[^/:]*:/.test(e)?null:this._removeDotSegments(this._basePath+e)}}_removeDotSegments(e){if(!/(^|\/)\.\.?($|[/#?])/.test(e))return e;const r=e.length;let s="",a=-1,i=-1,o=0,c="/";for(;a<r;){switch(c){case":":if(i<0&&e[++a]==="/"&&e[++a]==="/")for(;(i=a+1)<r&&e[i]!=="/";)a=i;break;case"?":case"#":a=r;break;case"/":if(e[a+1]===".")switch(c=e[++a+1],c){case"/":s+=e.substring(o,a-1),o=a+1;break;case void 0:case"?":case"#":return s+e.substring(o,a)+e.substr(a+1);case".":if(c=e[++a+1],c===void 0||c==="/"||c==="?"||c==="#"){if(s+=e.substring(o,a-2),(o=s.lastIndexOf("/"))>=i&&(s=s.substr(0,o)),c!=="/")return`${s}/${e.substr(a+1)}`;o=a+1}}}c=e[++a]}return s+e.substring(o)}parse(e,r,s){let a,i,o;if(r&&(r.onQuad||r.onPrefix||r.onComment)?(a=r.onQuad,i=r.onPrefix,o=r.onComment):(a=r,i=s),this._readCallback=this._readInTopContext,this._sparqlStyle=!1,this._prefixes=Object.create(null),this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${qt++}_`,this._prefixCallback=i||Ue,this._inversePredicate=!1,this._quantified=Object.create(null),!a){const l=[];let h;if(this._callback=(u,g)=>{u?h=u:g&&l.push(g)},this._lexer.tokenize(e).every(u=>this._readCallback=this._readCallback(u)),h)throw h;return l}let c=(l,h)=>{l!==null?(this._callback(l),this._callback=Ue):this._readCallback&&(this._readCallback=this._readCallback(h))};o&&(this._lexer.comments=!0,c=(l,h)=>{l!==null?(this._callback(l),this._callback=Ue):this._readCallback&&(h.type==="comment"?o(h.value):this._readCallback=this._readCallback(h))}),this._callback=a,this._lexer.tokenize(e,c)}}function Ue(){}function Hr(t,e){t._factory=e,t.DEFAULTGRAPH=e.defaultGraph(),t.RDF_FIRST=e.namedNode(Z.rdf.first),t.RDF_REST=e.namedNode(Z.rdf.rest),t.RDF_NIL=e.namedNode(Z.rdf.nil),t.N3_FORALL=e.namedNode(Z.r.forAll),t.N3_FORSOME=e.namedNode(Z.r.forSome),t.ABBREVIATIONS={a:e.namedNode(Z.rdf.type),"=":e.namedNode(Z.owl.sameAs),">":e.namedNode(Z.log.implies),"<":e.namedNode(Z.log.isImpliedBy)},t.QUANTIFIERS_GRAPH=e.namedNode("urn:n3:quantifiers")}Hr(Wr.prototype,Na);async function La(t,e={}){const r=e.webId??t.info?.webId;if(!r?.trim()||typeof t.fetch!="function")return null;const s=Ua(r),a=await t.fetch(s,{headers:{Accept:"text/turtle, application/ld+json;q=0.9, text/n3;q=0.8, */*;q=0.1"}});if(!a.ok)throw new Error(`Failed to fetch WebID profile: ${a.status} ${a.statusText}`.trim());const i=a.headers.get("content-type")??"",o=await a.text();if(!o.trim())return Gt(r,null);const c=await Ca(o,{contentType:i,profileDocumentUrl:s,webId:r});return Gt(r,c)}async function Ca(t,e){return(e.contentType?.toLowerCase()??"").includes("application/ld+json")||t.trimStart().startsWith("{")?Aa(t,e.webId):await Ea(t,e)}async function Ea(t,e){const r=Wr,a=new r({baseIRI:e.profileDocumentUrl}).parse(t);return Ta(a,e.webId)}function Aa(t,e){try{const r=JSON.parse(t),s=Array.isArray(r)?r:Ne(r)&&Array.isArray(r["@graph"])?r["@graph"]:[r],a=s.find(o=>Ne(o)&&o["@id"]===e),i=Ne(a)?a:s.find(Ne);return i?Vr({id:e,name:le(i,Q.fn),nick:le(i,hr.nick),avatar:le(i,Q.hasPhoto),note:le(i,Q.note),email:le(i,Q.hasEmail),phone:le(i,Q.hasTelephone),region:le(i,Q.region),gender:le(i,Q.hasGender)}):null}catch{return null}}function Ta(t,e){const r={id:e};for(const s of t){if(s.subject.value!==e)continue;const a=s.predicate.value,i=s.object.value;!a||!i||(a===Q.fn?r.name=i:a===hr.nick?r.nick=i:a===Q.hasPhoto?r.avatar=i:a===Q.note?r.note=i:a===Q.hasEmail?r.email=i:a===Q.hasTelephone?r.phone=i:a===Q.region?r.region=i:a===Q.hasGender&&(r.gender=i))}return Vr(r)}function Gt(t,e){return{webId:t,profile:e,displayName:Rs(e),username:ba(t)}}function Vr(t){const e=Object.fromEntries(Object.entries(t).filter(([,r])=>typeof r=="string"&&r.trim()));return Object.keys(e).length>1?e:null}function le(t,e){return ot(t[e])}function ot(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(ot).find(Boolean);if(Ne(t))return ot(t["@value"]??t["@id"])}function Ua(t){const e=t.indexOf("#");return e>=0?t.slice(0,e):t}function Ne(t){return typeof t=="object"&&t!==null}function _t({accountIdentity:t,runtime:e}){const r=e?.state.status,s=r==="authenticated"&&e?e.webId??e.state.webId:t?.webId,a=r==="authenticated"&&s?void 0:t,i=a?.displayName,o=a?.username,c=a?.id,l=a?.webId,h=e?.fetch,u=d.useMemo(()=>Da({displayName:i,username:o,id:c},s),[i,c,o,l,s]),g=`${s??""}\0${u.displayName}\0${u.username??""}`,[f,v]=d.useState(),[p,m]=d.useState(!1);d.useEffect(()=>{const S=h;if(r!=="authenticated"||!S||!s)return;let N=!1,x;async function I(k,R){m(!0);try{const y=await La({info:{webId:R},fetch:k});if(N||!y)return;const A=Fa(y.profile?.avatar);let j=A;if(A&&(j=await Oa(k,A),x=j?.startsWith("blob:")?j:void 0),N){x&&URL.revokeObjectURL(x);return}v({key:g,value:{displayName:y.displayName??y.username??u.displayName,username:y.username||u.username,avatarUrl:j??u.avatarUrl,avatarSourceUrl:A,note:y.profile?.note||u.note,region:y.profile?.region||u.region,webId:y.webId||u.webId,loading:!1,source:"webid-profile"}})}catch{N||v(void 0)}finally{N||m(!1)}}return I(S,s),()=>{N=!0,x&&URL.revokeObjectURL(x)}},[h,u,g,r,s]);const b=r==="authenticated"?p:!1;return r==="authenticated"&&f?.key===g?{...f.value,loading:b}:{...u,loading:b}}function Da(t,e){const r=t?.username||$a(e)||t?.id;return{displayName:t?.displayName||r||t?.id||"Xpod account",username:r,webId:e,loading:!1,source:"account"}}async function Oa(t,e){try{const r=await t(e);if(!r.ok)return e;const s=await r.blob();return URL.createObjectURL(s)}catch{return e}}function Fa(t){if(t)try{const e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"?e.href:void 0}catch{return}}function $a(t){if(t)try{const e=new URL(t);return e.pathname.split("/").filter(Boolean).at(0)||e.hostname}catch{return}}const Ba=d.createContext(null);function za({value:t,children:e}){return d.createElement(Ba.Provider,{value:t},e)}async function Ma(t){const{Parser:e,Writer:r,DataFactory:s}=await ae(async()=>{const{Parser:_,Writer:C,DataFactory:$}=await import("./index-gtv-MAHl.js");return{Parser:_,Writer:C,DataFactory:$}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])),{UDFS:a,RDF:i}=await ae(async()=>{const{UDFS:_,RDF:C}=await import("./xpod-remembered-login-nv1g1sfC.js").then($=>$.by);return{UDFS:_,RDF:C}},__vite__mapDeps([3,4,1,2,5,6,7])),o=new URL(t.approval),c=new URL(t.decisionBy);if(![o,c].every(_=>["https:","http:"].includes(_.protocol)&&!_.username&&!_.password))throw new Error("Approval and decision identity must be HTTP(S) IRIs without credentials.");if(!["approved","rejected"].includes(t.decision))throw new Error("Invalid approval decision.");const l=o.href;o.hash="";const h=o.href,u=await t.authenticatedFetch(h,{headers:{accept:"text/turtle"},cache:"no-store",redirect:"error"});if(u.status===404)return{status:"not_found"};if(!u.ok)throw new Error(`Approval read failed: HTTP ${u.status}`);const g=u.headers.get("etag"),f=await u.text();if(!g||!/^"[^"\r\n]+"$/.test(g))return{status:"unavailable",reason:"A strong ETag is required for approval decisions."};if(!u.headers.get("content-type")?.toLowerCase().includes("text/turtle"))return{status:"unavailable",reason:"The approval document must be served as Turtle."};const v=new e({baseIRI:h}).parse(f),p=_=>v.filter(C=>C.subject.termType==="NamedNode"&&C.subject.value===l&&C.predicate.value===_).map(C=>C.object);if(!p(i.type).some(_=>_.termType==="NamedNode"&&_.value===a.ApprovalRequest))return{status:"not_found"};const m=p(a.status);if(m.length!==1||m[0].termType!=="Literal"||!["pending","handling"].includes(m[0].value)||p(a.resolvedAt).length)return{status:"not_actionable",reason:"Approval is already decided or has ambiguous state."};if(p(a.assignedTo).some(_=>_.termType!=="NamedNode"||_.value!==c.href))return{status:"not_actionable",reason:"Approval belongs to another decision maker."};const S=t.now??(()=>new Date),N=()=>p(a.expiresAt).some(_=>{const C=Date.parse(_.value);return!Number.isFinite(C)||C<=S().getTime()});if(N())return{status:"not_actionable",reason:"Approval has expired."};const x=p(a.leaseOwner),I=p(a.leaseExpiresAt);if((x.length||I.length)&&(x.length!==1||x[0].termType!=="Literal"||I.length!==1||I[0].termType!=="Literal"||!Number.isFinite(Date.parse(I[0].value))||Date.parse(I[0].value)>S().getTime()))return{status:"conflict",reason:"Approval is being handled by another client."};const k=new Set([a.status,a.decisionBy,a.resolvedAt]),R=v.filter(_=>_.subject.value!==l||!k.has(_.predicate.value)),y=s.namedNode(l);R.push(s.quad(y,s.namedNode(a.status),s.literal(t.decision)),s.quad(y,s.namedNode(a.decisionBy),s.namedNode(c.href)),s.quad(y,s.namedNode(a.resolvedAt),s.literal(S().toISOString(),s.namedNode("http://www.w3.org/2001/XMLSchema#dateTime"))));const A=await new Promise((_,C)=>{const $=new r({format:"Turtle"});$.addQuads(R),$.end((T,V)=>T?C(T):_(V))});if(t.isCurrent&&!t.isCurrent())return{status:"not_actionable",reason:"The current session changed."};if(N())return{status:"not_actionable",reason:"Approval has expired."};const j=await t.authenticatedFetch(h,{method:"PUT",headers:{"content-type":"text/turtle","if-match":g},body:A,redirect:"error"});if(await j.arrayBuffer(),j.status===412)return{status:"conflict",reason:"Another client changed the approval. Refresh before deciding again."};if(!j.ok)throw new Error(`Approval decision failed: HTTP ${j.status}`);return{status:"decided"}}const Le=Ps;function Xa(){const t=vr(),e=Le(),r=e.selectedStorage,s=_t({accountIdentity:t.identity,runtime:e}),a=e.state.status==="authenticated"?e.webId??e.state.webId:void 0,i=Be(),o=Ls(t.idpIndex),c=t.isInitializing?void 0:_r(t.idpIndex),l=c?new URL(c).origin:void 0,h=l?fr(void 0,t.idpIndex):void 0,u=o===!0?h??(i&&i.issuer===l?i.account.email:void 0):void 0;return d.useEffect(()=>{!l||o===!1||!a||!r||!e.currentPod||r.webId===a&&(e.currentPod.webId!==a||e.currentPod.podUrl!==r.storageUrl||i&&!Cs(i,{accountIdentity:t.identity,accountEmail:h,webId:a,selectedStorage:r})||Es({issuer:l,account:{...u?{email:u}:{},...t.identity??{},displayName:s.displayName,...s.username?{username:s.username}:{},...s.avatarSourceUrl??i?.account.avatarUrl?{avatarUrl:s.avatarSourceUrl??i?.account.avatarUrl}:{}},webId:a,storageBinding:r,routeId:As}))},[t.identity,l,o,u,h,s.displayName,s.avatarSourceUrl,s.username,i,e.currentPod,r,a]),null}const qa=80,Ga=2048;function Wa(){const t=Le(),e=_t({runtime:t}),r=t.state.status==="authenticated"?t.webId??t.state.webId:void 0,s=t.state.status==="authenticated"?t.currentPod?.podUrl??t.podUrl??t.state.podUrl:void 0,a=d.useMemo(()=>Ha({isLoggedIn:t.state.status==="authenticated",displayName:e.displayName,username:e.username,webId:r,podUrl:s}),[e.displayName,e.username,t.state.status,s,r]);return d.useEffect(()=>{globalThis.xpodDesktop?.setIdentity(a)},[a]),d.useEffect(()=>()=>{globalThis.xpodDesktop?.setIdentity(null)},[]),null}function Ha({isLoggedIn:t,displayName:e,username:r,webId:s,podUrl:a}){if(!t)return null;const i=Wt(e)??Wt(r)??"WebID",o=Ht(s),c=Ht(a);return{label:i,...o?{webId:o}:{},...c?{podUrl:c}:{}}}function Wt(t){if(!t)return;const r=Array.from(t,s=>{const a=s.codePointAt(0);return Va(a)?" ":s}).join("").replace(/\s+/g," ").trim();if(r)return Array.from(r).slice(0,qa).join("").trim()}function Va(t){return t<32||t>=127&&t<=159||t>=8234&&t<=8238||t>=8294&&t<=8297}function Ht(t){if(!(!t||t.length>Ga))try{const e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"||e.username||e.password?void 0:e.toString()}catch{return}}function Qa({children:t}){const[e,r]=d.useState(!1),s=d.useRef(()=>{});return d.useEffect(()=>{let a=!1,i,o,c=0;async function l(){if(a||i)return;clearTimeout(o);const u=new AbortController;i=u;const g=setTimeout(()=>u.abort(),5e3);let f=!0;try{const v=await fetch("/service/status",{cache:"no-store",signal:u.signal});if(f=v.status<500,v.ok){const p=await v.json().catch(()=>null);Array.isArray(p)&&(f=!p.some(m=>m&&["css","api"].includes(m.name)&&typeof m.status=="string"&&m.status!=="running")),u.signal.aborted&&(f=!1)}else await v.body?.cancel()}catch{f=!1}finally{clearTimeout(g),i=void 0}a||(c=f?0:c+1,r(!f),o=setTimeout(()=>{document.visibilityState!=="hidden"&&l()},f?1e4:Math.min(2e3*2**Math.min(c-1,4),3e4)))}const h=()=>{document.visibilityState!=="hidden"&&l()};return s.current=()=>{l()},window.addEventListener("online",h),window.addEventListener("focus",h),document.addEventListener("visibilitychange",h),l(),()=>{a=!0,clearTimeout(o),i?.abort(),s.current=()=>{},window.removeEventListener("online",h),window.removeEventListener("focus",h),document.removeEventListener("visibilitychange",h)}},[]),n.jsxs("div",{className:"flex h-dvh min-h-0 flex-col",style:{"--xpod-shell-height":"100%"},children:[e&&n.jsxs("section",{role:"alert","aria-label":"Xpod 连接中断",className:"flex shrink-0 flex-wrap items-center gap-x-4 gap-y-2 border-b border-border bg-background px-4 py-2 text-sm",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("span",{className:"font-medium",children:"Xpod 连接中断"}),n.jsx("span",{className:"ml-2 text-muted-foreground",children:"正在自动重连;你仍可打开这台设备和设置。"}),n.jsxs("details",{className:"text-xs text-muted-foreground",children:[n.jsx("summary",{children:"页面与未完成操作"}),"登录状态和当前页面已保留。未完成的操作不会自动重试,请在连接恢复后确认结果。"]})]}),n.jsx("button",{type:"button",onClick:()=>s.current(),className:"shrink-0 rounded-lg bg-primary px-3 py-2 text-primary-foreground",children:"立即重试"})]}),n.jsx("div",{className:"min-h-0 flex-1",children:t})]})}function Ka(){const t=cr();return d.useEffect(()=>globalThis.xpodDesktop?.onNavigate?.(e=>{const r=new URL(e,window.location.origin);r.origin===window.location.origin&&t(`${r.pathname}${r.search}${r.hash}`)}),[t]),null}const Re="/ai-connections",F={pod:"/pod/models",status:"/device/services",network:"/device/network",aiConnections:"/ai-connections"},Qr={"/dashboard":F.status,"/dashboard/overview":F.status,"/dashboard/status":F.status,"/dashboard/runtime":"/device/runtime","/dashboard/logs":"/device/logs","/dashboard/network":F.network,"/dashboard/usage":"/pod/data","/dashboard/models":F.aiConnections,"/dashboard/pod":F.pod,"/dashboard/services":F.status,"/dashboard/settings":"/device/runtime","/status":F.status,"/status/overview":F.status,"/status/services/gateway":F.status,"/status/services/solid-server":F.status,"/status/services/api-server":F.status,"/status/logs":"/device/logs","/network":F.network,"/network/overview":F.network,"/settings/models":F.aiConnections,"/settings/ai-connections":F.aiConnections,"/settings/ai-config":F.pod,"/settings/pod":F.pod,"/settings/identity-access":"/pod/apps","/settings/storage":"/pod/data","/settings/network":F.network,"/settings/services":F.status,"/settings/system":"/device/runtime","/settings/runtime":"/device/runtime","/ai-config":F.pod,"/ai-config/model-assignments":F.pod,"/ai-config/document-processing":F.pod,"/ai-config/search-indexing":"/pod/search","/ai-config/index-lifecycle":"/pod/search"},qo=[...["/dashboard","/status","/network"].map(t=>({app:"dashboard",basename:t})),...["/settings","/ai-connections","/ai-config","/tasks","/pod","/device","/inbox","/notifications"].map(t=>({app:"settings",basename:t}))];function Ja(t){return Qr[t.replace(/\/$/,"")]??t}const Ya="https://id.undefineds.co/app/xpod-desktop-client.json",Za={client_id:Ya},Kr=1,ei="xpod.auth.transaction.v1",ti=600*1e3,Jr=1,xe="xpod.auth.selected-storage.v1",ri=1440*60*1e3;class E extends Error{code;constructor(e,r){super(r),this.name="XpodLoginTransactionError",this.code=e}}function Go(t,e={}){const r=e.storage??yt()??wt();if(!r)throw new E("storage_unavailable","Session storage is unavailable");const s=new URL(e.origin??jt()).origin,a=e.storageRoot??s,i=es(t,a,e.storageRoot===void 0),c=(e.now??(()=>Date.now()))(),l={version:Jr,createdAt:c,expiresAt:c+(e.ttlMs??ri),binding:i,...e.storageRoot===void 0?{}:{storageRoot:ts(e.storageRoot)}};r.setItem(xe,JSON.stringify(l))}function si(t={}){return t.storage?We(t.storage,t):We(yt(),t)??We(wt(),t)}function We(t,e){if(!t)return;const r=t.getItem(xe);if(!r)return;const s=()=>t.removeItem(xe);let a;try{a=JSON.parse(r)}catch{s();return}if(!oi(a)){s();return}const i=e.now??(()=>Date.now());if(a.expiresAt<=i()){s();return}let o;try{o=es(a.binding,a.storageRoot??new URL(e.origin??jt()).origin,a.storageRoot===void 0)}catch{s();return}if(e.webId!==void 0&&o.webId!==e.webId){s();return}return o}function He(t={}){t.storage?.removeItem(xe);try{yt()?.removeItem(xe),wt()?.removeItem(xe)}catch{}}function Yr(){const t=globalThis.crypto;if(typeof t?.randomUUID=="function")return t.randomUUID();if(typeof t?.getRandomValues=="function"){const e=new Uint8Array(24);return t.getRandomValues(e),`xpod-${Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}`}throw new E("storage_unavailable","Secure transaction id generation is unavailable")}function ni(t={}){const e=t.storage??ci(),r=new URL(t.origin??jt()).origin,s=t.now??(()=>Date.now()),a=t.ttlMs??ti,i=t.prefix??ei,o=`${i}.active`,c=f=>`${i}.record.${f}`,l=f=>`${i}.consumed.${f}`,h=f=>{e.getItem(o)===f&&e.removeItem(o),e.removeItem(c(f))},u=(f,v=!0)=>{if(!Qt(f))throw new E("malformed","Transaction id is malformed");if(e.getItem(l(f))==="1")throw new E("consumed","Transaction has already been consumed");if(v&&e.getItem(o)!==f)throw new E("unknown","Transaction is not the active Xpod login transaction");const p=e.getItem(c(f));if(!p)throw v&&e.getItem(o)===f&&e.removeItem(o),new E("unknown","Xpod login transaction was not found");let m;try{m=JSON.parse(p)}catch{throw h(f),new E("malformed","Xpod login transaction is malformed")}if(!ii(m)||m.transaction.id!==f)throw h(f),new E("malformed","Xpod login transaction is malformed");if(m.expiresAt<=s())throw h(f),new E("expired","Xpod login transaction has expired");try{const b=Vt({...m.transaction,authorizationSurface:"redirect",discovery:"strict"},r);return m.transaction={id:b.id,route:b.route,...b.returnTo===void 0?{}:{returnTo:b.returnTo},...b.prompt===void 0?{}:{prompt:b.prompt},...b.selectedStorage===void 0?{}:{selectedStorage:b.selectedStorage}},m}catch(b){throw h(f),b instanceof E?b:new E("malformed","Xpod login transaction is malformed")}};return{begin:f=>{const v=e.getItem(o);if(v){try{u(v)}catch(x){if(!(x instanceof E&&(x.code==="expired"||x.code==="malformed"||x.code==="unknown")))throw x}if(e.getItem(o)===v)throw new E("already_active","An Xpod login transaction is already pending in this tab")}const p=Qt(f.id)?f.id:Yr(),m=Vt({...f,id:p},r),b=s(),S=b+a,N={version:Kr,createdAt:b,expiresAt:S,transaction:{id:m.id,route:m.route,...m.returnTo===void 0?{}:{returnTo:m.returnTo},...m.prompt===void 0?{}:{prompt:m.prompt},...m.selectedStorage===void 0?{}:{selectedStorage:m.selectedStorage}}};return e.setItem(c(m.id),JSON.stringify(N)),e.setItem(o,m.id),m},readSinglePending(){const f=e.getItem(o);if(f)return Ve(u(f).transaction)},updateSelectedStorage(f,v){const p=u(f),m=Ve(p.transaction),b=Zr(v,r,m.route.storageProvider?.url),S={...p,transaction:{...p.transaction,selectedStorage:b}};e.setItem(c(f),JSON.stringify(S))},consume(f){const v=u(f),p=Ve(v.transaction);return e.removeItem(o),e.removeItem(c(f)),e.setItem(l(f),"1"),p},cancel(f){u(f),e.removeItem(o),e.removeItem(c(f)),e.setItem(l(f),"1")}}}function Vt(t,e){let r;try{r=Ts(t)}catch(i){throw new E("malformed",i instanceof Error?i.message:"Transaction is malformed")}let s;try{s=Us(r.route,e)}catch(i){throw new E("cross_origin",i instanceof Error?i.message:"Transaction route is not local")}let a;try{a=et(r.returnTo)}catch(i){throw new E("mismatch",i instanceof Error?i.message:"Transaction return path is unsafe")}if(r.selectedStorage!==void 0)try{const i=Zr(r.selectedStorage,e,s.storageProvider?.url);return{id:r.id,route:s,selectedStorage:i,authorizationSurface:"redirect",discovery:"strict",...a===void 0?{}:{returnTo:a},...r.prompt===void 0?{}:{prompt:r.prompt}}}catch(i){throw i instanceof E?i:new E("mismatch","Selected storage binding is invalid")}return{id:r.id,route:s,authorizationSurface:"redirect",discovery:"strict",...a===void 0?{}:{returnTo:a},...r.prompt===void 0?{}:{prompt:r.prompt}}}function Zr(t,e,r){if(!t||typeof t.storageUrl!="string"||typeof t.webId!="string"||ft(t.webId))throw new E("malformed","Selected storage binding is malformed");let s,a;try{s=new URL(t.storageUrl),a=new URL(t.webId)}catch{throw new E("malformed","Selected storage binding is malformed")}if(!["http:","https:"].includes(s.protocol)||!["http:","https:"].includes(a.protocol))throw new E("cross_origin","Selected storage binding must use web URLs");if(s.origin!==e||a.origin!==e||r&&s.origin!==new URL(r).origin)throw new E("cross_origin","Selected storage binding is not local to this Xpod");if(s.username||s.password||s.hash||a.username||a.password)throw new E("malformed","Selected storage binding contains unsafe URL data");return{storageUrl:s.href,webId:t.webId,...t.label===void 0?{}:{label:t.label}}}function Ve(t){return{id:t.id,route:t.route,authorizationSurface:"redirect",discovery:"strict",...t.returnTo===void 0?{}:{returnTo:t.returnTo},...t.prompt===void 0?{}:{prompt:t.prompt},...t.selectedStorage===void 0?{}:{selectedStorage:t.selectedStorage}}}function es(t,e,r){if(!t||typeof t.storageUrl!="string"||typeof t.webId!="string"||ft(t.webId))throw new E("malformed","Selected storage binding is malformed");let s,a;try{s=new URL(t.storageUrl),a=new URL(t.webId)}catch{throw new E("malformed","Selected storage binding is malformed")}if(!["http:","https:"].includes(s.protocol)||!["http:","https:"].includes(a.protocol))throw new E("cross_origin","Selected storage binding must use web URLs");if(!ai(s,e)||r&&a.origin!==new URL(e).origin||s.username||s.password||s.hash||a.username||a.password)throw new E("cross_origin","Selected storage binding is not local to this Xpod");return{storageUrl:s.href,webId:t.webId}}function ts(t){const e=new URL(t);return e.hash="",e.search="",e.pathname.endsWith("/")||(e.pathname+="/"),e.href}function ai(t,e){const r=new URL(ts(e));if(t.origin!==r.origin)return!1;const s=r.pathname;return t.pathname===s.slice(0,-1)||t.pathname.startsWith(s)}function Qt(t){return typeof t=="string"&&/^[A-Za-z0-9_-]{16,128}$/.test(t)}function ii(t){if(!t||typeof t!="object")return!1;const e=t;return e.version===Kr&&typeof e.createdAt=="number"&&typeof e.expiresAt=="number"&&!!(e.transaction&&typeof e.transaction=="object")}function oi(t){if(!t||typeof t!="object")return!1;const e=t;return e.version===Jr&&typeof e.createdAt=="number"&&typeof e.expiresAt=="number"&&!!(e.binding&&typeof e.binding=="object")}function ci(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}throw new E("storage_unavailable","Session storage is unavailable")}function wt(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage}catch{}}function yt(){try{if(typeof window<"u"&&window.localStorage)return window.localStorage}catch{}}function jt(){return typeof window<"u"&&window.location.origin!=="null"?window.location.origin:"http://localhost"}function li({collection:t,assertCurrent:e,accountIndex:r,fetch:s=window.fetch.bind(window)}){const a=async(...l)=>{e();const h=await s(...l);try{e()}catch(u){throw h.body?.cancel().catch(()=>{}),u}return h},i=new Set,o=async l=>{e();const h=await mt(l,a,r);if(e(),!h||!new URL(h).pathname.startsWith("/.account/"))throw new Error("客户端凭据地址不属于可信账号服务。");return h},c=(l,h,u)=>(e(),a(l,{method:h,credentials:"include",redirect:"error",headers:gt({Accept:"application/json",...u?{"Content-Type":"application/json"}:{}},r),...u?{body:JSON.stringify(u)}:{}}));return{async create({name:l,webId:h}){if(!l.trim()||!h)throw new Error("创建客户端凭据需要名称和当前 WebID。");const u=await c(await o(t),"POST",{name:l.trim(),webId:h});if(!u.ok)throw new Error(`创建客户端凭据失败(HTTP ${u.status})。`);const g=await u.json();if(e(),typeof g.id!="string"||!g.id||g.id.includes(":")||typeof g.secret!="string"||!g.secret||typeof g.resource!="string"||!g.resource)throw new Error("账号服务未返回有效的客户端凭据。");const f=await o(g.resource),v=new TextEncoder().encode(`${g.id}:${g.secret}`),p=btoa(Array.from(v,m=>String.fromCharCode(m)).join(""));return e(),{apiKey:`sk-${p}`,clientId:g.id,resource:f}},async list(){const l=await c(await o(t),"GET");if(!l.ok)throw new Error(`读取客户端凭据失败(HTTP ${l.status})。`);const h=await l.json();e();const u=Object.entries(h.clientCredentials??{}),g=await Promise.all(u.map(async([f,v])=>{const p=await o(String(v)),m=await c(p,"GET");if(m.status===404||m.status===410)return;if(!m.ok)throw new Error(`读取客户端凭据失败(HTTP ${m.status})。`);const b=await m.json();if(e(),!(b.id!==f||typeof b.webId!="string"||!b.webId))return{clientId:f,label:f,resource:p,webId:b.webId}}));return e(),g.filter(f=>f!==void 0)},async revoke({clientId:l,resource:h,webId:u}){const g=await o(h),f=JSON.stringify([g,l,u]),v=await c(g,"GET");if(v.status===404||v.status===410){if(i.has(f))return;throw new Error("无法确认客户端凭据已撤销,请检查当前 Account 登录;Key 记录已保留。")}if(!v.ok)throw new Error(`读取客户端凭据失败(HTTP ${v.status})。`);const p=await v.json();if(e(),p.id!==l||p.webId!==u)throw new Error("客户端凭据与当前 Key 或 WebID 不匹配,未执行删除。");const m=await c(g,"DELETE");if(!m.ok)throw new Error(`撤销客户端凭据失败(HTTP ${m.status})。`);i.add(f)}}}class ee extends Error{code;constructor(e,r){super(r),this.name="AccountStorageBindingsError",this.code=e}}async function di(t){const e=hi(t.origin),r=t.controls?.account?.bindings;if(typeof r!="string"||r.trim()==="")throw new ee("missing-control","Account storage bindings control is unavailable");const s=t.fetchImpl??fetch,a=fi(r,e),i=a.origin===e?a.href:await mt(a.href,s,t.trustedAccountIndex);if(!i)throw new ee("cross-origin","Account storage bindings control is not hosted by this Xpod");const o=gt({Accept:"application/json",...t.headers});let c;try{c=await s(i,{headers:o,credentials:"include"})}catch(h){throw new ee("request-failed",h instanceof Error?h.message:"Failed to load Account storage bindings")}if(c.status===401||c.status===403)throw new ee("forbidden","Account storage bindings require an authenticated Account");if(!c.ok)throw new ee("request-failed",`Account storage bindings request failed (${c.status})`);let l;try{l=await c.json()}catch{throw new ee("invalid-response","Account storage bindings response is not valid JSON")}return ui(l,a.origin,gi(a,t.trustedAccountIndex,e))}function ui(t,e,r=!1){if(!Kt(t)||!Array.isArray(t.bindings))throw new ee("invalid-response","Account storage bindings response is malformed");const s=[],a=new Set;for(const i of t.bindings){if(!Kt(i)||typeof i.webId!="string"||typeof i.storageUrl!="string")throw new ee("invalid-response","Account storage binding row is malformed");const o=pi(i.webId),c=mi(i.storageUrl,r?void 0:e);if(!o||!c)throw new ee("cross-origin","Account storage binding is outside the trusted storage scope");const l={webId:o,storageUrl:c,...typeof i.label=="string"?{label:i.label}:{}},h=`${l.webId}
4
+ ${l.storageUrl}`;a.has(h)||(a.add(h),s.push(l))}return s}function hi(t){try{return new URL(t??(typeof window>"u"?"http://localhost":window.location.origin)).origin}catch{throw new ee("cross-origin","Current Xpod origin is invalid")}}function fi(t,e){try{const r=new URL(t,e);if(!["http:","https:"].includes(r.protocol)||r.username||r.password||r.hash)throw new Error("unsafe control URL");return r}catch{throw new ee("cross-origin","Account storage bindings control is not a valid URL")}}function pi(t){if(!ft(t))try{const e=new URL(t);return!["http:","https:"].includes(e.protocol)||e.username||e.password?void 0:t}catch{return}}function mi(t,e){try{const r=new URL(t.trim());return e!==void 0&&r.origin!==e||!["http:","https:"].includes(r.protocol)||r.username||r.password||r.search||r.hash?void 0:(r.pathname=r.pathname.endsWith("/")?r.pathname:`${r.pathname}/`,r.href)}catch{return}}function gi(t,e,r){if(!e)return!1;try{const s=new URL(e,r);return s.pathname.startsWith("/.account/")&&t.origin===s.origin&&t.pathname.startsWith("/.account/")}catch{return!1}}function Kt(t){return!!(t&&typeof t=="object"&&!Array.isArray(t))}function bi(t){let e;const r=t.webId,s=t.name?.trim()||"Xpod 会话凭据";let a,i,o=!1;const c=async()=>{if(!r||o)return;const h=t.capability??await t.resolveCapability?.();if(!h||o)return;e=h;const u=await h.create({name:s,webId:r});if(o){await h.revoke({clientId:Jt(u.apiKey),resource:u.resource,webId:r}).catch(()=>{});return}return a={apiKey:u.apiKey,clientId:Jt(u.apiKey),resource:u.resource},a},l=async()=>a||(i??=c().finally(()=>{i=void 0}),await i);return{async authorization(){if(o)return;const h=await l();return!o&&h?`Bearer ${h.apiKey}`:void 0},async apiKey(){if(o)return;const h=await l();return o?void 0:h?.apiKey},clientId(){return a?.clientId},async release(){o=!0;const h=a;a=void 0;const u=e;!h||!u||!r||await u.revoke({clientId:h.clientId,resource:h.resource,webId:r})}}}function Jt(t){const e=t.startsWith("sk-")?t.slice(3):t;try{const r=atob(e),s=r.indexOf(":");return s>0?r.slice(0,s):""}catch{return""}}function Yt(t,e,r=t,s,a){return e?async(i,o)=>{const c=(o?.method??(i instanceof Request?i.method:"GET")).toUpperCase(),l=await t(i,o);if(!["GET","HEAD"].includes(c)||!vi(i,s,a)||l.status!==403||!await xi(l))return l;const h=await e().catch(()=>{});if(!h)return l;const u=new Headers(o?.headers??(i instanceof Request?i.headers:void 0));return u.set("authorization",h),u.delete("dpop"),r(i,{...o,headers:u})}:t}async function xi(t){try{const e=await t.clone().json();return e?.error==="service_access_missing"||!!(e?.error&&typeof e.error=="object"&&"code"in e.error&&e.error.code==="service_access_missing")}catch{return!1}}function vi(t,e,r){if(!e)return!1;try{const s=new URL(t instanceof Request?t.url:String(t),e);if(s.username||s.password||s.hash||!["http:","https:"].includes(s.protocol)||!(s.pathname.startsWith("/api/")||s.pathname.startsWith("/v1/")))return!1;const a=new URL(e).origin;if(s.origin===a)return!0;if(!r)return!1;const i=new URL(r(s.href));return i.origin===a&&!i.username&&!i.password&&i.pathname===s.pathname&&i.search===s.search&&i.hash===s.hash}catch{return!1}}async function _i(t){if(!t.accountIndex||!t.webId)return;t.assertCurrent(t.webId);const e=t.binding??await wi(t)??await yi(t);if(t.assertCurrent(t.webId),!(!e||e.webId!==t.webId))return e.assertCurrent(),li({collection:e.collection,assertCurrent:()=>{t.assertCurrent(t.webId),e.assertCurrent()},accountIndex:t.accountIndex,...e.fetch?{fetch:e.fetch}:{}})}async function wi(t){const e=t.accountIndex,r=t.webId;try{const l=new URL(e);if(!["http:","https:"].includes(l.protocol)||l.username||l.password||l.pathname!=="/.account/"||l.search||l.hash)return}catch{return}let s;try{s=await t.accountFetch(e,{headers:gt({accept:"application/json"},e),credentials:"include",redirect:"error"})}catch{return}if(!s.ok)return;const a=await s.json().catch(()=>{}),i=a?.controls?.account?.clientCredentials;if(typeof i!="string"||!i)return;try{for(const l of[i,a?.controls?.account?.bindings]){if(typeof l!="string"||!l)return;const h=new URL(l,e);if(h.origin!==new URL(e).origin||!h.pathname.startsWith("/.account/")||h.username||h.password||h.hash)return}}catch{return}const o=await di({controls:a?.controls,fetchImpl:t.accountFetch,trustedAccountIndex:e}).catch(()=>{});if(t.assertCurrent(r),!o?.some(l=>l.webId===r))return;const c=await mt(i,t.accountFetch,e);return c?{collection:c,webId:r,assertCurrent:()=>t.assertCurrent(r),fetch:t.accountFetch}:void 0}async function yi(t){if(!t.sessionFetch)return;const e=t.webId,r=en({accountIndex:t.accountIndex,fetch:t.sessionFetch,assertCurrent:()=>t.assertCurrent(e)}),s=await tn({accountIndex:t.accountIndex,webId:e,fetch:r}).catch(()=>{});if(s)return{collection:s.collection,webId:s.webId,assertCurrent:()=>t.assertCurrent(s.webId),fetch:r}}function ji({children:t,value:e}){const r=e??Ds(),s=d.useMemo(()=>r.storage??{},[r]),a=d.useMemo(()=>Ni(r),[r]),[i,o]=d.useState(a.snapshot),[c,l]=d.useState(a.issuer),[h,u]=d.useState(),[g,f]=d.useState(),[v,p]=d.useState(),[m,b]=d.useState(0),[S,N]=d.useState(),x=d.useRef(i),I=d.useRef(a.rejected),k=d.useRef(void 0),R=d.useCallback(async(w,P)=>I.current?Promise.reject(Zt):P===void 0?r.session.fetch(w):r.session.fetch(w,P),[r.session]),y=d.useMemo(()=>i.status==="authenticated"?r.session.createAuthenticatedFetch(i.webId):void 0,[r.session,i]),A=d.useCallback(async(w,P)=>{if(!y||I.current)throw Zt;return P===void 0?y(w):y(w,P)},[y]),j=d.useCallback(()=>{if(k.current)return k.current;const w=(async()=>{try{await r.session.logout();const P=r.session.getSnapshot();(P.status!=="authenticated"||tt(P,r.getIssuer(),r.getExpectedIssuer?.()??window.location.origin))&&(I.current=!1)}catch{}finally{const P={status:"anonymous"};r.pod.clear(),He({storage:s.selectedStorage}),Pt(s.issuer),r.setIssuer(void 0),x.current=P,o(P),l(void 0),u(void 0),f(void 0),p(void 0),N(void 0)}})().finally(()=>{k.current===w&&(k.current=void 0)});return k.current=w,w},[r,s.issuer,s.selectedStorage]),_=d.useContext(bt),C=_?.idpIndex,$=_?.registerAccountSession;d.useLayoutEffect(()=>{if(!(!$||i.status!=="authenticated"||!c||I.current))return $({issuer:c,fetch:A,assertCurrent:()=>{if(I.current||r.session.getSnapshot()!==i||r.getIssuer()!==c)throw new Error("Solid 会话已改变,请重新打开账号操作。")}})},[A,c,$,r,i]);const T=i.status==="authenticated"?i.webId:void 0,V=_?.controls?.account?.clientCredentials,K=_?.identity?.webId,te=_?.bindAccountCapability,J=d.useMemo(()=>V&&K&&K===T&&te?{collection:V,webId:K,assertCurrent:te(),fetch:ye}:void 0,[V,K,te,T]),z=d.useMemo(()=>{const w=()=>{if(r.session.getSnapshot()!==i)throw new Error("Solid 会话已改变,请重新打开客户端凭据操作。")};return bi({webId:T,resolveCapability:()=>_i({accountIndex:C,webId:T,binding:J,accountFetch:ye,sessionFetch:y,assertCurrent:w})})},[J,C,y,T,r.session,i]),B=d.useRef(void 0);d.useEffect(()=>(B.current?.credential===z&&(B.current.cancelled=!0),()=>{const w={credential:z,cancelled:!1};B.current=w,queueMicrotask(()=>{w.cancelled||z.release().catch(()=>{})})}),[z]);const H=d.useCallback((w,P)=>Yt(A,()=>z.authorization(),r.transportFetch??ye,window.location.origin,r.resolveLocalUrl)(w,P),[A,z,r]),re=d.useCallback((w,P)=>Yt(R,()=>z.authorization(),r.transportFetch??ye,window.location.origin,r.resolveLocalUrl)(w,P),[R,z,r]),se=d.useMemo(()=>({...r.session,fetch:re,getSnapshot:()=>x.current}),[re,r.session]);d.useEffect(()=>{const w=L=>{const X=r.getIssuer();if(!tt(L,X,r.getExpectedIssuer?.()??window.location.origin)){I.current=!0,j();return}L.status==="authenticated"&&(I.current=!1);const U=x.current;x.current=L,o(L),l(X),L.status!=="authenticated"?(r.setLocalPodRoutes?.(void 0),r.setLocalPodRoutesRefresh?.(void 0),u(void 0),L.status!=="expired"&&f(void 0),p(void 0),N(void 0),r.pod.clear()):U!==L&&(u(void 0),f(void 0),p(void 0),N(void 0),r.pod.clear(U.status==="authenticated"?{webId:U.webId}:void 0))},P=r.session.subscribe(w);return w(r.session.getSnapshot()),P},[j,r,s]),d.useEffect(()=>{I.current&&j()},[j]),d.useEffect(()=>{if(i.status!=="authenticated")return;let w=!1;const P=new AbortController,L=si({storage:s.selectedStorage,origin:typeof window>"u"?void 0:window.location.origin,webId:i.webId}),X={webId:i.webId,...L?{podUrl:L.storageUrl}:{},fetch:H};return(async()=>{try{const U=r.getProvisionRouteStatus?.()??await Os(fetch,{signal:P.signal});if(w)return;r.setLocalPodRoutes?.(Lt(L?.storageUrl??U.storageRoot,U));const q=await r.pod.open(X),Y=Lt(q.podUrl,U);if(w)return;if(r.setLocalPodRoutes?.(Y),r.setLocalPodRoutesRefresh?.(async()=>{const O=await Fs(q.podUrl,fetch,{signal:P.signal});w||r.setLocalPodRoutes?.(O)}),!w){if(L&&(q.webId!==L.webId||!Si(q.podUrl,L.storageUrl))){He({storage:s.selectedStorage}),u(void 0),f(void 0),p({webId:i.webId,error:new Error("Selected Pod binding mismatch")});return}u(q),f(L??{webId:q.webId,storageUrl:q.podUrl}),p(void 0)}}catch(U){w||p({webId:i.webId,error:U instanceof Error?U:new Error(String(U))})}})(),()=>{w=!0,P.abort(),r.setLocalPodRoutesRefresh?.(void 0)}},[H,m,r,s.selectedStorage,i]);const de=d.useCallback(()=>{p(void 0),b(w=>w+1)},[]),D=i.status==="authenticated"?i.webId:void 0;d.useEffect(()=>{if(!D)return;let w=!1;return ki(A).then(P=>{!w&&r.session.getSnapshot().status==="authenticated"&&r.session.getSnapshot().webId===D&&N(P)}),()=>{w=!0}},[A,D,r]);const ne=d.useMemo(()=>{const w=c??r.getIssuer(),P=i.status==="authenticated"&&v?.webId===i.webId?v:void 0,L=$s(i,h,w);return{session:se,pod:r.pod,fetch:H,transportFetch:r.transportFetch??ye,state:L.status==="error"?{...L,error:Xs(L.error)}:L,webId:L.webId,podUrl:L.podUrl,issuer:L.issuer,currentPod:h,selectedStorage:g,...P?{podError:P}:{},retryPodOpen:de,aiClientConfiguration:S,resolveLocalUrl:X=>r.resolveLocalUrl(X),requestPodAuthorization:()=>z.authorization(),requestPodApiKey:()=>z.apiKey(),login:async X=>{const U=Bs(X),q=await zs(U.route.identityProvider.url,fetch),Y=q.oidcIssuer;if(!Y)throw new TypeError("Xpod login route has no valid issuer");const O=new URL("/auth/callback",window.location.origin),oe=globalThis.xpodDesktop?Za.client_id:void 0;try{await r.session.login({...oe?{clientId:oe}:{},oidcIssuer:Y,redirectUrl:O.toString(),handleRedirect:ce=>{r.setIssuer(Y),l(Y);const ve=new URL(ce);U.prompt?ve.searchParams.set("prompt",U.prompt):oe&&ve.searchParams.get("prompt")==="consent"&&ve.searchParams.delete("prompt"),window.location.assign(q.provisionCode?Ms(ve.href,q.provisionCode):ve.href)}}),r.setIssuer(Y),l(Y)}catch(ce){throw console.error("[XpodSolidRuntimeProvider] WebID login failed",ce,ce instanceof Error?ce.cause:void 0),ce}},logout:async()=>{await z.release().catch(()=>{}),await r.session.logout(),r.pod.clear(),He({storage:s.selectedStorage}),Pt(s.issuer),u(void 0),f(void 0),N(void 0)}}},[S,H,h,se,c,v,z,de,r,s,g,i]);return n.jsx(za,{value:{session:se,pod:r.pod,currentPod:h},children:n.jsx(pr.Provider,{value:ne,children:t})})}const Ii={status:"anonymous"},Zt=new Error("Xpod session is unavailable"),ye=(t,e)=>globalThis.fetch(t,e);function Ni(t){const e=t.session.getSnapshot(),r=t.getIssuer();return tt(e,r,t.getExpectedIssuer?.()??window.location.origin)?{snapshot:e,issuer:r,rejected:!1}:{snapshot:Ii,issuer:void 0,rejected:!0}}function Si(t,e){try{return new URL(t).href===new URL(e).href}catch{return t===e}}async function ki(t){try{const e=new URL("/api/ai/client-configuration/capability",window.location.href).toString(),r=await t(e,{method:"GET",credentials:"include",headers:{accept:"application/json"}});if(!r.ok||!r.headers.get("content-type")?.includes("application/json"))return await r.arrayBuffer().catch(()=>{}),Qe();const s=await r.json();if(Ri(s)&&s.available===!0&&s.authority==="local-filesystem")return{available:!0,authority:"local-filesystem",manualInstructions:typeof s.manualInstructions=="string"?s.manualInstructions:Qe().manualInstructions}}catch{}return Qe()}function Qe(){return{available:!1,manualInstructions:"manual client setup is available"}}function Ri(t){return!!(t&&typeof t=="object"&&!Array.isArray(t))}function Pi({children:t}){return d.useContext(hs)?n.jsx(n.Fragment,{children:t}):n.jsx(fs,{children:t})}function Li(t){const e=async(r,s="GET",a,i)=>{const o=await t.fetch(`${(t.baseUrl??"").replace(/\/$/,"")}/api/tasks${r}${i?`?id=${encodeURIComponent(i)}`:""}`,{method:s,headers:a===void 0?void 0:{"Content-Type":"application/json"},body:a===void 0?void 0:JSON.stringify(a)});if(!o.ok){const c=await o.json().catch(()=>{});throw new Error(o.status===401?"登录已失效,请重新登录":o.status===403?"暂时无法访问任务,请检查连接与授权":o.status>=500?"任务服务暂时不可用,请稍后重试":c?.error&&/[\u4e00-\u9fff]/.test(c.error)?c.error:"任务操作未完成,请检查输入后重试")}return o.json()};return{resumeRun:(r,s)=>e("/resume","POST",{approval:s},r),selection:r=>e("/selection","GET",void 0,r),list:()=>e(""),create:r=>e("","POST",r),update:(r,s)=>e("","PATCH",s,r),pause:(r,s)=>e("/pause","POST",{paused:s},r),run:r=>e("/run","POST",{},r),runs:r=>e("/runs","GET",void 0,r),steps:r=>e("/steps","GET",void 0,r),stop:r=>e("/stop","POST",{},r)}}const rs=d.createContext(null);function ss(){return d.useContext(rs)}function Ce(){const t=ss();if(!t)throw new Error("ShellStateProvider is required");return t}async function Ci({webId:t,podUrl:e,authenticatedFetch:r}){const s=new URL("/",e).origin,a=await r(`${s}/api/pod/settings/status`,{method:"GET",credentials:"include",headers:{accept:"application/json"}});if(!a.ok)throw await a.arrayBuffer(),new Error("Pod settings request failed. Please try again.");if(!a.headers.get("content-type")?.includes("application/json"))throw await a.arrayBuffer(),new Error("Pod settings request failed. Please try again.");const i=await a.json();if(i.identity?.webId!==t)throw new Error("Pod settings response does not match the current Solid session.");return i}const De=()=>({attention:[],activity:[],inProgress:[],inbox:[]});function Ei(t,e=Date.now()){return["pending","handling"].includes(t.status)&&(!t.expiresAt||new Date(t.expiresAt).getTime()>e)}const Ke=t=>t?new Date(t).toISOString():"",ct=t=>`/tasks?run=${encodeURIComponent(t.id)}`;function Ai(t){if(!t.metadata||typeof t.metadata!="object")return;const e=t.metadata.waitingTool;if(!e||typeof e!="object")return;const r=e.requestId;return typeof r=="string"?r:void 0}function ns(t,e){return!!(t.thread&&t.toolCallId&&t.thread===e.thread&&t.toolCallId===Ai(e))}function lt(t,e){return e.status==="waiting_input"&&ns(t,e)}function Ti(t,e,r){const s=`approval=${encodeURIComponent(t.id)}`;if(e.some(i=>i.object===t.id))return`/inbox?${s}`;const a=r.find(i=>lt(t,i));return a?`${ct(a)}&${s}`:`/inbox?${s}`}function Ui({approvals:t,inbox:e,runs:r,tasks:s}){const a=new Set(["completed","failed","cancelled"]),i=t.filter(o=>{if(!Ei(o))return!1;const c=r.filter(l=>ns(o,l));return c.length===0||c.some(l=>!a.has(l.status))});return{attention:[...i.map(o=>({id:o.id,approvalId:o.id,thread:o.thread||void 0,run:r.find(c=>lt(o,c))?.id,title:o.toolName||"访问申请",kind:"approval",href:Ti(o,e,r),risk:o.risk,toolName:o.toolName,expiresAt:Ke(o.expiresAt)||void 0})),...r.filter(o=>["failed","waiting_input"].includes(o.status)).map(o=>{const c=t.find(l=>["approved","rejected"].includes(l.status)&&lt(l,o));return{id:o.id,run:o.id,thread:o.thread||void 0,resumeApproval:c?.id,title:o.status==="failed"?"运行失败":c?"审批已保存,运行待处理":"运行在等你确认",kind:"run",href:ct(o)}})],activity:s.map(o=>({id:`task:${o.id}`,title:`新建任务:${o.title||"未命名任务"}`,href:`/tasks?task=${encodeURIComponent(o.id)}`,createdAt:Ke(o.createdAt)})).sort((o,c)=>c.createdAt.localeCompare(o.createdAt)),inProgress:r.filter(o=>o.status==="running").map(o=>({id:o.id,title:o.prompt||"任务运行中",href:ct(o)})),inbox:e.map(o=>({id:o.id,actor:o.actor||void 0,object:o.object,createdAt:Ke(o.createdAt),approvalId:i.find(c=>c.id===o.object)?.id})).sort((o,c)=>c.createdAt.localeCompare(o.createdAt))}}function Di(t){return{...t,activity:t.activity.map(e=>({...e,read:!0}))}}async function Oi(t){const[e,r,s,a]=await Promise.all([t.select().from(Ct),t.select().from(Et),t.select().from(At),t.select().from(Tt)]);return Ui({approvals:e.map(i=>({...i,id:t.resolveRowIri(Ct,{...i})})),inbox:r.map(i=>({...i,id:t.resolveRowIri(Et,{...i})})),runs:s.map(i=>({...i,id:t.resolveRowIri(At,{...i})})),tasks:a.map(i=>({...i,id:t.resolveRowIri(Tt,{...i})}))})}async function Fi(t,e,r,s,a=()=>!0){const i=await Ma({approval:e,decisionBy:r,decision:s,authenticatedFetch:t,isCurrent:a});if(i.status==="decided")return;const o={conflict:"申请已被其他入口处理,请刷新后查看。",not_found:"申请不存在,请刷新。",not_actionable:"申请已处理、过期或当前身份无权处理,请刷新。",unavailable:"此 Pod 尚不支持安全审批,请稍后重试。"};throw new Error(o[i.status])}function $i({children:t}){const e=Le();return n.jsx(Bi,{runtime:e,children:t},`${e.state.status}|${e.webId||""}|${e.currentPod?.podUrl||""}`)}function Bi({children:t,runtime:e}){const r=d.useMemo(()=>Li({fetch:e.fetch,baseUrl:window.location.origin}),[e.fetch]),[s,a]=d.useState(De),[i,o]=d.useState(!1),[c,l]=d.useState(),[h,u]=d.useState([]),g=d.useRef(new Set),[f,v]=d.useState(0),p=d.useRef(new Set),m=d.useRef(!0),b=d.useCallback(()=>v(x=>x+1),[]);d.useEffect(()=>(m.current=!0,()=>{m.current=!1}),[]),d.useEffect(()=>{let x=!0,I=!1;async function k(){if(!I){I=!0,o(!0);try{const[y,A,j]=await Promise.allSettled([e.state.status==="authenticated"&&e.currentPod?Oi(e.currentPod.database):Promise.resolve(De()),nn(),e.state.status==="authenticated"&&e.webId&&e.currentPod?Ci({webId:e.webId,podUrl:e.currentPod.podUrl,authenticatedFetch:e.fetch}):Promise.resolve(null)]),_=y.status==="fulfilled"?y.value:De();if(A.status==="fulfilled"&&A.value?.status==="fail"&&_.attention.push({id:"device:network",kind:"network",title:"设备网络需要检查",href:"/device/network"}),j.status==="fulfilled"&&j.value?.storage.status==="available"){const C=j.value.storage;C.limits.storageLimitBytes&&C.usage.storageBytes/C.limits.storageLimitBytes>=.8&&_.attention.push({id:"pod:storage",kind:"quota",title:"Pod 空间快到上限",href:"/pod/data"})}x&&(a(C=>{const $=y.status==="fulfilled"?_:{...C,attention:[...C.attention.filter(T=>T.kind!=="network"&&T.kind!=="quota"),..._.attention]};return{...$,activity:$.activity.map(T=>({...T,read:p.current.has(T.id)}))}}),l(y.status==="rejected"?"Pod 通知读取失败,请重试":void 0))}catch{x&&l("通知读取失败,请重试")}finally{I=!1,x&&o(!1)}}}k();const R=window.setInterval(()=>{k()},3e4);return window.addEventListener("focus",b),window.addEventListener("xpod:pod-changed",b),()=>{x=!1,window.clearInterval(R),window.removeEventListener("focus",b),window.removeEventListener("xpod:pod-changed",b)}},[e.currentPod,e.webId,e.fetch,e.state.status,f,b]),d.useEffect(()=>{globalThis.xpodDesktop?.publishAttention?.(s)},[s]),d.useEffect(()=>()=>{globalThis.xpodDesktop?.publishAttention?.(De())},[]);const S=d.useCallback(async(x,I)=>{if(!(!m.current||g.current.has(x))){g.current.add(x),u(k=>k.map(R=>R.approvalId===x?{...R,busy:!0}:R));try{await r.resumeRun(I,x),m.current&&(u(k=>k.filter(R=>R.approvalId!==x)),b())}catch{m.current&&u(k=>[...k.filter(R=>R.approvalId!==x),{approvalId:x,run:I,message:"决定已保存,运行处理失败,请重试。"}])}finally{g.current.delete(x)}}},[r,b]),N=d.useCallback(async(x,I)=>{if(e.state.status!=="authenticated"||!e.currentPod||!e.webId)throw new Error("请先登录并打开 Pod。");const k=s.attention.find(R=>R.approvalId===x)?.run;await Fi(e.fetch,x,e.webId,I,()=>m.current),m.current&&(a(R=>({...R,attention:R.attention.filter(y=>y.approvalId!==x),inbox:R.inbox.map(y=>y.approvalId===x?{...y,approvalId:void 0}:y)})),k&&await S(x,k),b())},[e.currentPod,e.webId,e.fetch,e.state.status,s.attention,S,b]);return d.useEffect(()=>globalThis.xpodDesktop?.onApprovalDecision?.(({approvalId:x,decision:I})=>{N(x,I).catch(k=>{m.current&&l(k instanceof Error?k.message:"决定保存失败,请重试")})}),[N]),n.jsx(rs.Provider,{value:{snapshot:s,loading:i,error:c,refresh:b,decide:N,resumeFailures:h,retryResume:S,markAllRead(){s.activity.forEach(x=>p.current.add(x.id)),a(Di)}},children:t})}function er({item:t}){const{decide:e}=Ce(),[r,s]=d.useState(!1),[a,i]=d.useState("");async function o(c){if(t.approvalId){s(!0);try{await e(t.approvalId,c),i("决定已保存。")}catch(l){i(l instanceof Error?l.message:"保存失败,请重试。")}finally{s(!1)}}}return n.jsxs("div",{className:"space-y-2 rounded-md border border-border p-3 text-sm leading-normal",children:[n.jsx("p",{className:"font-medium",children:t.title}),n.jsxs("p",{className:"text-xs leading-normal text-muted-foreground",children:["风险:",{low:"低",medium:"中",high:"高"}[t.risk||""]||t.risk||"未说明",t.expiresAt?` · 有效至 ${new Date(t.expiresAt).toLocaleString("zh-CN")}`:""]}),n.jsxs("div",{className:"flex flex-wrap gap-2",children:[n.jsx("button",{disabled:r,onClick:()=>{o("approved")},className:"rounded bg-primary px-2 py-1 text-primary-foreground",children:"只这一次"}),n.jsx("button",{disabled:!0,title:"长期授权待接入",className:"rounded border px-2 py-1 opacity-50",children:"以后都允许 · 待接入"}),n.jsx("button",{disabled:r,onClick:()=>{o("rejected")},className:"rounded border px-2 py-1",children:"拒绝"})]}),n.jsx("p",{className:"text-xs leading-normal text-muted-foreground",children:"这次决定只对当前申请有效。"}),a&&n.jsx("p",{role:"status",children:a})]})}function as({run:t,recoveryApproval:e}){const{snapshot:r,resumeFailures:s,retryResume:a}=Ce(),i=s.filter(c=>!t||c.run===t),o=r.attention.filter(c=>c.resumeApproval&&c.run&&(!t||c.run===t));for(const c of o)i.some(l=>l.approvalId===c.resumeApproval)||i.push({approvalId:c.resumeApproval,run:c.run,message:"审批决定已保存,可以继续处理这次运行。"});return t&&e&&!i.some(c=>c.approvalId===e)&&i.push({approvalId:e,run:t,message:"审批决定已保存,可以继续处理这次运行。"}),n.jsx(n.Fragment,{children:i.map(c=>n.jsx(Nr,{tone:"neutral",role:"alert",className:"my-2",action:n.jsx("button",{disabled:c.busy,className:"underline",onClick:()=>{a(c.approvalId,c.run)},children:c.busy?"正在重试…":"重试处理运行"}),children:c.message},c.approvalId))})}function is(){const{snapshot:t}=Ce(),[e]=ps(),r=t.attention.find(a=>a.approvalId===e.get("approval")),s=r&&!t.inbox.some(a=>a.approvalId===r.approvalId);return n.jsxs(n.Fragment,{children:[n.jsx(as,{}),s&&n.jsx("div",{className:"mb-4",children:n.jsx(er,{item:r})}),t.inbox.length?n.jsx("ul",{className:"space-y-3",children:t.inbox.map(a=>{const i=t.attention.find(o=>o.approvalId===a.approvalId&&a.approvalId);return n.jsxs("li",{className:"space-y-2 border-b border-border pb-3",children:[n.jsxs("p",{className:"break-all text-xs leading-normal text-muted-foreground",children:[a.actor||"未知发送者"," · ",new Date(a.createdAt).toLocaleString("zh-CN")]}),i?n.jsx(er,{item:i}):n.jsx("a",{className:"break-all text-sm leading-normal underline",href:/^https?:\/\//.test(a.object)?a.object:void 0,target:"_blank",rel:"noreferrer",children:a.object})]},a.id)})}):n.jsx("p",{className:"py-6 text-sm leading-normal text-muted-foreground",children:"收件箱是空的"})]})}function os({close:t=()=>{}}){const{snapshot:e,markAllRead:r}=Ce();return n.jsxs("div",{className:"space-y-5",children:[n.jsx(as,{}),n.jsxs("section",{children:[n.jsx("h3",{className:"mb-2 text-sm leading-normal font-medium",children:"需要你处理"}),e.attention.length?n.jsx("ul",{className:"space-y-2",children:e.attention.map(s=>n.jsx("li",{children:n.jsxs(Ze,{onClick:t,to:s.href,className:"block rounded-md border border-border p-3 text-sm leading-normal hover:bg-accent",children:[s.title," ›"]})},s.id))}):n.jsx("p",{className:"text-sm leading-normal text-muted-foreground",children:"没有待处理事项"})]}),n.jsxs("section",{children:[n.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[n.jsx("h3",{className:"text-sm leading-normal font-medium",children:"动态"}),n.jsx("button",{className:"text-xs leading-normal text-muted-foreground",onClick:r,children:"全部已读"})]}),e.activity.length?n.jsx("ul",{className:"space-y-2",children:e.activity.map(s=>n.jsx("li",{children:n.jsx(Ze,{to:s.href,onClick:t,className:`block text-sm leading-normal ${s.read?"text-muted-foreground":"font-medium"}`,children:s.title})},s.id))}):n.jsx("p",{className:"text-sm leading-normal text-muted-foreground",children:"暂无动态"})]})]})}function zi(){const{snapshot:t,loading:e,error:r,refresh:s}=Ce(),[a,i]=d.useState(null),o=d.useRef(null),c=d.useRef(null),l=d.useRef(null);return d.useEffect(()=>{if(!a)return;c.current?.focus();function h(g){g.key==="Escape"&&(i(null),l.current?.focus())}function u(g){o.current?.contains(g.target)||i(null)}return document.addEventListener("keydown",h),document.addEventListener("pointerdown",u),()=>{document.removeEventListener("keydown",h),document.removeEventListener("pointerdown",u)}},[a]),n.jsxs("div",{ref:o,className:"relative flex items-center gap-1",children:[n.jsx("button",{"aria-label":e?"正在同步":r||"刷新同步状态",title:r||(e?"正在同步":"刷新同步状态"),onClick:s,className:"rounded p-2 hover:bg-accent",children:n.jsx(Er,{size:16,className:e?"animate-spin":""})}),["notifications","inbox"].map(h=>n.jsxs("button",{"aria-label":h==="notifications"?"通知":"收件箱","aria-expanded":a===h,"aria-controls":"shell-popover",onClick:u=>{l.current=u.currentTarget,i(a===h?null:h)},className:"relative rounded p-2 hover:bg-accent",children:[h==="notifications"?n.jsx(Bn,{size:16}):n.jsx(Kn,{size:16}),(h==="notifications"?t.attention.length+t.activity.filter(u=>!u.read).length:t.inbox.length)>0&&n.jsx(vt,{tone:"info",size:"sm",className:"absolute right-1 top-1"})]},h)),a&&n.jsxs("div",{id:"shell-popover",ref:c,tabIndex:-1,role:"region","aria-label":a==="notifications"?"通知中心":"收件箱",className:"absolute right-0 top-full z-50 mt-2 max-h-[70vh] w-[360px] max-w-[calc(100vw-24px)] overflow-y-auto rounded-lg border border-border bg-popover p-4 text-popover-foreground shadow-lg",children:[n.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[n.jsx("h2",{className:"font-medium",children:a==="notifications"?"通知中心":"收件箱"}),n.jsx("button",{"aria-label":"关闭",onClick:()=>{i(null),l.current?.focus()},children:n.jsx(Ar,{size:16})})]}),r&&n.jsx(Nr,{tone:"destructive",role:"alert",className:"mb-3",action:n.jsx("button",{onClick:s,className:"underline",children:"重试"}),children:r}),a==="notifications"?n.jsx(os,{close:()=>i(null)}):n.jsx(is,{})]})]})}const Mi=d.lazy(()=>ae(()=>import("./PodPage-Dyo3yCb-.js"),__vite__mapDeps([10,1,2,3,4,5,6,7,11,12,13,8,9]))),Xi=[{path:"/device/network",label:"网络访问"},{path:"/device/services",label:"服务状态"},{path:"/device/runtime",label:"运行设置"},{path:"/device/logs",label:"查看日志"}],qi=[{path:"/pod/models",label:"模型设置"},{path:"/pod/search",label:"检索与索引"},{path:"/pod/apps",label:"授权应用"},{path:"/pod/data",label:"数据管理"}],Gi=[{path:"/settings/appearance",label:"外观"}];function Wi({items:t,query:e,label:r}){const{openMain:s}=an();return n.jsx("nav",{"aria-label":r,className:"p-2",children:t.filter(a=>a.label.includes(e.trim())).map(a=>n.jsx(gs,{to:a.path,onClick:s,className:({isActive:i})=>`flex min-h-11 items-center rounded-lg px-3 text-sm leading-normal ${i?"bg-accent font-medium text-primary":"hover:bg-muted"}`,children:a.label},a.path))})}function dt({subject:t}){const e=$e(),r=t==="device"?Xi:t==="pod"?qi:Gi,[s,a]=d.useState(""),i=r.find(c=>c.path===e.pathname)??r[0],o=t==="device"?"这台设备":t==="pod"?"Pod":"设置";return n.jsx(wr,{mode:"auto",listHeader:n.jsx("div",{className:"flex h-full min-w-0 items-center px-3",children:n.jsx(Ir,{"aria-label":"搜索页面",value:s,onChange:c=>a(c.target.value)})}),list:n.jsx(Wi,{items:r,query:s,label:o}),mainHeader:n.jsx(cs,{title:i.label}),main:n.jsx(ht,{})})}function cs({title:t,children:e}){return n.jsxs("div",{className:"flex h-full min-w-0 items-center justify-between gap-2 px-4",children:[n.jsx("h1",{className:"min-w-0 truncate text-sm leading-normal font-semibold",children:t}),n.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e,n.jsx(zi,{})]})]})}function tr({title:t,children:e}){return n.jsx(wr,{className:"workspace-page",pageType:"collection",hasObjectCollection:!1,listHeader:null,list:null,mainHeader:n.jsx(cs,{title:t}),main:n.jsx("div",{className:"p-6",children:e})})}function Hi({section:t}){const e=cr(),r=Le(),s=r.issuer?new URL("/.account/account/",r.issuer).toString():void 0;return n.jsx(xr,{children:n.jsx(Mi,{section:t,onSection:a=>e(`/pod/${a}`),accountUrl:s})})}function Vi(){const t=ms();return n.jsx("section",{className:"p-6 text-sm leading-normal",children:n.jsxs("label",{className:"flex flex-wrap items-center justify-between gap-3 border-b pb-4",children:["主题",n.jsxs(jr,{"aria-label":"主题",className:"w-auto",value:t.preference,onChange:e=>t.setPreference(e.target.value),children:[n.jsx("option",{value:"system",children:"跟随系统"}),n.jsx("option",{value:"light",children:"浅色"}),n.jsx("option",{value:"dark",children:"深色"})]})]})})}const Je=[{id:"tasks",label:"任务",labelEn:"Tasks",href:"/tasks",activePaths:["/tasks"],icon:ua},{id:"ai",label:"AI 连接",labelEn:"AI connections",href:"/ai-connections",activePaths:["/ai-connections"],icon:la},{id:"pod",label:"Pod",labelEn:"Pod",href:"/pod/models",activePaths:["/pod"],icon:yr},{id:"device",label:"这台设备",labelEn:"This device",href:"/device/network",activePaths:["/device"],icon:na},{id:"settings",label:"设置",labelEn:"Settings",href:"/settings/appearance",activePaths:["/settings"],icon:oa}];function ls(t,e){const r=e.replace(/\/+$/,"")||"/";return t.activePaths.some(s=>r===s||r.startsWith(`${s}/`))}function Qi(t,e,r){const i=Math.min(360,e-16),o=Math.max(8,Math.min(t.top,r-240-8));return{left:Math.max(8,Math.min(t.right+12,e-i-8)),top:o,width:i,maxHeight:Math.max(0,r-o-8)}}function Ki(){const t=vr(),e=d.useContext(pr),r=t.isLoggedIn&&t.accountState.status==="authenticated",s=e?.state.status==="authenticated"&&!!(e.webId??e.state.webId),a=r||s,[i,o]=d.useState(so(a)),[c,l]=d.useState(),[h,u]=d.useState(),[g,f]=d.useState(),v=d.useRef(null),p=d.useRef(null),m=d.useRef(void 0),b=d.useId(),S=t.identity,N=_r(t.idpIndex),x=!t.isInitializing&&N?new URL(N).origin:void 0,I=x?fr(void 0,t.idpIndex):void 0,k=Be(),R=rn(t.controls,S),y=x&&k?.issuer===x&&R&&k.account.id===R?k.account:void 0,A=r?Ji(S,I,y):void 0,j=_t({accountIdentity:A,runtime:s?e:void 0}),_=j.displayName,C=Zi(j.displayName),$=e?.webId??(e?.state.status==="authenticated"?e.state.webId:void 0),T=e?.selectedStorage?.storageUrl??e?.podUrl,V=e?.selectedStorage,K=e?.currentPod,te=d.useMemo(()=>T?eo(T):void 0,[T]),J=e?.state.status==="authenticated"&&!!($&&T&&V&&K)&&V?.webId===$&&rr(V?.storageUrl??"",T??"")&&K?.webId===$&&rr(K?.podUrl??"",T??""),z=a,B=i&&z,H=d.useCallback(D=>{o(D),D||(f(void 0),sr())},[]);d.useLayoutEffect(()=>{if(!B)return;const D=()=>{const ne=p.current;ne&&f(Qi(ne.getBoundingClientRect(),window.innerWidth,window.innerHeight))};return D(),window.addEventListener("resize",D),window.addEventListener("scroll",D,!0),window.visualViewport?.addEventListener("resize",D),()=>{window.removeEventListener("resize",D),window.removeEventListener("scroll",D,!0),window.visualViewport?.removeEventListener("resize",D)}},[B]),d.useEffect(()=>{if(!z){sr();return}if(!B)return;const D=w=>{const P=w.target;P instanceof Node&&(v.current?.contains(P)||p.current?.contains(P)||H(!1))},ne=w=>{w.key==="Escape"&&(H(!1),p.current?.focus())};return document.addEventListener("pointerdown",D),document.addEventListener("keydown",ne),()=>{document.removeEventListener("pointerdown",D),document.removeEventListener("keydown",ne)}},[z,B,H]),d.useEffect(()=>{!B||!g||v.current?.focus({preventScroll:!0})},[B,g]),d.useEffect(()=>()=>{m.current!==void 0&&window.clearTimeout(m.current)},[]);const re=async()=>{l("logout"),H(!1);try{await at(t,e),(t.isAnonymous?.()??!0)&&H(!1)}catch{}finally{l(void 0)}},se=async()=>{l("switch"),H(!1);try{await at(t,e,{onComplete:()=>{mr();const D=new URL(Re,window.location.origin);D.searchParams.set("xpod-login","switch"),window.location.assign(D)}}),H(!1)}catch{}finally{l(void 0)}},de=async()=>{const D=j.webId??$;if(D){try{await navigator.clipboard.writeText(D),u("已复制")}catch{u("复制失败")}m.current!==void 0&&window.clearTimeout(m.current),m.current=window.setTimeout(()=>u(void 0),1800)}};return z?n.jsxs("div",{className:"relative",children:[n.jsxs("button",{ref:p,type:"button","aria-label":a?`打开 ${_} 的个人卡片`:"个人卡片","aria-expanded":B,"aria-controls":B?b:void 0,"data-testid":"xpod-user-card-trigger","data-pod-ready":J?"true":"false",className:"flex h-9 w-9 items-center justify-center rounded-md text-foreground transition-colors hover:bg-accent focus:outline-none focus:ring-0 focus-visible:bg-accent",onClick:()=>H(!B),children:[n.jsxs(Ut,{className:"h-8 w-8 rounded-md border border-border bg-muted",children:[j.avatarUrl?n.jsx(Dt,{src:j.avatarUrl,alt:_}):null,n.jsx(Ot,{className:"rounded-md bg-muted text-xs text-muted-foreground",children:C})]}),n.jsx("span",{className:"sr-only",children:a?_:"Not signed in"})]}),B&&typeof document<"u"?Ys.createPortal(n.jsx("section",{ref:v,id:b,role:"region",tabIndex:-1,"aria-label":a?_:"Xpod account","data-avatar-card":"true","data-selected-pod-url":T,style:g,className:`fixed z-50 overflow-y-auto rounded-xl border border-border/40 bg-card text-card-foreground shadow-xl shadow-black/10 ${g?"":"invisible"}`,children:n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-start gap-5 px-6 pb-5 pt-6",children:[n.jsxs(Ut,{"data-testid":"xpod-profile-avatar",className:"h-20 w-20 shrink-0 rounded-2xl border border-border/50 bg-primary/10 shadow-sm",children:[j.avatarUrl?n.jsx(Dt,{src:j.avatarUrl,alt:_}):null,n.jsx(Ot,{className:"rounded-2xl bg-primary/10 text-2xl font-bold text-primary",children:C})]}),n.jsxs("div",{className:"min-w-0 flex-1 py-0.5",children:[n.jsx("h2",{className:"truncate text-xl font-bold text-foreground",children:_}),n.jsxs("div",{className:"mt-1 flex min-w-0 items-center gap-1 text-sm text-muted-foreground",children:[n.jsx("span",{className:"shrink-0 opacity-70",children:"WebID"}),n.jsx("span",{className:"truncate font-mono font-medium",children:j.webId??$}),n.jsx(pe,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground","aria-label":"复制 WebID",onClick:()=>{de()},children:n.jsx(Wn,{className:"h-3 w-3","aria-hidden":"true"})}),h?n.jsx("span",{role:"status",className:"shrink-0 text-xs text-primary",children:h}):null]}),n.jsx(vn,{tone:J?"success":"neutral",dotSize:"sm",className:M("mt-2.5 gap-1.5 rounded-full px-2 py-1 text-xs font-medium",J?"bg-success/10 text-success":"bg-muted text-muted-foreground"),children:J?"Pod 已就绪":"WebID 已登录"})]})]}),j.note||j.region?n.jsxs("div",{className:"px-6 pb-5 text-sm text-muted-foreground",children:[j.note?n.jsx("p",{className:"line-clamp-2 text-foreground/85",children:j.note}):null,j.region?n.jsx("p",{className:"mt-1 text-xs",children:j.region}):null]}):null,n.jsx("div",{className:"border-t border-border/40 p-2",children:n.jsx(pe,{asChild:!0,variant:"ghost",className:"h-auto min-h-14 w-full justify-start gap-3 px-3 py-2.5 font-normal",children:n.jsxs("a",{href:"/pod/models","aria-label":"Pod",children:[n.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground",children:n.jsx(yr,{className:"h-4 w-4","aria-hidden":"true"})}),n.jsxs("span",{className:"min-w-0 flex-1 text-left",children:[n.jsx("span",{className:"block truncate text-sm font-medium text-foreground",children:to(te)}),n.jsxs("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:[ro(T)," · ",J?"已就绪":"尚未就绪"]})]}),J?n.jsx(qn,{className:"h-4 w-4 shrink-0 text-success","aria-label":"Pod 已就绪"}):n.jsx(Mn,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"})]})})}),n.jsx(Pr,{}),n.jsxs("div",{className:"p-2",children:[N?n.jsx(pe,{asChild:!0,variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal",children:n.jsxs("a",{href:N,target:"_blank",rel:"noopener noreferrer",children:[n.jsx(fa,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"管理账号",n.jsx(Vn,{className:"ml-1 h-3.5 w-3.5","aria-hidden":"true"})]})}):null,n.jsxs(pe,{type:"button",variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal",onClick:()=>{se()},disabled:c!==void 0,children:[c==="switch"?n.jsx(rt,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):n.jsx(Er,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"切换 WebID"]}),n.jsxs(pe,{type:"button",variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal text-destructive hover:text-destructive",onClick:()=>{re()},disabled:c!==void 0,children:[c==="logout"?n.jsx(rt,{className:"mr-2 h-4 w-4 animate-spin","aria-hidden":"true"}):n.jsx(ea,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"退出"]})]})]})}),document.body):null]}):n.jsx("a",{href:Re,"aria-label":"登录",title:"登录",className:"flex h-9 w-9 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent",children:n.jsx(Yn,{size:20,"aria-hidden":"true"})})}function Ji(t,e,r){if(t?.displayName||t?.username)return t;const s=e||(r&&"email"in r&&typeof r.email=="string"?r.email:void 0);if(!s&&!r)return t;const a=r?.username||Yi(s);return{...r??{},...t??{},...a?{username:a}:{},...r?.displayName?{displayName:r.displayName}:{displayName:a||s||"Xpod account"}}}function Yi(t){if(t)return t.split("@")[0]?.trim()||void 0}function Zi(t){const e=t.trim().split(/\s+/).filter(Boolean);return e.length>=2?`${e[0][0]}${e.at(-1)[0]}`.toUpperCase():t.slice(0,2).toUpperCase()||"XP"}function eo(t){try{return new URL(t).pathname.split("/").filter(Boolean).at(-1)}catch{return}}function to(t){return t?`${t} Pod`:"我的 Pod"}function ro(t){if(!t)return"未连接 Pod";try{return new URL(t).host}catch{return"Pod"}}function rr(t,e){try{return new URL(t).href===new URL(e).href}catch{return t===e}}function so(t){return t?typeof window<"u"&&new URLSearchParams(window.location.search).get("account")==="open":!1}function sr(){if(typeof window>"u")return;const t=new URL(window.location.href);t.searchParams.get("account")==="open"&&(t.searchParams.delete("account"),window.history.replaceState(window.history.state,"",`${t.pathname}${t.search}${t.hash}`))}function nr({items:t,label:e,attentionIds:r=[]}){const a=$e().pathname;return n.jsx("nav",{"aria-label":e,className:"flex w-full flex-col items-center gap-2",children:t.map(i=>{const o=i.icon,c=i.href??i.path??"/",l=i.activePaths?ls(i,a):a===i.path||a.startsWith(`${i.path}/`);return n.jsxs(Ze,{to:c,"aria-label":i.label,"aria-current":l?"page":void 0,"data-list-item":"true",title:i.label,onKeyDown:cn,className:Vs(ln(l),"text-sm"),children:[n.jsx(o,{className:"h-5 w-5 shrink-0","aria-hidden":"true"}),n.jsx("span",{className:"sr-only",children:i.label}),r.includes(i.id)?n.jsx(vt,{tone:"destructive",label:"需要处理",className:"absolute right-1 top-1"}):null]},i.id)})})}function no({product:t}){const e=$e(),s=ss()?.snapshot.attention.some(m=>m.kind==="network")??!1,[a,i]=d.useState({path:e.pathname,open:!1}),o=a.path===e.pathname&&a.open;a.path!==e.pathname&&i({path:e.pathname,open:!1});const c=d.useRef(null),l=d.useRef(!1),h=d.useRef(null),u=Je.find(m=>ls(m,e.pathname)),f={models:"模型设置",search:"检索与索引",indexing:"检索与索引",applications:"授权应用",data:"数据管理",network:"网络访问",services:"服务状态",runtime:"运行设置",logs:"查看日志",appearance:"外观"}[e.pathname.split("/").filter(Boolean).at(-1)??""];d.useEffect(()=>{l.current&&!o&&c.current?.focus(),l.current=o},[o]),d.useEffect(()=>{const m=()=>{window.innerWidth>=768&&i(b=>({...b,open:!1}))};return window.addEventListener("resize",m),()=>window.removeEventListener("resize",m)},[]),d.useEffect(()=>{if(!o)return;const m=b=>{if(b.key==="Escape"&&(i(I=>({...I,open:!1})),c.current?.focus()),b.key!=="Tab")return;const S=Array.from(h.current?.querySelectorAll('[data-app-layout-navigation] a, [data-app-layout-navigation] button, [data-workspace-pane="list"] a, [data-workspace-pane="list"] button, [data-workspace-pane="list"] input, [data-drawer-close]')??[]).filter(I=>I.getClientRects().length&&!I.hasAttribute("disabled")),N=S[0],x=S.at(-1);b.shiftKey&&document.activeElement===N?(b.preventDefault(),x?.focus()):!b.shiftKey&&document.activeElement===x&&(b.preventDefault(),N?.focus())};return document.addEventListener("keydown",m),h.current?.querySelector("[data-drawer-close]")?.focus(),()=>document.removeEventListener("keydown",m)},[o]);const v=n.jsx("button",{ref:c,type:"button",className:"xpod-navigation-toggle","aria-label":"打开导航","aria-expanded":o,onClick:()=>i({path:e.pathname,open:!0}),children:n.jsx(ra,{"aria-hidden":"true",size:20})}),p=n.jsxs(n.Fragment,{children:[v,n.jsxs("span",{className:"xpod-header-parent",children:[u?.label??"Xpod"," ›"]})]});return n.jsx(on.Provider,{value:{open:o,onClose:()=>i(m=>({...m,open:!1})),headerLeading:p},children:n.jsxs("section",{ref:h,role:o?"dialog":void 0,"aria-modal":o||void 0,"aria-label":o?"Xpod 导航":void 0,className:`xpod-desktop-shell xpod-${t}-shell`,"data-app-layout":"workspace","data-drawer-open":o,children:[n.jsxs("header",{className:"xpod-narrow-header","data-app-layout-header":!0,children:[v,n.jsxs("span",{children:[u?.label??"Xpod",f?` › ${f}`:""]})]}),o?n.jsx("button",{className:"xpod-drawer-backdrop","aria-label":"关闭导航",onClick:()=>{i(m=>({...m,open:!1})),c.current?.focus()}}):null,n.jsxs("aside",{className:"xpod-rail","data-app-layout-navigation":!0,"aria-label":"Xpod 工作区导航",onClick:m=>{m.target.closest("a")&&i(b=>({...b,open:!1}))},children:[n.jsx("div",{className:"xpod-rail-profile",children:n.jsx(Ki,{})}),n.jsx(nr,{items:Je.slice(0,3),label:"应用"}),n.jsx("div",{className:"xpod-rail-host",children:n.jsx(nr,{items:Je.slice(3),label:"本机",attentionIds:s?["device"]:[]})})]}),o?n.jsx("button",{"data-drawer-close":!0,className:"xpod-drawer-close","aria-label":"收起导航",onClick:()=>{i(m=>({...m,open:!1})),c.current?.focus()},children:n.jsx(Ar,{size:18})}):null,n.jsx("div",{className:"xpod-shell-content","data-app-layout-content":!0,children:n.jsx(ht,{})})]})})}function ao({onReady:t}){const e=d.useContext(bt),r=d.useRef(!1),s=e?.isInitializing===!0;return d.useEffect(()=>{!s&&!r.current&&(r.current=!0,t())},[s,t]),null}const ar="xpod:returnTo";function io(){try{const t=sessionStorage.getItem(ar);return t&&sessionStorage.removeItem(ar),t}catch{return null}}const ut="xpod.auth.login-cancelled";function Se(t){try{t?window.localStorage.setItem(ut,"1"):window.localStorage.removeItem(ut)}catch{}}function ds(t){const e=new URL(window.location.href);return e.searchParams.get("xpod-login")!==t?!1:(Se(!0),io(),e.searchParams.delete("xpod-login"),window.history.replaceState(window.history.state,"",`${e.pathname}${e.search}${e.hash}`),!0)}function oo(){return new URL(window.location.href).searchParams.get("xpod-login")==="switch"}function ir(){return ds("switch")}function co(){if(ds("cancelled"))return!0;try{return window.localStorage.getItem(ut)==="1"}catch{return!1}}function lo(t){const e=t.location??(typeof window>"u"?"http://localhost/":window.location),s=[qs(e)],a=uo(e),i=t.transactionStore??ni({origin:a}),o=u=>{if(u!==void 0)return et(u);const g=new URL(us(e)),f=`${g.pathname}${g.search}`;try{return et(f)}catch{return}};let c=!1;const l=u=>{try{return i.begin(u)}catch(g){if(c||!(g instanceof E)||g.code!=="already_active")throw g;try{const f=i.readSinglePending();f&&i.cancel(f.id)}catch{}return i.begin(u)}},h=async(u,g,f)=>{const v=o(u),p={id:Yr(),route:s[0],authorizationSurface:"redirect",discovery:"strict",...f?{prompt:f}:{},...v===void 0?{}:{returnTo:v},...g===void 0?{}:{selectedStorage:g}},m=l(p);c=!0;try{await t.runtime.login(m)}catch(b){try{i.cancel(m.id)}catch{}throw b}finally{c=!1}return m};return{routes:s,startLogin:h,retryLogin:h,cancelLogin(){const u=i.readSinglePending();u&&i.cancel(u.id)},readPending:()=>i.readSinglePending(),callbackUrl(){return`${a}/auth/callback`}}}function uo(t){return new URL(us(t)).origin}function us(t){return typeof t=="string"?t:t.href}function ho(t){if(!t)return"cloud";let e;try{e=new URL(t).hostname.toLowerCase()}catch{return"cloud"}return e==="localhost"||e.endsWith(".localhost")||e.endsWith(".local")||e==="::1"||e==="[::1]"||/^127\./u.test(e)||/^10\./u.test(e)||/^192\.168\./u.test(e)||/^172\.(1[6-9]|2\d|3[01])\./u.test(e)?"edge":"cloud"}const G=dr("zh-CN"),fo={name:"Xpod",icon:n.jsx(pt,{size:24})},po="无法打开选中的 Pod,请重试。",mo="操作未完成,请重试。";function go(t){return n.jsx(Fr,{children:n.jsx(bo,{...t})})}function bo({children:t,autoStart:e=!1,developerMode:r=!1}){const s=Le(),a=d.useContext(bt),i=d.useSyncExternalStore(Dr,ga,()=>!1),o=d.useMemo(()=>lo({runtime:s}),[s]),[c]=d.useState(oo),[l,h]=d.useState(()=>c||co());d.useEffect(()=>{if(l)try{o.cancelLogin()}catch{}},[l,o]);const u=_o(s.state),g=vo(s,u),f="remembered"in u?u.remembered:void 0,v=f?xo(f):void 0,[p,m]=d.useState(f&&v?{signature:v,identity:f}:void 0);v!==void 0&&v!==p?.signature&&m({signature:v,identity:f});const b=u.status==="authenticated"&&g?.status==="ready",[S,N]=d.useState(),[x,I]=d.useState(!1),[k,R]=d.useState(!1),[y,A]=d.useState(c?{prompt:"login"}:void 0),j=d.useRef(0),[_,C]=d.useState(!1),$=d.useRef(!1),T=d.useRef(!1),V=d.useCallback(O=>{console.error("[WebIdAuthBoundary] authentication action failed",O),N(mo)},[]),K=d.useCallback(O=>{const oe=++j.current;N(void 0),I(!0),O().catch(ce=>{oe===j.current&&V(ce)}).finally(()=>{oe===j.current&&I(!1)})},[V]),te=d.useCallback(()=>{Se(!1),h(!1),N(void 0),A({})},[]),J=d.useCallback(()=>{R(!0),te()},[te]),z=d.useCallback(()=>{if(!y)return;const O=y.prompt;h(!1),A(void 0),K(async()=>{const oe=j.current;c&&await s.session.initialize({restorePreviousSession:!1}),oe===j.current&&(c&&ir(),Se(!1),await o.startLogin(void 0,void 0,O))})},[o,y,K,s.session,c]),B=()=>{if(_){re();return}u.status==="authenticated"?s.retryPodOpen?.():J()},H=()=>{if(!_){try{o.cancelLogin()}catch{}c&&ir(),Se(!0),h(!0),A(void 0),j.current+=1,I(!1),N(void 0)}},re=()=>K(async()=>{R(!0),C(!0);const O=()=>{Se(!1),h(!1),mr(),N(void 0),A({prompt:"login"}),C(!1)};a?await at(a,s,{onComplete:O}):(await s.logout(),O())});if(d.useEffect(()=>{s.state.status!=="loading"||$.current||($.current=!0,s.session.initialize({restorePreviousSession:!l}).catch(V))},[l,V,s.session,s.state.status]),d.useEffect(()=>{l||y||i||x||_||!e||T.current||u.status!=="anonymous"||(T.current=!0,te())},[l,i,e,x,y,te,u.status,_]),b&&!x&&!S)return n.jsx(n.Fragment,{children:t});const se=f,de=u.status==="restoring",D=!!globalThis.xpodDesktop&&e&&!k&&!l&&!c&&!_&&!i&&!S&&(de||u.status==="anonymous"),ne=x||!!y||e&&!l&&!i&&u.status==="anonymous"&&!S,w=se&&!l?Oe(se):void 0;let L=((O=!1)=>w?{kind:"remembered",identity:w,busy:O}:{kind:"choose-service",busy:O})(),X,U=J,q,Y=!1;if(!l&&s.state.status==="error"&&s.state.error.name==="SolidSessionPendingError")X={tone:"warning",text:G.noticePending,primaryLabel:G.refreshPage,developerDetail:s.state.error.message},U=()=>window.location.reload();else if(S)X={tone:"warning",text:G.noticeIncomplete,primaryLabel:G.retry,developerDetail:S},U=B,q=w&&!_?re:void 0;else if(de)L={kind:"restoring",...se?{identity:Oe(se)}:{}};else if(ne){const O=w??(!l&&p?Oe(p.identity):void 0);L=O?{kind:"remembered",identity:O,busy:!0}:{kind:"choose-service",busy:!0},U=()=>{},Y=!_}else if(u.status==="authenticated"){const O=Oe(It(u.webId)??{displayName:Fn(u.webId),webId:u.webId});g?.status==="conflict"?(L={kind:"remembered",identity:O},X={tone:"warning",text:G.noticeIncomplete,primaryLabel:G.useAnother,developerDetail:g.message},U=re):g?.status==="error"?(L={kind:"remembered",identity:O},X={tone:"warning",text:G.noticeUnreachable,primaryLabel:G.retry,developerDetail:g.message},U=B,q=re):(L={kind:"remembered",identity:O,busy:!0},U=()=>{})}else w?(q=re,u.status==="expired"?(L={kind:"expired",identity:w},U=B):u.status==="error"&&(X={tone:"warning",text:G.noticeIncomplete,primaryLabel:G.reauthenticate,developerDetail:u.message},U=B)):!l&&(u.status==="error"||u.status==="expired")&&(X={tone:"warning",text:u.status==="expired"?G.expiredLine:G.noticeIncomplete,primaryLabel:G.reauthenticate,developerDetail:u.status==="error"?u.message:void 0},U=B);return n.jsxs(Gs,{ariaLabel:"登录 Xpod",children:[y?n.jsx(ao,{onReady:z}):null,D?n.jsxs("div",{role:"status","aria-live":"polite",className:"flex flex-1 items-center justify-center p-5 text-sm text-muted-foreground",children:[n.jsx(rt,{"aria-hidden":"true",className:"mr-2 h-5 w-5 animate-spin"}),"正在登录…"]}):n.jsx(On,{app:fo,brand:n.jsx(Ws,{renderLogo:O=>n.jsxs("span",{className:"flex items-center gap-2",children:[n.jsx(pt,{size:24}),n.jsxs("span",{className:"flex flex-col text-left",children:[n.jsx("span",{className:"text-[13px] font-medium",children:"Xpod"}),n.jsx("span",{className:"text-[9px] leading-none text-primary",children:O})]})]})}),state:L,notice:X,locale:"zh-CN",developerMode:r,capabilities:{customService:!1,register:!1},onPrimary:U,onUseAnother:q}),Y?n.jsx(pe,{type:"button",variant:"ghost",className:"mt-2 h-9 w-full rounded-lg px-2",onClick:H,children:G.cancel}):null]})}function Oe(t){const e=Be(),r=e&&(!t.webId||e.webId===t.webId)?e.storageBinding.storageUrl:void 0,s=ho(r);return{displayName:t.displayName,...t.avatarUrl?{avatarUrl:t.avatarUrl}:{},...r?{storage:{kind:s,label:s==="cloud"?G.storageCloud:G.storageEdge}}:{}}}function xo(t){return[t.routeId,t.webId??"",t.displayName,t.avatarUrl??""].join("\0")}function vo(t,e){if(e.status!=="authenticated")return;if(t.podError?.webId===e.webId)return{status:"error",message:po};if(t.currentPod===void 0)return{status:"waiting_for_binding"};const r=t.selectedStorage??{webId:t.currentPod.webId,storageUrl:t.currentPod.podUrl},s=t.state.status==="authenticated"?t.state.podUrl:void 0;return t.currentPod.webId===e.webId&&r.webId===t.currentPod.webId&&or(r.storageUrl,t.currentPod.podUrl)&&(s===void 0||or(t.currentPod.podUrl,s))?{status:"ready",selected:r}:{status:"conflict",message:"当前 WebID 已登录,但选中的 Pod 与该身份不一致。"}}function or(t,e){try{return new URL(t).href===new URL(e).href}catch{return t===e}}function It(t){const e=Be();if(e&&!(t&&t!==e.webId))return{displayName:e.account.displayName??e.account.username??e.account.email??"Xpod",...e.account.avatarUrl?{avatarUrl:e.account.avatarUrl}:{},webId:e.webId,routeId:e.routeId}}function Ye(t,e){const r=It(e);return r?{...t,remembered:r}:t}function _o(t){switch(t.status){case"loading":return Ye({status:"restoring"});case"anonymous":return Ye({status:"anonymous"});case"expired":return Ye({status:"expired"},t.webId);case"authenticated":return{status:"authenticated",webId:t.webId};case"error":{const e=It(t.webId);return{status:"error",message:t.error.message,retryRouteId:"xpod-current-origin",...e?{remembered:e}:{}}}}}const wo=d.lazy(()=>ae(()=>import("./ModelsPage-0qWGa5Y6.js").then(t=>t.M),__vite__mapDeps([14,1,2,9,4,5,11,3,6,7,15,12,16]))),yo=d.lazy(()=>ae(()=>import("./DevicePages-D1m_BNtX.js"),__vite__mapDeps([17,1,2,9,4,5,18,6,12,15,13,3,7,8])).then(t=>({default:t.DeviceNetworkPage}))),jo=d.lazy(()=>ae(()=>import("./DevicePages-D1m_BNtX.js"),__vite__mapDeps([17,1,2,9,4,5,18,6,12,15,13,3,7,8])).then(t=>({default:t.DeviceServicesPage}))),Io=d.lazy(()=>ae(()=>import("./DevicePages-D1m_BNtX.js"),__vite__mapDeps([17,1,2,9,4,5,18,6,12,15,13,3,7,8])).then(t=>({default:t.DeviceRuntimePage}))),No=d.lazy(()=>ae(()=>import("./DevicePages-D1m_BNtX.js"),__vite__mapDeps([17,1,2,9,4,5,18,6,12,15,13,3,7,8])).then(t=>({default:t.DeviceLogsPage}))),So=d.lazy(()=>ae(()=>import("./TasksPage-B0EoyRYT.js"),__vite__mapDeps([19,1,2,3,4,5,6,7,9,8,20]))),ge=t=>n.jsx(xr,{children:t}),ko=[{path:"device",element:n.jsx(dt,{subject:"device"}),children:[{index:!0,element:n.jsx(be,{to:"network",replace:!0})},{path:"network",element:ge(n.jsx(yo,{}))},{path:"services",element:ge(n.jsx(jo,{}))},{path:"runtime",element:ge(n.jsx(Io,{}))},{path:"logs",element:ge(n.jsx(No,{}))}]},{path:"settings",element:n.jsx(dt,{subject:"settings"}),children:[{index:!0,element:n.jsx(be,{to:"appearance",replace:!0})},{path:"appearance",element:n.jsx(Vi,{})}]}],Ro=[{element:n.jsx(go,{autoStart:!0,children:n.jsx(ht,{})}),children:[{path:"ai-connections",element:ge(n.jsx(wo,{}))},{path:"pod",element:n.jsx(dt,{subject:"pod"}),children:[{index:!0,element:n.jsx(be,{to:"models",replace:!0})},...["models","search","apps","data"].map(t=>({path:t,element:n.jsx(Hi,{section:t})}))]},{path:"tasks",element:ge(n.jsx(So,{}))},{path:"inbox",element:n.jsx(tr,{title:"收件箱",children:n.jsx(is,{})})},{path:"notifications",element:n.jsx(tr,{title:"通知",children:n.jsx(os,{})})}]}],Po=[{element:n.jsx(no,{product:"settings"}),children:[...ko,...Ro,...Object.entries(Qr).map(([t,e])=>({path:t.slice(1),element:t==="/settings/pod"?n.jsx(Zs,{to:e}):n.jsx(be,{to:e,replace:!0})})),{index:!0,element:n.jsx(be,{to:Re,replace:!0})},{path:"*",element:n.jsx(be,{to:Re,replace:!0})}]}];function Lo(){const t=$e(),e=xs(Po);return d.useEffect(()=>{document.title="Xpod"},[t.pathname]),e}function Co({runtime:t,initialPathname:e}={}){const[r]=d.useState(()=>Eo(e));return n.jsx(Pi,{children:n.jsx(sn,{children:n.jsxs(ji,{value:t,children:[n.jsx(Wa,{}),n.jsx(Xa,{}),n.jsxs(bs,{children:[n.jsx(Ka,{}),n.jsx(Qa,{children:n.jsx($i,{children:n.jsx(Fr,{children:n.jsx(Lo,{})})})}),n.jsx(An,{})]},r)]})})})}function Eo(t){const r=`${Ja(t??globalThis.location?.pathname??Re)}${globalThis.location?.search??""}${globalThis.location?.hash??""}`;return`${globalThis.location?.pathname??""}${globalThis.location?.search??""}${globalThis.location?.hash??""}`!==r&&globalThis.history?.replaceState(null,"",r),r}const Wo=Object.freeze(Object.defineProperty({__proto__:null,XpodShellApp:Co},Symbol.toStringTag,{value:"Module"}));export{er as A,Sa as B,Mn as C,Na as D,Vn as E,Wo as F,Nr as I,ke as L,Wr as N,Br as Q,Er as R,Ir as S,ie as T,ka as V,Re as X,He as a,Co as b,ni as c,Ra as d,ya as e,$r as f,jr as g,Ce as h,Li as i,as as j,zi as k,Ci as l,Wn as m,Z as n,vt as o,qo as p,Mo as q,Go as r,Se as s,Xo as t,Le as u,zo as v,Cn as w,An as x,lo as y,li as z};