@undefineds.co/xpod 0.4.28 → 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.
- package/dist/api/ApiServer.js +4 -0
- package/dist/api/ai-gateway/AiGatewayService.d.ts +55 -0
- package/dist/api/ai-gateway/AiGatewayService.js +145 -6
- package/dist/api/ai-gateway/auth/AiConnectionsInvocationKeyIssuer.js +5 -3
- package/dist/api/ai-gateway/auth/GatewayApiKeyAuthenticator.d.ts +16 -49
- package/dist/api/ai-gateway/auth/GatewayApiKeyAuthenticator.js +6 -71
- package/dist/api/ai-gateway/auth/InvocationTokenAuthenticator.js +1 -0
- package/dist/api/ai-gateway/auth/InvocationTokenCodec.d.ts +4 -0
- package/dist/api/ai-gateway/auth/InvocationTokenCodec.js +8 -1
- package/dist/api/ai-gateway/connect/FileSessionImportAdapter.d.ts +3 -0
- package/dist/api/ai-gateway/connect/FileSessionImportAdapter.js +23 -3
- package/dist/api/ai-gateway/connect/SessionImportProfiles.d.ts +9 -1
- package/dist/api/ai-gateway/connect/SessionImportProfiles.js +4 -3
- package/dist/api/ai-gateway/connect/index.d.ts +40 -0
- package/dist/api/ai-gateway/connect/index.js +194 -4
- package/dist/api/ai-gateway/models/PodModelSelectionRepository.js +1 -1
- package/dist/api/ai-gateway/pod/OwnerPodAccess.js +5 -0
- package/dist/api/ai-gateway/pod/PodBaseUrlResolver.d.ts +11 -2
- package/dist/api/ai-gateway/pod/PodBaseUrlResolver.js +72 -10
- package/dist/api/ai-gateway/quota/ProviderQuotaAdapter.js +1 -1
- package/dist/api/ai-gateway/routing/ModelRouter.d.ts +7 -0
- package/dist/api/ai-gateway/routing/ModelRouter.js +13 -10
- package/dist/api/ai-gateway/service-access/AiConnectionsServiceAccess.d.ts +1 -5
- package/dist/api/ai-gateway/service-access/AiConnectionsServiceAccess.js +8 -63
- package/dist/api/auth/AuthContext.d.ts +4 -0
- package/dist/api/auth/ClientCredentialsAuthenticator.js +11 -5
- package/dist/api/auth/SolidSessionFactory.d.ts +50 -4
- package/dist/api/auth/SolidSessionFactory.js +114 -4
- package/dist/api/chatkit/pod-store.d.ts +8 -1
- package/dist/api/chatkit/pod-store.js +54 -3
- package/dist/api/container/common.js +34 -60
- package/dist/api/container/index.js +0 -3
- package/dist/api/container/routes.js +1 -8
- package/dist/api/container/types.d.ts +2 -9
- package/dist/api/container/types.js +0 -5
- package/dist/api/handlers/AiGatewayManagementHandler.d.ts +4 -12
- package/dist/api/handlers/AiGatewayManagementHandler.js +18 -258
- package/dist/api/middleware/AuthMiddleware.js +29 -1
- package/dist/api/runs/PiAgentRuntimeDriver.js +6 -1
- package/dist/cli/index.js +2 -1
- package/dist/identity/oidc/PodOwnershipResolver.js +16 -6
- package/dist/runtime/ingress-port.d.ts +9 -2
- package/dist/runtime/ingress-port.js +7 -2
- package/dist/runtime/local-secret-file.d.ts +1 -1
- package/dist/runtime/runner/node/CommunitySolidServerCssRunner.d.ts +3 -1
- package/dist/runtime/runner/node/CommunitySolidServerCssRunner.js +31 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.d.ts +3 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.js +96 -67
- package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialPoolSection.d.ts +2 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiCredentialPoolSection.js +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeyRow.d.ts +1 -2
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeyRow.js +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeysSection.js +81 -23
- package/node_modules/@undefineds.co/ai-connections/dist/AiOfferingDetails.d.ts +2 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiOfferingDetails.js +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/AiProviderCard.d.ts +2 -1
- package/node_modules/@undefineds.co/ai-connections/dist/AiProviderCard.js +2 -2
- package/node_modules/@undefineds.co/ai-connections/dist/AiProviderHeader.js +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client/fingerprint.d.ts +1 -0
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client/fingerprint.js +7 -0
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client/normalize.d.ts +1 -2
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client/normalize.js +0 -33
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client/request.d.ts +1 -1
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client/request.js +68 -22
- package/node_modules/@undefineds.co/ai-connections/dist/contract/client/types.d.ts +37 -10
- package/node_modules/@undefineds.co/ai-connections/dist/controller.js +5 -54
- package/node_modules/@undefineds.co/ai-connections/dist/error-wording.js +7 -2
- package/node_modules/@undefineds.co/ai-connections/dist/service-access-resources.cjs +405 -0
- package/node_modules/@undefineds.co/ai-connections/dist/service-access-resources.d.ts +14 -0
- package/node_modules/@undefineds.co/ai-connections/dist/service-access-resources.js +36 -0
- package/node_modules/@undefineds.co/ai-connections/dist/service-access.js +5 -26
- package/node_modules/@undefineds.co/ai-connections/package.json +10 -2
- package/node_modules/@undefineds.co/extension-sdk/dist/solid-permissions.js +131 -13
- package/node_modules/@undefineds.co/extension-sdk/dist/web.d.ts +7 -1
- package/node_modules/@undefineds.co/extension-sdk/package.json +1 -1
- package/node_modules/@undefineds.co/pod-collections/dist/index.cjs +38 -5
- package/node_modules/@undefineds.co/pod-collections/dist/mapping.d.ts +8 -0
- package/node_modules/@undefineds.co/pod-collections/dist/mapping.js +34 -0
- package/node_modules/@undefineds.co/pod-collections/dist/mutations.d.ts +2 -1
- package/node_modules/@undefineds.co/pod-collections/dist/mutations.js +6 -4
- package/node_modules/@undefineds.co/pod-collections/dist/sync.js +4 -3
- package/node_modules/@undefineds.co/pod-collections/package.json +1 -1
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/IdpChrome.d.ts +1 -1
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/IdpChrome.js +2 -2
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/IdpViews.js +2 -2
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/PodSignInFrame.d.ts +3 -3
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/PodSignInFrame.js +5 -5
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/parts.d.ts +5 -5
- package/node_modules/@undefineds.co/shared-ui/dist/pod-sign-in/parts.js +5 -5
- package/node_modules/@undefineds.co/shared-ui/dist/theme.css +32 -5
- package/node_modules/@undefineds.co/shared-ui/package.json +1 -1
- package/package.json +2 -2
- package/static/app/assets/main.css +1 -1
- package/static/app/assets/main.js +18 -18
- package/static/dashboard/assets/{AccountAuthBoundary-Dv52SZc6.js → AccountAuthBoundary-CuqXFEW4.js} +1 -1
- package/static/dashboard/assets/{DesktopOidcCallback-DaT_Rumf.js → DesktopOidcCallback-7i-yOvPW.js} +1 -1
- package/static/dashboard/assets/DevicePages-D1m_BNtX.js +2 -0
- package/static/dashboard/assets/ModelsPage-0qWGa5Y6.js +12 -0
- package/static/dashboard/assets/{PaneListHeader-DtvnRmFq.js → PaneListHeader-uWdPgJ0E.js} +1 -1
- package/static/dashboard/assets/{PodDeletionAuthorizationPanel-BJk_8rJq.js → PodDeletionAuthorizationPanel-C22bhZeD.js} +3 -3
- package/static/dashboard/assets/{PodPage-C4gzEspV.js → PodPage-Dyo3yCb-.js} +1 -1
- package/static/dashboard/assets/{SystemSettingsPage-HaNrP1H1.js → SystemSettingsPage-CeX-oG_a.js} +1 -1
- package/static/dashboard/assets/{TasksPage-BdO5K2L7.js → TasksPage-B0EoyRYT.js} +1 -1
- package/static/dashboard/assets/{WebDesktopEntry-Cj9_ZfJU.js → WebDesktopEntry-DT44RrTa.js} +1 -1
- package/static/dashboard/assets/XpodAiConnectionsPodStore-EXCqZPmb.js +3 -0
- package/static/dashboard/assets/XpodShellApp-BEzi4f1j.css +1 -0
- package/static/dashboard/assets/XpodShellApp-DAFsxamX.js +4 -0
- package/static/dashboard/assets/{account-session-DlcKNG7k.js → account-session-rRAOF7nF.js} +1 -1
- package/static/dashboard/assets/{button-wslF55uZ.js → button-WVnQUNG-.js} +1 -1
- package/static/dashboard/assets/{collection-runtime-uxxgEu13.js → collection-runtime-BAJQ8Qub.js} +1 -1
- package/static/dashboard/assets/{createLucideIcon-BJQl82Qk.js → createLucideIcon-BWelSi3L.js} +1 -1
- package/static/dashboard/assets/dashboard-hSOBxPcP.css +1 -0
- package/static/dashboard/assets/{dashboard-Or0gnkou.js → dashboard-vmne1ZE0.js} +2 -2
- package/static/dashboard/assets/{index-BqFeOML9.js → index-HDQQ8asz.js} +1 -1
- package/static/dashboard/assets/{index-DgKn1twH.js → index-gtv-MAHl.js} +1 -1
- package/static/dashboard/assets/{label-CS6Sx6Zb.js → label-tKuCTJm2.js} +1 -1
- package/static/dashboard/assets/{list-UyhlCFKk.js → list-CKq3KHke.js} +1 -1
- package/static/dashboard/assets/{nav-item-style-CW1Nnorq.js → nav-item-style-B2gI7c52.js} +1 -1
- package/static/dashboard/assets/pod-collections-host-BqOAkacM.js +8 -0
- package/static/dashboard/assets/{safe-continuation-ClWAhcma.js → safe-continuation-BsKjDpAA.js} +1 -1
- package/static/dashboard/assets/{section-header-CEIEcco-.js → section-header-DM0JU-wk.js} +1 -1
- package/static/dashboard/assets/{setting-row-CaYv3dfF.js → setting-row-XiH7UjWy.js} +1 -1
- package/static/dashboard/assets/{xpod-remembered-login-BUF9fin1.js → xpod-remembered-login-nv1g1sfC.js} +4 -4
- package/static/dashboard/dashboard.html +2 -2
- package/static/settings/assets/{AccountAuthBoundary-Chqd38oU.js → AccountAuthBoundary-DAUR0omy.js} +1 -1
- package/static/settings/assets/{DesktopOidcCallback-VUrOSM_q.js → DesktopOidcCallback-BNZAZMWY.js} +1 -1
- package/static/settings/assets/DevicePages-BO9SrXRp.js +2 -0
- package/static/settings/assets/ModelsPage-DREEXdf3.js +12 -0
- package/static/settings/assets/{PaneListHeader-B5RkRqr4.js → PaneListHeader-CeUH0JjQ.js} +1 -1
- package/static/settings/assets/{PodDeletionAuthorizationPanel-DPM-5Izt.js → PodDeletionAuthorizationPanel-Ch4--l4b.js} +3 -3
- package/static/settings/assets/{PodPage-CxND6wwc.js → PodPage-CqJBj3GJ.js} +1 -1
- package/static/settings/assets/{SystemSettingsPage-C8EdMkW7.js → SystemSettingsPage-2LSjpqUa.js} +1 -1
- package/static/settings/assets/{TasksPage-DuqptEm8.js → TasksPage-DA5IRxlP.js} +1 -1
- package/static/settings/assets/{WebDesktopEntry-BRcyktkv.js → WebDesktopEntry-BVelF1q0.js} +1 -1
- package/static/settings/assets/XpodAiConnectionsPodStore-O5-2qBsx.js +3 -0
- package/static/settings/assets/XpodShellApp-BEzi4f1j.css +1 -0
- package/static/settings/assets/XpodShellApp-D1b3kqD0.js +4 -0
- package/static/settings/assets/XpodThemeProvider-hSOBxPcP.css +1 -0
- package/static/settings/assets/{XpodThemeProvider-DK3pIdRG.js → XpodThemeProvider-rUdAw66p.js} +2 -2
- package/static/settings/assets/{account-session-DJOZ03xr.js → account-session-BD1q8D_o.js} +1 -1
- package/static/settings/assets/auth-callback-PWS7okI8.js +1 -0
- package/static/settings/assets/{button-D3yW-2o1.js → button-ZJYFB218.js} +1 -1
- package/static/settings/assets/{collection-runtime-DfGo25mh.js → collection-runtime-C2FHCCXJ.js} +1 -1
- package/static/settings/assets/{createLucideIcon-CacwLsmB.js → createLucideIcon-B2wXvYTD.js} +1 -1
- package/static/settings/assets/{index-r5KRYsKC.js → index-JFAkaKZH.js} +1 -1
- package/static/settings/assets/{label-MJjUmvzG.js → label-BLrTAmGy.js} +1 -1
- package/static/settings/assets/{list-Ce-5k1MX.js → list-Cm96vvJO.js} +1 -1
- package/static/settings/assets/{nav-item-style-ZUbL8KOZ.js → nav-item-style-C2upI7sr.js} +1 -1
- package/static/settings/assets/pod-collections-host-BqOAkacM.js +8 -0
- package/static/settings/assets/{safe-continuation-vlBZFSlU.js → safe-continuation-CYaRj3rj.js} +1 -1
- package/static/settings/assets/{section-header-DGJdEvQw.js → section-header-BviL5H8E.js} +1 -1
- package/static/settings/assets/{setting-row-C7tuFiho.js → setting-row-BYikj0YO.js} +1 -1
- package/static/settings/assets/{settings-CyQPih1O.js → settings-CpoDG_Qr.js} +1 -1
- package/static/settings/assets/{xpod-remembered-login-D-TzzT5K.js → xpod-remembered-login-BJ4QUSXy.js} +4 -4
- package/static/settings/auth-callback.html +3 -3
- package/static/settings/settings.html +3 -3
- package/dist/api/ai-gateway/auth/GatewayApiKey.d.ts +0 -28
- package/dist/api/ai-gateway/auth/GatewayApiKey.js +0 -162
- package/dist/api/ai-gateway/auth/GatewayKeyLocatorCodec.d.ts +0 -26
- package/dist/api/ai-gateway/auth/GatewayKeyLocatorCodec.js +0 -97
- package/dist/api/ai-gateway/auth/PodGatewayAccessKeyRepository.d.ts +0 -67
- package/dist/api/ai-gateway/auth/PodGatewayAccessKeyRepository.js +0 -340
- package/dist/runtime/gateway-locator-secret.d.ts +0 -5
- package/dist/runtime/gateway-locator-secret.js +0 -30
- package/static/dashboard/assets/DevicePages-HjclpIVm.js +0 -2
- package/static/dashboard/assets/ModelsPage-Be2TPd-x.js +0 -11
- package/static/dashboard/assets/XpodAiConnectionsPodStore-B7gmXBmC.js +0 -3
- package/static/dashboard/assets/XpodShellApp-Bwom2xL3.css +0 -1
- package/static/dashboard/assets/XpodShellApp-D_KY4nCW.js +0 -4
- package/static/dashboard/assets/dashboard-CbJ-JkrI.css +0 -1
- package/static/dashboard/assets/pod-collections-host-DjK2xf-b.js +0 -8
- package/static/settings/assets/DevicePages-C6qwvWwu.js +0 -2
- package/static/settings/assets/ModelsPage-Ry_dObRQ.js +0 -11
- package/static/settings/assets/XpodAiConnectionsPodStore-CyA_BJVC.js +0 -3
- package/static/settings/assets/XpodShellApp-Bwom2xL3.css +0 -1
- package/static/settings/assets/XpodShellApp-CsivHJl0.js +0 -4
- package/static/settings/assets/XpodThemeProvider-CbJ-JkrI.css +0 -1
- package/static/settings/assets/auth-callback-GIBYEz_7.js +0 -1
- package/static/settings/assets/pod-collections-host-DjK2xf-b.js +0 -8
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{ad as gt,ae as A,af as wt,F as h,aa as I,a9 as be,ag as It,E as Ce,ah as At,a7 as _t,ai as Pt}from"./xpod-remembered-login-BUF9fin1.js";const W=["openai","anthropic","kimi","bailian","deepseek","zhipu","ollama","custom"],Be={smart:{id:"linx"},fast:{id:"linx-lite"}};function Ct(e,t){const r=e.toLowerCase(),n=Be[t].id;return r===n||r===`undefineds/${n}`}const He={openai:"OpenAI",anthropic:"Anthropic",kimi:"Kimi",bailian:"百炼",deepseek:"DeepSeek",zhipu:"智谱 AI",ollama:"Ollama",custom:"Custom"},Ge=[{id:"api-platform",label:"API Platform",kind:"api-platform",lifecycle:"active",authModes:["apiKey"]}],Ut={id:"api-key",authMode:"apiKey",lifecycle:"active"},St={id:"browser-login",authMode:"apiKey",connectMode:"browserAssistedApiKey",lifecycle:"active"},q=[Ut,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"}}],Ue="https://www.kimi.com/code",Et="https://www.kimi.com/code/console",kt="https://www.kimi.com/user/agreement",Mt="https://api.kimi.com/coding/v1",Rt="https://api.kimi.com/coding/",Ot="https://platform.moonshot.cn/console/api-keys",Se="https://platform.moonshot.cn/console/account",Tt="https://platform.moonshot.cn/docs/intro",xt="https://api.moonshot.ai/v1",J="https://bailian.console.aliyun.com/",X="https://help.aliyun.com/zh/model-studio/",Ee="https://open.bigmodel.cn/usercenter/apikeys",ke="https://open.bigmodel.cn/",Lt="https://open.bigmodel.cn/api/paas/v4",$t="https://open.bigmodel.cn/api/coding/paas/v4",Ve={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:q,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:q,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:Rt,quotaStrategy:"subscription",quotaUrl:Ue,consoleUrl:Et,subscriptionUrl:Ue,usagePolicyUrl:kt,supportsDeveloperMessages:!1}),Me({id:"api-platform",label:"API Platform",kind:"api-platform",authModes:["apiKey"],productLabel:"Moonshot AI",runtimeProviderIds:["kimi"],credentialPrefixHints:["sk-"],baseUrl:xt,quotaStrategy:"console",quotaUrl:Se,consoleUrl:Ot,subscriptionUrl:Se,usagePolicyUrl:Tt})],bailian:[Y({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:J,usagePolicyUrl:X}),Y({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:J,usagePolicyUrl:X}),Y({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:J,usagePolicyUrl:X}),Y({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:J,usagePolicyUrl:X})],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:q,productLabel:"智谱 AI",runtimeProviderIds:["zhipu"],credentialPrefixHints:["id."],consoleUrl:Ee,subscriptionUrl:"https://open.bigmodel.cn/finance-center/expense-manage",endpoints:[{protocol:"chatCompletions",baseUrl:Lt,region:"cn"}],modelDiscovery:{strategy:"openaiCompatible",path:"/models",endpointProtocol:"chatCompletions"},quota:{strategy:"console",url:"https://open.bigmodel.cn/finance-center/expense-manage"},usagePolicyUrl:ke,region:"cn"},{id:"coding-plan",label:"GLM Coding Plan",kind:"token-plan",lifecycle:"active",authModes:["apiKey"],authorizationMethods:q,productLabel:"智谱 AI",runtimeProviderIds:["zhipu"],credentialPrefixHints:["id."],consoleUrl:Ee,subscriptionUrl:"https://bigmodel.cn/glm-coding",endpoints:[{protocol:"chatCompletions",baseUrl:$t,region:"cn"}],modelDiscovery:{strategy:"openaiCompatible",path:"/models",endpointProtocol:"chatCompletions"},quota:{strategy:"subscription",url:"https://bigmodel.cn/glm-coding"},usagePolicyUrl:ke,region:"cn"}]};function Me(e){return{id:e.id,label:e.label,kind:e.kind,lifecycle:"active",authModes:e.authModes,authorizationMethods:q,productLabel:e.productLabel,runtimeProviderIds:e.runtimeProviderIds,credentialPrefixHints:e.credentialPrefixHints,consoleUrl:e.consoleUrl,subscriptionUrl:e.subscriptionUrl,endpoints:We(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 Y(e){return{id:e.id,label:e.label,lifecycle:"active",productLabel:"Alibaba Bailian",kind:e.kind,authModes:["apiKey"],authorizationMethods:q,runtimeProviderIds:e.runtimeProviderIds,credentialPrefixHints:e.credentialPrefixHints,consoleUrl:e.consoleUrl,subscriptionUrl:e.consoleUrl,endpoints:We(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 We(e,t,r,n){return[{protocol:"chatCompletions",baseUrl:e,region:r,...n===void 0?{}:{supportsDeveloperMessages:n}},...t?[{protocol:"anthropic",baseUrl:t,region:r}]:[]]}function Je(e,t=!1){return(Ve[e]??Ge).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 fn=W.flatMap(e=>[e,...Nt(e).map(t=>`${e}-${t.id}`)]);function Nt(e){return e==="custom"?B:Ve[e]??Ge}function zt(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 Re(e,t){const r=Je(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 Z(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 Q(e){return{offeringId:e.offeringId,priority:e.priority??100,enabled:e.enabled??!0,health:e.health??"unknown",...e.baseUrl?{baseUrl:e.baseUrl}:{}}}function yn(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 te extends Error{constructor(t,r,n={}){const i=Xe(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=b(t)&&typeof t.providerStatus=="number"?t.providerStatus:void 0,this.payload=t,this.provider=n.provider,this.authMode=n.authMode}}function Xe(e){if(b(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 Oe(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 qt(e){if(!W.includes(e))throw new Error(`Unsupported AI provider: ${e}`)}function ae(e){if(!(!b(e)||typeof e.id!="string"||typeof e.owner!="string"||!Array.isArray(e.scopes)||!e.scopes.every(t=>typeof t=="string")||typeof e.createdAt!="string"))return g({id:e.id,kind:e.kind==="client-credentials"?e.kind:void 0,credentialResource:u(e.credentialResource),fingerprint:u(e.fingerprint),owner:e.owner,scopes:e.scopes,createdAt:e.createdAt,expiresAt:u(e.expiresAt),lastUsedAt:u(e.lastUsedAt),disabledAt:u(e.disabledAt),revokedAt:u(e.revokedAt),name:u(e.name),maskedHint:u(e.maskedHint),plaintextAvailable:typeof e.plaintextAvailable=="boolean"?e.plaintextAvailable:void 0,clientCredentialId:u(e.clientCredentialId),appliedTo:u(e.appliedTo),appliedOn:u(e.appliedOn),appliedAt:u(e.appliedAt),appliedClients:K(e.appliedClients)})}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)!b(r)||typeof r.id!="string"||!r.id||t.push(g({id:r.id,displayName:u(r.displayName),inputModalities:K(r.inputModalities),outputModalities:K(r.outputModalities),capabilities:K(r.capabilities)}));return t}function K(e){if(!Array.isArray(e))return;const t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}function Ye(e){if(!b(e)||typeof e.id!="string"||vt(e.id))return;const t=U(e.provider)??U(e.providerId)??U(e.owned_by)??Ft(e.id);if(!t)return;const r=b(e.capabilities)?e.capabilities.imageInput:void 0;return g({id:e.id,provider:t,offeringId:u(e.offeringId),resourceId:u(e.resourceId),displayName:u(e.displayName)??u(e.display_name)??u(e.name),modelType:typeof e.modelType=="string"&&Object.prototype.hasOwnProperty.call(gt,e.modelType)?e.modelType:void 0,contextWindow:pe(e.contextWindow)??pe(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:xe(e.modalities,"input")??(r===!0?["text","image"]:r===!1?["text"]:void 0),outputModalities:xe(e.modalities,"output"),capabilities:Kt(e)})}function Dt(e){if(!(!b(e)||typeof e.id!="string"||!e.id))return g({id:e.id,displayName:u(e.displayName)??u(e.display_name)??u(e.name),provider:u(e.provider)??u(e.providerId)??u(e.owned_by)})}function xe(e,t){if(!b(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 Kt(e){if(Array.isArray(e.custom_capabilities)){const r=e.custom_capabilities.filter(n=>typeof n=="string");if(r.length>0)return r}if(!b(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 vt(e){return Object.keys(Be).some(t=>Ct(e,t))}function U(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":W.includes(t)?t:void 0}function Ft(e){const t=e.split("/",1)[0];return e.includes("/")?U(t):void 0}function pe(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function jt(e){const t=new Map;for(const r of e){const n=Bt(r);if(!n)continue;const i=t.get(n.id);t.set(n.id,i?er(i,n):n)}return[...t.values()]}function Bt(e){return Gt(e)??Ht(e)}function Ht(e){if(!b(e)||typeof e.provider!="string"||!mr(e.status)||!b(e.connect)||!Array.isArray(e.connect.modes)||!e.connect.modes.every(ge)||typeof e.connect.configured!="boolean")return;const t=U(e.provider);if(!t)return;const r=ir(e,t);return{id:t,name:it(t),offerings:[],credentials:r?[r]:[],selectedModels:[],status:rr(e.status)}}function Gt(e){if(!b(e))return;const t=U(e.id)??U(e.provider);if(!t||!cr(e.status))return;const r=k(e.offerings,Vt),n=k(e.credentials,H),i=k(e.selectedModels,Ye);return{id:t,name:u(e.name)??it(t),offerings:r,credentials:n,selectedModels:i,status:e.status}}function Vt(e){if(!b(e)||typeof e.id!="string"||!e.id)return;const t=k(e.authModes,rt);return g({id:e.id,label:u(e.label),kind:u(e.kind),lifecycle:Xt(e.lifecycle),authModes:t,authorizationMethods:k(e.authorizationMethods,Ze),runtimeProviderIds:K(e.runtimeProviderIds),productLabel:u(e.productLabel),credentialPrefixHints:K(e.credentialPrefixHints),consoleUrl:u(e.consoleUrl),subscriptionUrl:u(e.subscriptionUrl),endpoints:k(e.endpoints,Qe),modelDiscovery:Yt(e.modelDiscovery),quota:Zt(e.quota),usagePolicyUrl:u(e.usagePolicyUrl),region:u(e.region)})}function Wt(e){if(!b(e)||typeof e.offeringId!="string"||!e.offeringId)return;const t=U(e.provider);if(!t)return;const r=k(e.authorizationMethods,Ze);return{provider:t,offeringId:e.offeringId,...Array.isArray(e.endpoints)?{endpoints:k(e.endpoints,Qe)}:{},authorizationMethods:r}}function Ze(e){if(!b(e)||typeof e.id!="string"||!e.id)return;const t=rt(e.authMode),r=Jt(e.lifecycle);if(!t||!r)return;const n=ge(e.connectMode)?e.connectMode:void 0;return g({id:e.id,authMode:t,connectMode:n,label:u(e.label),lifecycle:r,reason:u(e.reason)})}function Jt(e){return e==="active"||e==="unavailable"?e:void 0}function Xt(e){return e==="active"||e==="legacy"||e==="unavailable"?e:void 0}function Qe(e){if(!b(e))return;const t=u(e.protocol),r=u(e.baseUrl);if(!(!t||!r))return g({protocol:t,baseUrl:r,region:u(e.region)})}function Yt(e){if(!b(e))return;const t=u(e.strategy),r=u(e.path),n=u(e.endpointProtocol);return t&&r&&n?{strategy:t,path:r,endpointProtocol:n}:void 0}function Zt(e){if(!b(e))return;const t=u(e.strategy),r=u(e.url);return t&&r?{strategy:t,url:r}:void 0}function H(e){if(!(!b(e)||typeof e.id!="string"||!e.id||typeof e.offeringId!="string"||!e.offeringId||!nt(e.authMode)||typeof e.enabled!="boolean"||typeof e.priority!="number"||!Number.isFinite(e.priority)||!sr(e.health)||typeof e.version!="number"||!Number.isFinite(e.version)))return g({id:e.id,provider:U(e.provider),offeringId:e.offeringId,authMode:e.authMode,label:u(e.label),enabled:e.enabled,priority:e.priority,health:e.health,maskedHint:u(e.maskedHint),baseUrl:u(e.baseUrl),proxyUrl:u(e.proxyUrl),expiresAt:u(e.expiresAt),lastFailureCode:u(e.lastFailureCode),lastFailureAt:u(e.lastFailureAt),rateLimitResetAt:u(e.rateLimitResetAt),failCount:pe(e.failCount),version:e.version})}function et(e){return b(e)?Object.fromEntries(Object.entries(e).filter(([t])=>!Qt(t)).map(([t,r])=>[t,tt(r)])):{}}function tt(e){return Array.isArray(e)?e.map(tt):b(e)?et(e):e}function Qt(e){const t=e.toLocaleLowerCase();return t.includes("secret")||t.includes("token")||t.includes("apikey")||t==="api_key"||t==="key"||t==="authorization"}function er(e,t){const r=se([...e.credentials,...t.credentials],o=>o.id),n=se([...e.offerings,...t.offerings],o=>o.id),i=se([...e.selectedModels,...t.selectedModels],tr);return{id:e.id,name:e.name??t.name,offerings:n,credentials:r,selectedModels:i,status:nr(e.status,t.status)}}function tr(e){return e.resourceId??`${e.provider}:${e.offeringId??""}:${e.id}`}function rr(e){return e==="connected"?"available":e==="reauthRequired"?"attention":"unconfigured"}function nr(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 ir(e,t){if(e.status==="disconnected")return;const r=or(e.authMode);return g({id:u(e.credentialIri)??`${t}:current`,offeringId:ar(t,r),authMode:r,label:u(e.accountLabel),enabled:e.status==="connected",priority:0,health:e.status==="reauthRequired"||e.reauthRequired===!0?"expired":"healthy",maskedHint:u(e.maskedHint),baseUrl:u(e.baseUrl),proxyUrl:u(e.proxyUrl),expiresAt:u(e.expiresAt),version:typeof e.version=="number"?e.version:0})}function or(e){return e==="deviceCodeOAuth"?"deviceCode":"apiKey"}function ar(e,t){return e==="kimi"&&(t==="deviceCode"||t==="oauth")?"subscription-key":t==="deviceCode"||t==="oauth"?"official-subscription":"api-platform"}function rt(e){return nt(e)?e:void 0}function nt(e){return e==="oauth"||e==="deviceCode"||e==="apiKey"||e==="local"}function sr(e){return e==="healthy"||e==="expired"||e==="invalid"||e==="unknown"}function cr(e){return e==="unconfigured"||e==="configured"||e==="available"||e==="attention"||e==="unavailable"}function k(e,t){return Array.isArray(e)?e.map(t).filter(D):[]}function se(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 it(e){return He[e]}function dr(e){if(!b(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=U(e.provider);if(t)return g({id:e.id,credentialIri:e.credentialIri,webId:e.webId,provider:t,authMode:e.authMode,status:e.status,accountLabel:u(e.accountLabel),expiresAt:u(e.expiresAt),version:typeof e.version=="number"?e.version:void 0,reauthRequired:typeof e.reauthRequired=="boolean"?e.reauthRequired:void 0})}function lr(e,t){if(!b(e)||!ge(e.mode)||!yr(e.status)||e.provider!==t)throw new Error("AI Connection returned an invalid Connect response");return g({mode:e.mode,status:e.status,provider:t,attemptId:u(e.attemptId),state:u(e.state),signature:u(e.signature),expiresAt:u(e.expiresAt),authorizationUrl:ce(e.authorizationUrl),userCode:u(e.userCode),verificationUri:ce(e.verificationUri),verificationUriComplete:ce(e.verificationUriComplete),intervalSeconds:typeof e.intervalSeconds=="number"?e.intervalSeconds:void 0,apiKeyManagementSupported:typeof e.apiKeyManagementSupported=="boolean"?e.apiKeyManagementSupported:void 0,credentialId:u(e.credentialId),offeringId:u(e.offeringId),authorizationMethodId:u(e.authorizationMethodId),oauthCredential:ur(e.oauthCredential),message:u(e.message)})}function ur(e){if(e!==void 0){if(!b(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 g({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:u(e.expiresAt),scope:u(e.scope),idToken:u(e.idToken),accountSubject:u(e.accountSubject),accountId:u(e.accountId),accountLabel:u(e.accountLabel),offeringId:u(e.offeringId),authorizationMethodId:u(e.authorizationMethodId),expectedVersion:typeof e.expectedVersion=="number"?e.expectedVersion:void 0})}}function pr(e,t){if(!b(e)||!Array.isArray(e.models))throw new Error("AI Connection returned an invalid model discovery response");const r=e.models.map(n=>{if(!b(n)||typeof n.id!="string"||!n.id)return;const i=Array.isArray(n.capabilities)?n.capabilities.filter(c=>typeof c=="string"):void 0,o=fr(n.modelType);return g({id:n.id,displayName:u(n.displayName),capabilities:i??(o==="embedding"?["embedding"]:void 0),modelType:o})}).filter(D);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 g(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function fr(e){return e==="chat"||e==="embedding"?e:void 0}function u(e){return typeof e=="string"?e:void 0}function ce(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 ge(e){return e==="browserAssistedApiKey"||e==="deviceCodeOAuth"||e==="authorizationCodeOAuth"||e==="connectUnsupported"}function yr(e){return e==="pending"||e==="authorization_pending"||e==="slow_down"||e==="completed"||e==="expired"||e==="cancelled"||e==="unsupported"}function mr(e){return e==="connected"||e==="disconnected"||e==="reauthRequired"}function b(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function D(e){return e!==void 0}function we(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}){const n=we(t),i=async(a,s,d,f={})=>{const m=await r(`${n}${a}`,{method:s,credentials:"omit",mode:"cors",headers:{accept:"application/json",...d?{"content-type":"application/json"}:{}},...d?{body:JSON.stringify(d)}:{}}),w=await Oe(m);if(!m.ok)throw new te(w,m.status,f);return w},o=a=>(qt(a),`/api/ai/gateway/providers/${a}`),c=async(a,s,d,f)=>{const m=await i(`${o(a)}${s}`,d,f,{provider:a});return lr(m,a)},l=()=>i("/v1/models","GET"),y=async()=>{const a=await l();return Array.isArray(a.data)?a.data.map(Ye).filter(D):[]};return{webId:e,apiBase:n,getServiceAccess(){return i("/api/applets/service-access/ai-connections","GET")},async listProviders(){const a=await i("/api/ai/providers","GET");return Array.isArray(a.data)?jt(a.data):[]},async listAuthorizationMethods(){const a=await r(`${n}/api/ai/connections/authorization-methods`,{method:"GET",credentials:"omit",mode:"cors",headers:{accept:"application/json"}});if(a.status===404)return[];const s=await Oe(a);if(!a.ok)throw new te(s,a.status);return b(s)&&Array.isArray(s.data)?s.data.map(Wt).filter(D):[]},listModels:y,listGatewayModels:y,async listGatewayCatalogModels(){const a=await l();if(!b(a)||!Array.isArray(a.data))throw new Error("AI Connection returned an invalid Gateway model catalog response");return a.data.map(Dt).filter(D)},async listGatewayKeys(){const a=await i("/api/ai/gateway/keys","GET");return Array.isArray(a.data)?a.data.map(ae).filter(D):[]},async createGatewayKey(a){const s=await i("/api/ai/gateway/keys","POST",g(a));if(typeof s.key!="string"||!s.key)throw new Error("Xpod did not return the new API Key");const d=ae(s.record);if(!d)throw new Error("Xpod returned an invalid API Key record");return{plaintext:s.key,record:d}},async updateGatewayKey(a,s){const d=await i(`/api/ai/gateway/keys/${encodeURIComponent(a)}`,"PATCH",s),f=ae(d.record);if(!f)throw new Error("Xpod returned an invalid API Key record");return f},async deleteGatewayKey(a){await i(`/api/ai/gateway/keys/${encodeURIComponent(a)}`,"DELETE")},async beginConnect(a,s,d){return await c(a,"/connect/begin","POST",g({mode:s,offeringId:d?.offeringId,authorizationMethodId:d?.authorizationMethodId}))},connectStatus(a,s){if(!s.attemptId)throw new Error("Connect attempt id is required");const d=new URLSearchParams({state:s.state??"",signature:s.signature??""});return s.mode&&d.set("mode",s.mode),c(a,`/connect/status/${encodeURIComponent(s.attemptId)}?${d}`,"GET")},completeApiKey(a,s,d,f,m){return c(a,"/connect/complete-api-key","POST",g({attemptId:s.attemptId,state:s.state,signature:s.signature,offeringId:s.offeringId,apiKey:d,accountLabel:f,baseUrl:m}))},pollDevice(a,s){return c(a,"/connect/poll","POST",g({mode:s.mode,attemptId:s.attemptId,state:s.state,signature:s.signature,offeringId:s.offeringId}))},cancelConnect(a,s){return c(a,"/connect/cancel","POST",g({mode:s.mode,attemptId:s.attemptId,state:s.state,signature:s.signature,offeringId:s.offeringId}))},refreshOAuthCredential(a,s,d,f,m,w){return c(a,"/connect/refresh","POST",{credentialId:s,refreshToken:d,expectedVersion:f,...m?{offeringId:m}:{},...w?{mode:w}:{}})},async disconnect(a,s){const d=s?`?${new URLSearchParams({credentialId:s})}`:"",f=await i(`${o(a)}/connect${d}`,"DELETE");return dr(f.record)},async createApiKeyCredential(a,s){const d=await i(`/api/ai/providers/${a}/credentials/api-key`,"POST",g({...s}),{provider:a}),f=H(d.credential);if(!f)throw new Error("AI Connection returned an invalid Provider credential");return f},async createLocalCredential(a,s){const d=await i(`/api/ai/providers/${a}/credentials/local`,"POST",g(s),{provider:a}),f=H(d.credential);if(!f)throw new Error("AI Connection returned an invalid Provider credential");return f},async updateProviderCredential(a,s,d){const f=await i(`/api/ai/providers/${a}/credentials/${encodeURIComponent(s)}`,"PATCH",g({...d}),{provider:a}),m=H(f.credential);if(!m)throw new Error("AI Connection returned an invalid Provider credential");return m},async deleteProviderCredential(a,s){const d=await i(`/api/ai/providers/${a}/credentials/${encodeURIComponent(s)}`,"DELETE",void 0,{provider:a});return H(d.credential)},async testProviderCredential(a,s){const d=await i(`/api/ai/providers/${a}/credentials/test`,"POST",g({...s}),{provider:a});return et(d.result)},quota(a,s=!1,d){const f=!s&&d?.credentialIri?`?credentialIri=${encodeURIComponent(d.credentialIri)}${d.offeringId?`&offeringId=${encodeURIComponent(d.offeringId)}`:""}`:"";return i(`${o(a)}/quota/${s?"refresh":"status"}${f}`,s?"POST":"GET",s?g({offeringId:d?.offeringId,credentialId:d?.credentialId,credentialIri:d?.credentialIri}):void 0,{provider:a})},quotaFromSecret(a,s){return i(`${o(a)}/quota/refresh`,"POST",g(s),{provider:a})},async discoverModels(a,s){const d=await i(`${o(a)}/models/refresh`,"POST",g({...s}),{provider:a,authMode:s?.authMode});return pr(d,a)},async saveProviderModel(a,s){const d=await i(o(a)+"/models","POST",g({id:s.id,displayName:s.displayName,inputModalities:s.inputModalities,outputModalities:s.outputModalities,capabilities:s.capabilities}),{provider:a});return Te(d.data)},async deleteProviderModel(a,s){const d=await i(`${o(a)}/models/${encodeURIComponent(s)}`,"DELETE",void 0,{provider:a});return Te(d.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 A.buildId({id:e})}function _r(e){return A.buildId({id:`custom-instance-${encodeURIComponent(e)}.ttl#this`})}function Le(e,t){const r=crypto.randomUUID();return t==="local"?`${e}-local-${r}`:`${e}-${r}`}function mn(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":W.find(n=>r===n||r.startsWith(`${n}-`))}function x(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 M(e){const t=x(e);if(t)return(t.split("#",1)[0]??t).replace(/\.ttl$/u,"")}const ot="AI Connection request failed. Please try again.";function ee(e){return typeof e=="object"&&e!==null}const at="订阅登录态自动刷新失败,请稍后重试。",st="订阅登录态已失效,请在原客户端重新登录后重读,或使用设备码登录。",ct="模型服务请求超时。请检查网络或代理设置,稍后重试同步模型。",dt="订阅登录态不可用,请重读登录态或重新登录后再同步模型。",lt=new Set([ct,dt,at,st,"密钥不可用。请检查密钥是否填写正确,或换一个密钥后重试。","模型服务地址不正确。请检查服务地址后重试。","请求太频繁。请稍等一会儿再试。","模型服务暂时没有响应。请稍后重试。","模型列表获取失败。请检查密钥、服务地址或网络后重试。"]);function $e(e){if(e.startsWith("provider_models_response_error:"))return Ie(e.slice(31))??"模型列表获取失败。请检查密钥、服务地址或网络后重试。";const t=re(e);if(t)return t;const r=e.split(":",1)[0]?.trim(),n=r?re(r):void 0;return n||(e==="AI Connection service identity is unavailable"||lt.has(e)||Er(e)?e:e.startsWith("invalid_")?"AI Connection returned an invalid response.":ot)}function Pr(e){return e instanceof te?Cr(e.payload,e.status,{provider:e.provider,authMode:e.authMode}):e instanceof Error?$e(e.message):$e(String(e))}function Cr(e,t,r={}){const n=Xe(e);if(n==="provider_models_response_error"){const c=ee(e)&&typeof e.message=="string"?Ie(e.message):void 0;return c||"模型列表获取失败。请检查密钥、服务地址或网络后重试。"}if(n==="provider_models_fetch_failed"){const c=ee(e)&&typeof e.providerStatus=="number"?e.providerStatus:void 0,l=ee(e)&&typeof e.providerMessage=="string"?e.providerMessage.trim():void 0;return Sr(Ur(c,r.authMode),l)}const i=n?re(n,r.provider):void 0;if(i)return i;const o=ee(e)&&typeof e.error=="string"?e.error:void 0;if(o){const c=re(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?`${fe(r.provider)} connection is not configured.`:t===429?"AI Connection is rate limited. Please try again later.":t===503?"AI Connection service is unavailable.":ot}function re(e,t){switch(e.trim().toLowerCase().replace(/-/g,"_")){case"not_configured":case"notconfigured":return t?`${fe(t)} connection is not configured.`:"AI provider connection is not configured.";case"unsupported":return t?`${fe(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 ct;case"invalid_proxy_url":return"代理地址必须是无账号密码的 HTTP 或 HTTPS 地址。";case"oauth_refresh_failed":case"oauth_refresh_unavailable":case"local_session_refresh_failed":return at;case"oauth_session_reauth_required":case"oauth_refresh_token_required":case"local_session_reauth_required":case"local_session_missing_refresh_token":return st;case"models_persistence_failed":return"模型已获取,但保存到 Pod 失败。请重试同步模型。";case"quota_credential_not_found":return"当前身份没有可用的额度凭证。";case"credential_secret_unavailable":return"当前凭证密钥不可用,请重新保存后再查询额度。";case"gateway_api_key_plaintext_unavailable":return"Pod 中未找到此 API Key 的原文,无法复制配置。请创建新的 Key,更新客户端后再删除旧 Key。";case"quota_adapter_not_found":return"该接入方式不支持查询官方额度。";default:return}}function Ur(e,t){return e===401||e===403?t==="deviceCodeOAuth"?dt:"密钥不可用。请检查密钥是否填写正确,或换一个密钥后重试。":e===404?"模型服务地址不正确。请检查服务地址后重试。":e===429?"请求太频繁。请稍等一会儿再试。":e!==void 0&&e>=500?"模型服务暂时没有响应。请稍后重试。":"模型列表获取失败。请检查密钥、服务地址或网络后重试。"}function Sr(e,t){const r=t?Ie(t):void 0;return r?`${e} 上游返回:${r}`:e}function Er(e){const r=e.indexOf(" 上游返回:");return r<=0?!1:lt.has(e.slice(0,r))}function Ie(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 fe(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 kr(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 te&&(o.message=Pr(o)),o}});return t}const Mr={"api-key":"添加 API Key","browser-login":"打开控制台","browser-oauth":"浏览器登录","device-code":"设备码登录","local-session-import":"已有登录态","local-service":"本地服务"};function Rr(e){return e.label??Mr[e.id]}function hn(e){return e.map(t=>{const r=Rr(t);return r===t.label?t:{...t,label:r}})}function ne(e){return He[e]}const Or=3e4;function bn({webId:e,podUrl:t,authenticatedFetch:r}){return kr(hr({webId:e,podBaseUrl:t,authenticatedFetch:Tr(r)}))}function Tr(e){return(async(t,r)=>ye(await e(t,r)))}function xr({podUrl:e,authenticatedFetch:t,invocationFetch:r=t,now:n=()=>new Date,invocationSelector:i=zr}){const o=we(e);let c,l;const y=async(f,m)=>{const w=await t(f,m);return c=await Nr(w.clone(),i),w},a=async()=>{if(Dr(c,n()))return c;if(l)return l;l=s();try{return await l}finally{l=void 0}},s=async()=>{if(!(await y(`${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 m=c;if(!m?.token)throw new Error("AI Connection request failed. Please try again.");return m},d=async(f,m)=>{const w=await a(),S=Kr(w);if(!S)throw new Error("AI Connection request failed. Please try again.");const F=new Headers(m?.headers);return F.set("Authorization",`Bearer ${S}`),r(f,{...m,credentials:"omit",headers:F})};return(async(f,m)=>{if(Lr(f,o))return y(f,m);if(!$r(f,o))return t(f,m);const w=await d(f,m);if(w.status!==401)return ye(w);await w.arrayBuffer(),c=void 0;const S=await d(f,m);return ye(S)})}function gn({podUrl:e,controlPlaneOrigin:t,authenticatedFetch:r,invocationFetch:n,now:i}){const o=we(e),c=n??r,y=xr({podUrl:e,authenticatedFetch:r,invocationFetch:(a,s)=>{const d=new URL(a instanceof Request?a.url:String(a),o);if(t&&d.origin===o&&d.pathname.startsWith("/api/ai/client-configuration/")){const f=new URL(`${d.pathname}${d.search}`,t);return c(a instanceof Request?new Request(f,a):f.href,s)}return c(a,s)},now:i,invocationSelector:qr});return{inspect:async a=>{const s=await y($(o,a),{method:"GET",credentials:"omit",headers:{accept:"application/json"}});return s.status===403||s.status===404||s.status===503?(await s.arrayBuffer(),Ne()):N(s)},plan:async a=>N(await y(`${$(o,a.client)}/plan`,{method:"POST",credentials:"omit",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({endpoint:t?new URL(t).origin:a.endpoint,...a.activeModels!==void 0?{activeModels:a.activeModels}:{}})})),apply:async a=>N(await y(`${$(o,a.client)}/apply`,{method:"POST",credentials:"omit",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({planId:a.planId,apiKey:a.apiKey,confirmation:a.confirmation})})),verify:async a=>N(await y(`${$(o,a.client)}/verify`,{method:"POST",credentials:"omit",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({planId:a.planId})})),launch:async a=>N(await y(`${$(o,a)}/launch`,{method:"POST",credentials:"omit",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({})})),restore:async a=>{const s=await y(`${$(o,a)}/restore`,{method:"POST",credentials:"omit",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({})});return s.status===403||s.status===404||s.status===503?(await s.arrayBuffer(),Ne()):N(s)}}}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 Nr(e,t){if(!(!e.ok||!e.headers.get("content-type")?.includes("application/json")))try{const r=await e.json();return vr(t(r))}catch{return}}function zr(e){return e.invocation}function qr(e){const t=e.aiClientConfiguration;return ie(t)?t.invocation:void 0}function Dr(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()>Or}function Kr(e){return e?.token}function vr(e){if(!ie(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 ye(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 $(e,t){return`${e}/api/ai/client-configuration/${encodeURIComponent(t)}`}async function N(e){if(!e.ok)throw await Fr(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 Fr(e){let t;try{t=e.headers.get("content-type")?.includes("application/json")?await e.json():void 0}catch{t=void 0}if(ie(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 Ne(){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}const r=Hr(t);return r?new Response(JSON.stringify({code:r}),{status:e.status,statusText:e.statusText,headers:{"content-type":"application/json"}}):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 Hr(e){if(!(!ie(e)||typeof e.error!="string")&&e.error==="Gateway API Key plaintext is not available")return"gateway_api_key_plaintext_unavailable"}function ie(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}const V=Array.from(new Set([...W,"zhipu","ollama","custom"])),ze=new WeakMap,Gr=Ce.storage.base.slice(Ce.storage.base.lastIndexOf("/")+1);function Vr(e){const t=e.indexOf("#");return t<0?e:e.slice(0,t)}function wn(e){wt();const t=new URL("settings/-/sparql",e.podUrl).toString();return h.setSparqlEndpoint(t),A.setSparqlEndpoint(t),I.setSparqlEndpoint(t),{credentialsTableDocument(){return h.buildIri(e.podUrl,{id:Gr})},providerTableDocument(r,n){const i=P(r);if(!i)throw new Error("unsupported_provider");const o=i==="custom"&&n?me(n):R(i);return A.buildIri(e.podUrl,{id:Vr(o)})},async listModels(){return await e.database.init?.(I),(await e.database.select().from(I).execute()).map(Qr).filter(T)},async listProviders(){await e.database.init?.(h,A,I);const r=await e.database.select().from(h).execute(),n=await e.database.select().from(A).execute(),i=await e.database.select().from(I).execute();return Jr(e,r,n,i)},async createApiKeyCredential(r,n){const i=P(r);if(!i)throw new Error("unsupported_provider");await e.database.init?.(h,A);const o=p(n.id),c=o??h.buildId({id:Le(i,"apiKey")}),l=1,y=Z(i,n.offeringId??G(i,"apiKey")),a=n.baseUrl??Re(i,y),s=de(n.proxyUrl),d={id:c,provider:i==="custom"?me(c):R(i),service:"ai",authMode:"apiKey",offeringId:y,status:"active",accountLabel:n.label,label:n.label,baseUrl:a,proxyUrl:s,keyVersion:String(l),reauthRequired:!1,encryptedSecret:j(e,i,c,{type:"apiKey",apiKey:n.apiKey}),encryptionAlgorithm:"PLAINTEXT",metadata:{...Q({offeringId:y,baseUrl:a,priority:n.priority}),...n.compatibility?{compatibility:n.compatibility}:{}}};return await De(e,c,d,o!==void 0),_(e,i,d)},async createLocalCredential(r,n){const i=P(r);if(!i)throw new Error("unsupported_provider");await e.database.init?.(h,A);const o=p(n.id),c=o??h.buildId({id:Le(i,"local")}),l=Z(i,n.offeringId??G(i,"local")),y=n.baseUrl??Re(i,l),a={id:c,provider:R(i),service:"ai",authMode:"local",offeringId:l,status:"active",accountLabel:n.label??"Local",label:n.label??"Local",baseUrl:y,keyVersion:"1",reauthRequired:!1,encryptedSecret:j(e,i,c,{type:"local"}),encryptionAlgorithm:"PLAINTEXT",metadata:Q({offeringId:l,baseUrl:y,priority:n.priority})};return await De(e,c,a,o!==void 0),_(e,i,a)},async saveOAuthCredential(r,n){const i=P(r);if(!i)throw new Error("unsupported_provider");const c=(ze.get(e.database)??Promise.resolve()).then(async()=>{await e.database.init?.(h,A);const l=Z(i,n.offeringId??G(i,"deviceCode")),a=(await e.database.select().from(h).execute()).find(E=>{const L=_(e,i,E);if(!L||L.authMode!=="deviceCode"&&L.authMode!=="oauth"||ve(i,L.offeringId)!==ve(i,l)||E.status!=="active"&&E.status!=="disabled")return!1;const bt=z(e,i,L.id,E.encryptedSecret);return Xr(n,C(E.metadata),bt)}),s=a&&_(e,i,a),d=C(a?.metadata),f=s&&z(e,i,s.id,a?.encryptedSecret),m=s?.id??h.buildId({id:`${i}-oauth-${crypto.randomUUID()}`}),w=n.accountLabel??"OAuth",S=n.accountId??p(d?.accountId)??p(f?.accountId),F=n.accountSubject??p(d?.authoritativeSubject)??p(f?.accountSubject)??p(f?.authoritativeSubject),oe={...a,id:m,provider:R(i),service:"ai",authMode:"deviceCodeOAuth",offeringId:l,status:s?.enabled===!1?"disabled":"active",accountLabel:a?.accountLabel??w,label:a?.label??w,expiresAt:n.expiresAt,scopes:n.scope?n.scope.split(/\s+/u).filter(Boolean):void 0,keyVersion:String((s?.version??0)+1),reauthRequired:!1,failCount:0,lastFailureCode:null,lastFailureAt:null,rateLimitResetAt:null,encryptedSecret:j(e,i,m,{type:"deviceCodeOAuth",accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:n.expiresAt,scope:n.scope,idToken:n.idToken,accountId:S,accountSubject:F,accountLabel:n.accountLabel,offeringId:l,authorizationMethodId:n.authorizationMethodId}),encryptionAlgorithm:"PLAINTEXT",metadata:{...d,...Q({offeringId:l,priority:s?.priority,enabled:s?.enabled,health:"healthy"}),authoritativeSubject:F,accountId:S,authorizationMethodId:n.authorizationMethodId}};if(a){const E={...oe};if(delete E.id,!await e.database.updateById(h,m,E))throw new Error("credential_version_conflict")}else await e.database.insert(h).values(oe).execute();return _(e,i,oe)});return ze.set(e.database,c.then(()=>{},()=>{})),c},async updateOAuthCredential(r,n,i,o){const c=P(r);if(!c)throw new Error("unsupported_provider");await e.database.init?.(h,A);const l=await e.database.findById(h,n),y=l&&_(e,c,l);if(!l||!y||y.authMode!=="deviceCode")throw new Error("oauth_credential_not_found");if(y.version!==i)throw new Error("credential_version_conflict");const a=z(e,c,n,l.encryptedSecret),s=o.accountId??p(C(l.metadata)?.accountId)??p(a?.accountId),d=o.accountSubject??p(C(l.metadata)?.authoritativeSubject)??p(a?.accountSubject)??p(a?.authoritativeSubject),f=Z(c,o.offeringId??y.offeringId),m={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:s,accountSubject:d,accountLabel:o.accountLabel??p(l.accountLabel),offeringId:f,authorizationMethodId:o.authorizationMethodId??p(C(l.metadata)?.authorizationMethodId)}),accountLabel:o.accountLabel??p(l.accountLabel),label:o.accountLabel??p(l.label),offeringId:f,metadata:{...C(l.metadata),...Q({offeringId:f,health:"healthy"}),authoritativeSubject:d,accountId:s,authorizationMethodId:o.authorizationMethodId??p(C(l.metadata)?.authorizationMethodId)}},w=await e.database.updateById(h,n,m);if(!w)throw new Error("credential_version_conflict");return _(e,c,w)},async updateProviderCredential(r,n,i){const o=P(r);if(!o)throw new Error("unsupported_provider");await e.database.init?.(h,A);const c=await e.database.findById(h,n),l=c&&_(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 y=i.apiKey!==void 0&&z(e,o,n,c.encryptedSecret)?.apiKey!==i.apiKey,a={...C(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:de(i.proxyUrl)},...y?{health:"unknown"}:{}},s={...i.label===void 0?{}:{accountLabel:i.label,label:i.label},...i.baseUrl===void 0?{}:{baseUrl:i.baseUrl},...i.proxyUrl===void 0?{}:{proxyUrl:de(i.proxyUrl)},...i.enabled===void 0?{}:{status:i.enabled?"active":"disabled"},...y?{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:a},d=await e.database.updateById(h,n,s);if(!d)throw new Error("credential_update_failed");const f=_(e,o,d);if(!f)throw new Error("credential_update_failed");return f},async markCredentialHealth(r,n,i,o){const c=P(r);if(!c)throw new Error("unsupported_provider");await e.database.init?.(h);const l=await e.database.findById(h,n),y=l&&_(e,c,l);if(!l||!y)throw new Error("credential_not_found");if(y.version!==o)throw new Error("credential_version_conflict");const a=await e.database.updateById(h,n,{keyVersion:String(y.version+1),metadata:{...C(l.metadata),health:i},...i==="healthy"?{failCount:0,lastFailureCode:null,lastFailureAt:null,rateLimitResetAt:null,reauthRequired:!1}:{}});if(!a)throw new Error("credential_update_failed");const s=_(e,c,a);if(!s)throw new Error("credential_update_failed");return s},async deleteProviderCredential(r,n){const i=P(r);if(!i)throw new Error("unsupported_provider");await e.database.init?.(h,A);const o=await e.database.findById(h,n),c=o&&_(e,i,o);if(c)return await e.database.deleteById(h,n),c},async readCredentialSecret(r,n){const i=P(r);if(!i)throw new Error("unsupported_provider");const o=await e.database.findById(h,n);if(!o||!_(e,i,o))throw new Error("credential_not_found");const c=z(e,i,n,o.encryptedSecret);if(!c)throw new Error("credential_secret_unavailable");return c},async saveDiscoveredModels(r,n,i){const o=P(r);if(!o)throw new Error("unsupported_provider");await e.database.init?.(h,A,I);const c=await qe(e,n),l=Ke(o,c);await Fe(e.database,l,ne(o));const y=await e.database.select().from(I).execute(),a=new Set(y.map(f=>p(f.id)).filter(T)),s=i.map(en).filter(T),d=new Set(s.map(f=>f.id));for(const f of y.filter(m=>tn(m,l,o))){const m=O(p(f.id),l)??yt(p(f.id));m&&!d.has(m)&&p(f.status)!=="unavailable"&&await e.database.updateById(I,String(f.id),{status:"unavailable"})}for(const f of s)await rn(e,l,f,a)},async saveModelSelection(r,n,i){const o=P(r);if(!o)throw new Error("unsupported_provider");await e.database.init?.(A,I);const c=o==="custom"&&i?await qe(e,i):null;if(o==="custom"&&i&&!c)throw new Error("credential_not_found");const l=c?Ke(o,c):R(o);await Fe(e.database,l,ne(o));const a=(await e.database.select().from(A).execute()).find(m=>v(p(m.id),l)),s=p(a?.id)??l,d=await e.database.select().from(I).execute(),f=[...new Set(n.map(m=>on(o,m,d,c?l:void 0)))];await Wr(e,s,f)}}}async function ut(e,t,r,n){if(n.length===0)return;if(!e.authenticatedFetch)throw new Error("uri_array_authenticated_fetch_required");const i=pt(t,e.podUrl,r),o=y=>{if(!/^[a-z][a-z0-9+.-]*:/iu.test(y)||/[\s<>"{}|^`\\]/u.test(y))throw new Error("uri_array_invalid_iri");return`<${y}>`},c=n.flatMap(({column:y,values:a})=>{const s=y.options.predicate;if(!y.options.isArray||y.options.baseType!=="uri"||!s)throw new Error("uri_array_column_required");const d=`${o(i)} ${o(s)}`,f=[...new Set(a)].map(m=>`${d} ${o(m)} .`).join(`
|
|
2
|
-
`);return[`DELETE WHERE { ${d} ?previous . }`,...f?[`INSERT DATA { ${f} }`]:[]]}),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 Wr(e,t,r){await ut(e,A,t,[{column:A.columns.hasModel,values:r.map(n=>pt(I,e.podUrl,n))}])}function pt(e,t,r){return/^https?:\/\//u.test(r)?r:e.buildIri(t,{id:r})}async function qe(e,t){const r=await e.database.findById(h,t);return r||((await e.database.select().from(h).execute()).find(i=>{const o=p(i.id);return o===t||(o?h.buildIri(e.podUrl,{id:o})===t:!1)})??null)}function Jr(e,t,r,n){const i=t.filter(o=>p(o.service)==="ai").filter(o=>p(o.status)!=="revoked");return V.map(o=>{const c=i.map(s=>_(e,o,s)).filter(T).sort((s,d)=>s.priority-d.priority||s.id.localeCompare(d.id)),l=r.find(s=>M(p(s.id))===o),a=mt(l?.hasModel).map(s=>Zr(o,s,n));return{id:o,name:o==="custom"?c.find(s=>s.label)?.label??ne(o):ne(o),offerings:o==="custom"?an(i.filter(s=>_(e,o,s))):Je(o,e.openAiSubscriptionImportAvailable===!0),credentials:c,selectedModels:a,status:sn(c)}})}async function De(e,t,r,n){if(!(n?await e.database.findById(h,t):null)){await e.database.insert(h).values(r).execute();return}const o={...r};if(delete o.id,!await e.database.updateById(h,t,o))throw new Error("credential_create_failed")}function j(e,t,r,n){return wr({webId:e.webId,provider:t,credentialIri:h.buildIri(e.podUrl,{id:r}),secret:n})}function Xr(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(p).filter(T).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 _(e,t,r){const n=p(r.id);if(!n)return;const i=_e(p(r.provider))??dn(n);if(i!==t)return;const o=C(r.metadata),c=ht(r.authMode);if(c)return{id:n,provider:i,offeringId:ft(r,i,c),authMode:c,label:p(r.accountLabel)??p(r.label),enabled:je(o?.enabled)??p(r.status)==="active",priority:le(o?.priority)??100,health:un(o?.health)??(je(r.reauthRequired)?"expired":"healthy"),lastFailureCode:p(r.lastFailureCode),lastFailureAt:ue(r.lastFailureAt),rateLimitResetAt:ue(r.rateLimitResetAt),failCount:le(r.failCount),maskedHint:cn(e,i,n,r.encryptedSecret),baseUrl:p(r.baseUrl),proxyUrl:ln(p(r.proxyUrl)??p(o?.proxyUrl)),compatibility:Yr(o?.compatibility),expiresAt:ue(r.expiresAt),version:le(r.keyVersion)??0}}function Yr(e){return e==="auto"||e==="openai"||e==="anthropic"?e:void 0}function ft(e,t,r){return p(e.offeringId)??p(C(e.metadata)?.offeringId)??Pe(p(e.provider))??G(t,r)}function Zr(e,t,r){const n=r.find(l=>x(p(l.id))===x(t)),i=p(n?.isProvidedBy),o=n?O(t,i??e)??t:O(t,e)??t,c=n??r.find(l=>{const y=p(l.id),a=p(l.isProvidedBy);return y===t||O(y,e)===o||_e(a)===e&&O(y,a??e)===o});return{id:o,provider:e,offeringId:Pe(p(c?.isProvidedBy)),credentialId:Ae(i),resourceId:p(c?.id)??t,displayName:p(c?.displayName),availability:p(c?.status)==="unavailable"||!c?"unavailable":"available"}}function Qr(e){const t=p(e.isProvidedBy),r=_e(t),n=r&&O(p(e.id),t??r);if(!(!r||!n))return{id:n,provider:r,offeringId:Pe(t),credentialId:Ae(t),resourceId:p(e.id),displayName:p(e.displayName),availability:p(e.status)==="unavailable"?"unavailable":"available",...nn(e)}}function en(e){const t=C(e),r=p(t?.id);if(!r)return;const n=p(t?.modelType)?.trim(),i=n?be(n):void 0;return{id:r,displayName:p(t?.displayName),...i?{rdfType:[I.getType(),i]}:{},...Array.isArray(t?.capabilities)?{capabilities:It(t.capabilities)}:{}}}function Ke(e,t){const r=Ae(p(t?.provider));return r?me(r):R(e)}function R(e){return Ar(e)}function me(e){return _r(e)}function Ae(e){const t=M(e),r=t?.startsWith("custom-instance-")?t.slice(16):void 0;if(r)try{return decodeURIComponent(r)}catch{return}}function ve(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 v(e,t){const r=x(e),n=x(t);return r!==void 0&&r===n}function tn(e,t,r){const n=p(e.isProvidedBy);return v(n,t)?!0:r==="custom"?!1:M(n)?.startsWith(`${r}-`)===!0}function yt(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(A).execute()).some(i=>v(p(i.id),t))||await e.insert(A).values({id:t,displayName:r}).execute()}async function rn(e,t,r,n){const i=he(t,r.id),o=n.has(i),c=o?await e.database.findById(I,i):void 0,l={displayName:r.displayName??r.id,isProvidedBy:t,status:"active"};if(o)await e.database.updateById(I,i,l);else{const a=e.database.insert(I).values({id:i,...l}).toIR();for(const s of a.rows)delete s.rdfType,delete s.capabilities;await e.database.session.execute({type:"insert",table:I,values:a.rows[0],plan:a})}const y=[];if(!o||r.rdfType){const a=mt(c?.rdfType).filter(s=>/^[a-z][a-z0-9+.-]*:/iu.test(s)&&be(s)!==s);y.push({column:I.columns.rdfType,values:[...new Set([I.getType(),...a,...r.rdfType??[]])]})}r.capabilities!==void 0&&y.push({column:I.columns.capabilities,values:r.capabilities}),await ut(e,I,i,y),n.add(i)}function nn(e){const t=Array.isArray(e.rdfType)?e.rdfType:[e.rdfType],r=t.find(i=>typeof i=="string"&&be(i)===i),n=At({rdfType:t,capabilities:e.capabilities}).capabilities.map(_t).filter(T);return{...r?{modelType:Pt(r)}:{},...n.length>0?{capabilities:n}:{}}}function he(e,t){const r=x(e)??`${e}.ttl`;return`${r.split("#",1)[0]??r}#${encodeURIComponent(t)}`}function on(e,t,r,n){const i=p(t.resourceId),o=n??R(e),c=p(t.id),l=c?r.filter(a=>{const s=p(a.isProvidedBy),d=M(s);return(n?v(s,n):d===e||d?.startsWith(`${e}-`)===!0)&&O(p(a.id),s??o)===c}):[],y=n||l.length===1?l[0]:void 0;if(i){const a=r.find(m=>p(m.id)===i);if(!a&&y)return String(y.id);const s=p(a?.isProvidedBy),d=M(s),f=n?v(s,n):d===e||d?.startsWith(`${e}-`)===!0;if(a&&!f)throw new Error("invalid_model_selection_resource");if(!a){const m=c??yt(i),w=M(i),S=n?v(w,n):w===e||w?.startsWith(`${e}-`)===!0;if(!m||!S)throw new Error("invalid_model_selection_resource");return he(o,m)}return i}if(!c)throw new Error("invalid_model_selection_resource");return p(y?.id)??he(o,c)}function O(e,t){if(!e)return;const n=x(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 mt(e){if(Array.isArray(e))return e.map(p).filter(T);const t=p(e);return t?[t]:[]}function an(e){const t=new Map;for(const r of e){const n=C(r.metadata),i=ft(r,"custom",ht(r.authMode)??"apiKey"),o=zt(n?.compatibility,i),c=p(r.baseUrl)??p(n?.baseUrl),l=B.find(y=>y.id===i)??B.find(y=>y.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 sn(e){return e.some(t=>t.health==="expired"||t.health==="invalid")?"attention":e.some(t=>t.enabled)?"available":e.length>0?"configured":"unconfigured"}function cn(e,t,r,n){const i=z(e,t,r,n),o=p(i?.apiKey);if(o)return o.length<=8?`${o.slice(0,2)}…`:`${o.slice(0,3)}...${o.slice(-4)}`}function z(e,t,r,n){return Ir({webId:e.webId,provider:t,credentialIri:h.buildIri(e.podUrl,{id:r}),envelope:n})}function _e(e){const t=M(e),r=P(t);return r||V.find(n=>t?.startsWith(`${n}-`))}function Pe(e){const t=M(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 V)if(t.startsWith(`${r}-`))return t.slice(r.length+1)}}function dn(e){const t=/\/([^/#]+)\.ttl#/u.exec(e);return P(t?.[1])}function P(e){if(typeof e!="string"||!e.trim())return;const t=e.trim().toLowerCase();if(t==="zhipu"||t.startsWith("zhipu-"))return"zhipu";if(V.includes(t))return t;for(const r of V)if(t.startsWith(`${r}-`)||r==="bailian"&&(t==="bailian-token-plan"||t==="bailian-coding-plan"))return r}function de(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 ln(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 ht(e){if(e==="oauth"||e==="deviceCode"||e==="apiKey"||e==="local")return e;if(e==="deviceCodeOAuth")return"deviceCode"}function un(e){if(e==="healthy"||e==="expired"||e==="invalid"||e==="unknown")return e;if(e==="reauthRequired")return"expired";if(e==="disabled")return"unknown"}function C(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function p(e){return typeof e=="string"&&e.trim()?e:void 0}function le(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 je(e){if(typeof e=="boolean")return e;if(e==="true")return!0;if(e==="false")return!1}function ue(e){return e instanceof Date?e.toISOString():p(e)}function T(e){return e!==void 0}export{te as A,He as P,Q as a,_r as b,Le as c,G as d,Ar as e,bn as f,wn as g,fn as h,W as i,mn as j,hr as k,Pr as l,Ct as m,yn as n,Re as o,M as p,gn as q,Z as s,hn as w};
|
|
@@ -1 +0,0 @@
|
|
|
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-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}}
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DgKn1twH.js","assets/dashboard-Or0gnkou.js","assets/dashboard-CbJ-JkrI.css","assets/xpod-remembered-login-BUF9fin1.js","assets/createLucideIcon-BJQl82Qk.js","assets/button-wslF55uZ.js","assets/PodDeletionAuthorizationPanel-BJk_8rJq.js","assets/account-session-DlcKNG7k.js","assets/safe-continuation-ClWAhcma.js","assets/nav-item-style-CW1Nnorq.js","assets/PodPage-C4gzEspV.js","assets/XpodAiConnectionsPodStore-B7gmXBmC.js","assets/section-header-CEIEcco-.js","assets/setting-row-CaYv3dfF.js","assets/ModelsPage-Be2TPd-x.js","assets/list-UyhlCFKk.js","assets/label-CS6Sx6Zb.js","assets/DevicePages-HjclpIVm.js","assets/PaneListHeader-DtvnRmFq.js","assets/TasksPage-BdO5K2L7.js","assets/TasksPage-DPpAgn4C.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as d,j as n,_ as ae,u as or,X as us,e as hs,L as Ze,a as fs,b as $e,O as ht,f as ps,N as ms,d as be,B as gs,g as bs}from"./dashboard-Or0gnkou.js";import{aj as Nt,ak as cr,al as lr,am as xs,an as vs,ao as Me,ap as St,aq as _s,ar as ws,as as je,at as Rt,au as ys,av as kt,aw as dr,ax as js,I as Is,H as Ns,ay as Ss,az as Rs,aA as Q,aB as ur,a1 as ks,aC as Be,Z as Ps,_ as hr,aD as Ls,aE as Cs,aF as Es,aG as ft,aH as As,L as Ts,K as et,V as Us,aI as tt,aJ as Pt,aK as Ds,M as Lt,aL as Os,aM as Fs,aN as $s,aO as Bs,aP as zs,aQ as Ms,aR as fr,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 pr,aZ as Xs,a_ as qs,X as Gs}from"./xpod-remembered-login-BUF9fin1.js";import{c as M,e as Ft,i as mr,a as Ws,B as pe,f as Hs}from"./button-wslF55uZ.js";import{p as ze,i as Vs,I as gr,P as Qs,X as Ks,R as br,r as Js,q as Ys}from"./PodDeletionAuthorizationPanel-BJk_8rJq.js";import{X as pt,u as xr,a as vr,r as mt,s as gt,A as bt}from"./account-session-DlcKNG7k.js";import{f as Zs,g as en,r as tn,A as rn}from"./safe-continuation-ClWAhcma.js";import{i as sn,T as _r,u as nn,D as wr,W as an,h as on,j as cn}from"./nav-item-style-CW1Nnorq.js";import{c as H}from"./createLucideIcon-BJQl82Qk.js";const ln=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],dn=ze("circle-check",ln);const un=[["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"}]],hn=ze("circle-x",un);const fn=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],pn=ze("search",fn);const mn=[["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",mn),yr=d.forwardRef(({className:t,multiple:e,size:r,...s},a)=>n.jsx("select",{ref:a,multiple:e,size:r,className:M(Vs,!e&&(!r||r<=1)&&"min-h-10",t),...s}));yr.displayName="NativeSelect";const jr=d.forwardRef(({className:t,placeholder:e="搜索",...r},s)=>n.jsxs("div",{className:"relative min-w-0 w-full",children:[n.jsx(pn,{"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(gr,{...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)})]}));jr.displayName="SearchInput";const gn={success:"bg-success",warning:"bg-warning",destructive:"bg-destructive",info:"bg-primary",neutral:"border border-muted-foreground bg-transparent"},bn={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",bn[r],gn[t],s),...i,...c})}function xn({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 vn={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"},_n={info:"text-primary",success:"text-success",warning:"text-warning",destructive:"text-destructive",neutral:"text-muted-foreground"},wn={info:Nt,success:dn,warning:xt,destructive:hn,neutral:Nt};function Ir({tone:t="info",title:e,icon:r,action:s,role:a="status",className:i,children:o,...c}){const l=wn[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",vn[t],i),...c,children:[n.jsx("span",{"aria-hidden":"true",className:M("mt-0.5 shrink-0",_n[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 yn={label:"Restoring session…"},Xe={title:"Connecting…",detail:"Waiting for the provider",cancelLabel:"Cancel"},qe={title:"Sign-in failed",primaryLabel:"Retry",secondaryLabel:"Back"};function he(t,e){return t?.trim()?t:e}function jn({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 In({accountName:t,avatarUrl:e,label:r}){const s=he(r,yn.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(jn,{name:t,avatarUrl:e,size:"lg"}),n.jsx("p",{className:"text-sm font-medium text-foreground",children:t})]}):null,n.jsx(cr,{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 Bo({title:t,detail:e,providerLabel:r,providerHost:s,onCancel:a,cancelLabel:i}){const o=he(t,Xe.title),c=he(e,Xe.detail),l=he(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(cr,{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",mr),children:l})}):null]})}function zo({title:t,description:e,primaryLabel:r,onPrimary:s,secondaryLabel:a,onSecondary:i}){const o=he(t,qe.title),c=he(r,qe.primaryLabel),l=he(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 Nn=Object.defineProperty,Nr=(t,e)=>Nn(t,"name",{value:e,configurable:!0}),$t="horizontal",Sn=["horizontal","vertical"],Rn=d.forwardRef(Nr(function(e,r){const{decorative:s,orientation:a=$t,...i}=e,o=Sr(a)?a:$t,l=s?{role:"none"}:{"aria-orientation":o==="vertical"?o:void 0,role:"separator"};return n.jsx(Qs.div,{"data-orientation":o,...l,...i,ref:r})},"Separator"));function Sr(t){return Sn.includes(t)}Nr(Sr,"isValidOrientation");var Rr=Rn;const kr=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}));kr.displayName=Rr.displayName;const kn=3e3,Pn=Ws("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,ue=[];const st=new Set;function Pr(){for(const t of st)t()}function Lr(t){const e=ue.findIndex(r=>r.id===t);e<0||(clearTimeout(ue[e].timer),ue=ue.filter(r=>r.id!==t),Pr())}function Ln(t){Lr(t)}function Mo(t){Ge=(Ge+1)%Number.MAX_SAFE_INTEGER;const e=Ge.toString(),r=t.duration??kn,s={id:e,title:t.title,description:t.description,variant:t.variant??"default",className:t.className,timer:setTimeout(()=>Lr(e),r)};return ue=[...ue.slice(-2),s],Pr(),e}function Cn(t){return st.add(t),()=>{st.delete(t)}}function Bt(){return ue}function En({className:t}){const e=d.useSyncExternalStore(Cn,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(Pn({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",mr),onClick:()=>Ln(r.id),children:n.jsx(Ks,{"aria-hidden":"true",className:"h-3.5 w-3.5"})})]},r.id))})}const An=300;function Tn({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 Un({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(js,{label:t.customLabel,error:e,children:c=>n.jsx(gr,{...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:dr,busy:r,disabled:!a.trim(),children:t.customSubmit})]})}function Dn({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:m,onRegister:f,onToggleCustom:x}){const p=lr(a,i),g=xs(An),[v,S]=d.useState(!1),I=e?n.jsx("div",{"data-pod-sign-in":"source",children:e}):n.jsx(vs,{icon:t.icon,name:t.name});if(r.kind==="restoring"){const _=g?r.identity:void 0;return n.jsxs(Me,{"data-pod-sign-in-state":"restoring",children:[I,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:g?n.jsxs("p",{className:"flex items-center gap-2 text-[13px] text-muted-foreground",children:[n.jsx(_s,{}),p.restoring]}):null})]})]})}const b=r.busy===!0,j=s?.primaryLabel??(r.kind==="remembered"?ws(p.enterApp,{app:t.name}):r.kind==="expired"?p.reauthenticate:p.useXpod),R=s?n.jsx(Tn,{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:[R,n.jsx(je,{className:Rt,busy:b,"data-pod-sign-in-primary":"true",onClick:h,children:j}),u?n.jsx(je,{variant:"ghost",className:M(ys,"w-full"),disabled:b,onClick:u,children:p.useAnother}):null]}),children:[I,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 k=l?.customService!==!1,y=l?.register!==!1&&!!f,A=k&&(r.customOpen??v),N=()=>{const _=!A;S(_),x?.(_)};return n.jsxs(Me,{"data-pod-sign-in-state":"choose-service",actions:n.jsxs(n.Fragment,{children:[R,n.jsxs(je,{className:Rt,busy:b,"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,j]}),k?n.jsxs(n.Fragment,{children:[n.jsx(je,{variant:"outline",className:dr,disabled:b,"aria-expanded":A,onClick:N,children:p.useOtherSolid}),A?n.jsx(Un,{copy:p,error:r.customError,busy:b,onSubmit:m}):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:b,onClick:f,children:p.register})]}):null]}),children:[I,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(kt,{summary:p.whatIsWebId,children:p.whatIsWebIdBody}),n.jsx(kt,{summary:p.whatIsPod,children:p.whatIsPodBody})]})]})]})}function On(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 Fn=[["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"}]],$n=H("bell",Fn);const Bn=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],zn=H("chevron-right",Bn);const Mn=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],Xn=H("circle-check",Mn);const qn=[["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"}]],Gn=H("copy",qn);const Wn=[["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"}]],Hn=H("inbox",Wn);const Vn=[["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"}]],Qn=H("log-in",Vn);const Kn=[["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"}]],Jn=H("log-out",Kn);const Yn=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],Zn=H("menu",Yn);const ea=[["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"}]],ta=H("monitor",ea);const ra=[["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"}]],Cr=H("refresh-cw",ra);const sa=[["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"}]],na=H("settings",sa);const aa=[["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"}]],ia=H("sparkles",aa);const oa=[["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"}]],ca=H("square-check-big",oa);const la=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],da=H("user-round",la);const ua=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Er=H("x",ua);function ha({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(Is,{"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 Ar=!1,Tr={status:"idle"},Fe,de;const nt=new Set,fa=()=>Ar,zt=()=>Tr;function Ur(t){return nt.add(t),()=>{nt.delete(t)}}function Ee(t){Tr=t,nt.forEach(e=>e())}function at(t,e,r={}){return de||(Ar=!0,Fe={account:t,runtime:e,solidCleared:!1,onComplete:r.onComplete},Dr())}function Dr(){if(de)return de;if(!Fe)return Promise.resolve();const t=Fe;return de=(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(()=>{de=void 0}),de}const Mt=d.createContext(!1);function Or({children:t}){const e=d.useContext(Mt),r=d.useSyncExternalStore(Ur,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(Ns,{mode:"page",title:"退出 Xpod",children:r.status==="running"?n.jsx(In,{label:"正在退出…"}):n.jsx(ha,{title:"退出未完成",description:r.step==="account"?"账号会话尚未退出,请重试完成退出。":"WebID 会话尚未退出,请重试完成退出。",primaryLabel:"重试退出",onPrimary:()=>{Dr().catch(()=>{})}})}),n.jsx("div",{className:s?"hidden":"contents","aria-hidden":s||void 0,inert:s||void 0,children:t})]})}function pa(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,ma=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,Xt={"\\":"\\","'":"'",'"':'"',n:`
|
|
3
|
-
`,r:"\r",t:" ",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},ga=/[\x00-\x20<>\\"\{\}\|\^\`]/,ba={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_newline:!0,_comment:!0,_whitespace:!0,_endOfFile:!0},xa=/$0^/;class va{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 ba)&&this[r]instanceof RegExp&&(this[r]=xa)}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 m="",f="",x="",p=null,g=0,v=!1;switch(u){case"^":if(s.length<3)break;if(s[1]==="^"){if(this._previousMarker="^^",s=s.substr(2),s[0]!=="<"){v=!0;break}}else{this._n3Mode&&(g=1,m="^");break}case"<":if(p=this._unescapedIri.exec(s))m="IRI",f=p[1];else if(p=this._iri.exec(s)){if(f=this._unescape(p[1]),f===null||ga.test(f))return o(this);m="IRI"}else s.length>1&&s[1]==="<"?(m="<<",g=2):this._n3Mode&&s.length>1&&s[1]==="="&&(g=2,this._isImpliedBy?(m="abbreviation",f="<"):(m="inverse",f=">"));break;case">":s.length>1&&s[1]===">"&&(m=">>",g=2);break;case"_":((p=this._blank.exec(s))||r&&(p=this._blank.exec(`${s} `)))&&(m="blank",x="_",f=p[1]);break;case'"':if(p=this._simpleQuotedString.exec(s))f=p[1];else if({value:f,matchLength:g}=this._parseLiteral(s),f===null)return o(this);(p!==null||g!==0)&&(m="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(p=this._simpleApostropheString.exec(s))f=p[1];else if({value:f,matchLength:g}=this._parseLiteral(s),f===null)return o(this);(p!==null||g!==0)&&(m="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(p=this._variable.exec(s))&&(m="var",f=p[0]);break;case"@":this._previousMarker==="literal"&&(p=this._langcode.exec(s))?(m="langcode",f=p[1]):(p=this._keyword.exec(s))&&(m=p[0]);break;case".":if(s.length===1?r:s[1]<"0"||s[1]>"9"){m=".",g=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} `)))&&(m="literal",f=p[0],x=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))?m=p[0].toUpperCase():v=!0;break;case"f":case"t":(p=this._boolean.exec(s))?(m="literal",f=p[0],x=Te.boolean):v=!0;break;case"a":(p=this._shortPredicates.exec(s))?(m="abbreviation",f="a"):v=!0;break;case"=":this._n3Mode&&s.length>1&&(m="abbreviation",s[1]!==">"?(g=1,f="="):(g=2,f=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(g=1,m=u);break;case"{":!this._lineMode&&s.length>=2&&(s[1]==="|"?(m="{|",g=2):(m=u,g=1));break;case"|":s.length>=2&&s[1]==="}"&&(m="|}",g=2);break;default:v=!0}if(v&&((this._previousMarker==="@prefix"||this._previousMarker==="PREFIX")&&(p=this._prefix.exec(s))?(m="prefix",f=p[1]||""):((p=this._prefixed.exec(s))||r&&(p=this._prefixed.exec(`${s} `)))&&(m="prefixed",x=p[1]||"",f=this._unescape(p[2]))),this._previousMarker==="^^")switch(m){case"prefixed":m="type";break;case"IRI":m="typeIRI";break;default:m=""}if(!m)return r||!/^'''|^"""/.test(s)&&/\n|\r/.test(s)?o(this):this._input=s;const S=g||p[0].length,I=i(m,f,x,h,S);this.previousToken=I,this._previousMarker=m,s=s.substr(S,s.length)}function i(c,l,h,u,m){const f=s?a-s.length:a,x=f+m,p={type:c,value:l,prefix:h,line:u,start:f,end:x};return e(null,p),p}function o(c){e(c._syntaxError(/^\S*/.exec(s)[0]))}}_unescape(e){let r=!1;const s=e.replace(ma,(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=Ss.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:_a,xsd:me}=Z;let Pe,wa=0;const ya={namedNode:Br,blankNode:zr,variable:Xr,literal:Mr,defaultGraph:Sa,quad:it,triple:it,fromTerm:Ie,fromQuad:qr};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 Fr extends ie{get termType(){return"NamedNode"}}class Re 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 Fr(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:_a.langString}equals(e){return e instanceof Re?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 ja extends ie{constructor(e){super(`_:${e}`)}get termType(){return"BlankNode"}get value(){return this.id.substr(2)}}class Ia extends ie{constructor(e){super(`?${e}`)}get termType(){return"Variable"}get value(){return this.id.substr(1)}}class Na extends ie{constructor(){return super(""),Pe||this}get termType(){return"DefaultGraph"}equals(e){return this===e||!!e&&this.termType===e.termType}}Pe=new Na;class $r 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 Br(t){return new Fr(t)}function zr(t){return new ja(t||`n3-${wa++}`)}function Mr(t,e){if(typeof e=="string")return new Re(`"${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 Re(`"${t}"`):new Re(`"${t}"^^${r}`)}function Xr(t){return new Ia(t)}function Sa(){return Pe}function it(t,e,r,s){return new $r(t,e,r,s)}function Ie(t){if(t instanceof ie)return t;switch(t.termType){case"NamedNode":return Br(t.value);case"BlankNode":return zr(t.value);case"Variable":return Xr(t.value);case"DefaultGraph":return Pe;case"Literal":return Mr(t.value,t.language||t.datatype);case"Quad":return qr(t);default:throw new Error(`Unexpected termType: ${t.termType}`)}}function qr(t){if(t instanceof $r)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 Gr{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&Wr(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 va({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,m)=>{u?h=u:m&&l.push(m)},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 Wr(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")}Wr(Gr.prototype,ya);async function Ra(t,e={}){const r=e.webId??t.info?.webId;if(!r?.trim()||typeof t.fetch!="function")return null;const s=Ea(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 ka(o,{contentType:i,profileDocumentUrl:s,webId:r});return Gt(r,c)}async function ka(t,e){return(e.contentType?.toLowerCase()??"").includes("application/ld+json")||t.trimStart().startsWith("{")?La(t,e.webId):await Pa(t,e)}async function Pa(t,e){const r=Gr,a=new r({baseIRI:e.profileDocumentUrl}).parse(t);return Ca(a,e.webId)}function La(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?Hr({id:e,name:ce(i,Q.fn),nick:ce(i,ur.nick),avatar:ce(i,Q.hasPhoto),note:ce(i,Q.note),email:ce(i,Q.hasEmail),phone:ce(i,Q.hasTelephone),region:ce(i,Q.region),gender:ce(i,Q.hasGender)}):null}catch{return null}}function Ca(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===ur.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 Hr(r)}function Gt(t,e){return{webId:t,profile:e,displayName:Rs(e),username:pa(t)}}function Hr(t){const e=Object.fromEntries(Object.entries(t).filter(([,r])=>typeof r=="string"&&r.trim()));return Object.keys(e).length>1?e:null}function ce(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 Ea(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(()=>Aa({displayName:i,username:o,id:c},s),[i,c,o,l,s]),m=`${s??""}\0${u.displayName}\0${u.username??""}`,[f,x]=d.useState(),[p,g]=d.useState(!1);d.useEffect(()=>{const S=h;if(r!=="authenticated"||!S||!s)return;let I=!1,b;async function j(R,k){g(!0);try{const y=await Ra({info:{webId:k},fetch:R});if(I||!y)return;const A=Ua(y.profile?.avatar);let N=A;if(A&&(N=await Ta(R,A),b=N?.startsWith("blob:")?N:void 0),I){b&&URL.revokeObjectURL(b);return}x({key:m,value:{displayName:y.displayName??y.username??u.displayName,username:y.username||u.username,avatarUrl:N??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{I||x(void 0)}finally{I||g(!1)}}return j(S,s),()=>{I=!0,b&&URL.revokeObjectURL(b)}},[h,u,m,r,s]);const v=r==="authenticated"?p:!1;return r==="authenticated"&&f?.key===m?{...f.value,loading:v}:{...u,loading:v}}function Aa(t,e){const r=t?.username||Da(e)||t?.id;return{displayName:t?.displayName||r||t?.id||"Xpod account",username:r,webId:e,loading:!1,source:"account"}}async function Ta(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 Ua(t){if(t)try{const e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"?e.href:void 0}catch{return}}function Da(t){if(t)try{const e=new URL(t);return e.pathname.split("/").filter(Boolean).at(0)||e.hostname}catch{return}}const Oa=d.createContext(null);function Fa({value:t,children:e}){return d.createElement(Oa.Provider,{value:t},e)}async function $a(t){const{Parser:e,Writer:r,DataFactory:s}=await ae(async()=>{const{Parser:_,Writer:C,DataFactory:$}=await import("./index-DgKn1twH.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-BUF9fin1.js").then($=>$.bw);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 m=u.headers.get("etag"),f=await u.text();if(!m||!/^"[^"\r\n]+"$/.test(m))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 x=new e({baseIRI:h}).parse(f),p=_=>x.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 g=p(a.status);if(g.length!==1||g[0].termType!=="Literal"||!["pending","handling"].includes(g[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),I=()=>p(a.expiresAt).some(_=>{const C=Date.parse(_.value);return!Number.isFinite(C)||C<=S().getTime()});if(I())return{status:"not_actionable",reason:"Approval has expired."};const b=p(a.leaseOwner),j=p(a.leaseExpiresAt);if((b.length||j.length)&&(b.length!==1||b[0].termType!=="Literal"||j.length!==1||j[0].termType!=="Literal"||!Number.isFinite(Date.parse(j[0].value))||Date.parse(j[0].value)>S().getTime()))return{status:"conflict",reason:"Approval is being handled by another client."};const R=new Set([a.status,a.decisionBy,a.resolvedAt]),k=x.filter(_=>_.subject.value!==l||!R.has(_.predicate.value)),y=s.namedNode(l);k.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(k),$.end((T,V)=>T?C(T):_(V))});if(t.isCurrent&&!t.isCurrent())return{status:"not_actionable",reason:"The current session changed."};if(I())return{status:"not_actionable",reason:"Approval has expired."};const N=await t.authenticatedFetch(h,{method:"PUT",headers:{"content-type":"text/turtle","if-match":m},body:A,redirect:"error"});if(await N.arrayBuffer(),N.status===412)return{status:"conflict",reason:"Another client changed the approval. Refresh before deciding again."};if(!N.ok)throw new Error(`Approval decision failed: HTTP ${N.status}`);return{status:"decided"}}const Le=ks;function Ba(){const t=xr(),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=Ps(t.idpIndex),c=t.isInitializing?void 0:vr(t.idpIndex),l=c?new URL(c).origin:void 0,h=l?hr(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&&!Ls(i,{accountIdentity:t.identity,accountEmail:h,webId:a,selectedStorage:r})||Cs({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:Es}))},[t.identity,l,o,u,h,s.displayName,s.avatarSourceUrl,s.username,i,e.currentPod,r,a]),null}const za=80,Ma=2048;function Xa(){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(()=>qa({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 qa({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 Ga(a)?" ":s}).join("").replace(/\s+/g," ").trim();if(r)return Array.from(r).slice(0,za).join("").trim()}function Ga(t){return t<32||t>=127&&t<=159||t>=8234&&t<=8238||t>=8294&&t<=8297}function Ht(t){if(!(!t||t.length>Ma))try{const e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"||e.username||e.password?void 0:e.toString()}catch{return}}function Wa({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 m=setTimeout(()=>u.abort(),5e3);let f=!0;try{const x=await fetch("/service/status",{cache:"no-store",signal:u.signal});if(f=x.status<500,x.ok){const p=await x.json().catch(()=>null);Array.isArray(p)&&(f=!p.some(g=>g&&["css","api"].includes(g.name)&&typeof g.status=="string"&&g.status!=="running")),u.signal.aborted&&(f=!1)}else await x.body?.cancel()}catch{f=!1}finally{clearTimeout(m),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 Ha(){const t=or();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 ke="/ai-connections",F={pod:"/pod/models",status:"/device/services",network:"/device/network",aiConnections:"/ai-connections"},Vr={"/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"},Xo=[...["/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 Va(t){return Vr[t.replace(/\/$/,"")]??t}const Qa="https://id.undefineds.co/app/xpod-desktop-client.json",Ka={client_id:Qa},Qr=1,Ja="xpod.auth.transaction.v1",Ya=600*1e3,Kr=1,xe="xpod.auth.selected-storage.v1",Za=1440*60*1e3;class E extends Error{code;constructor(e,r){super(r),this.name="XpodLoginTransactionError",this.code=e}}function qo(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=Zr(t,a,e.storageRoot===void 0),c=(e.now??(()=>Date.now()))(),l={version:Kr,createdAt:c,expiresAt:c+(e.ttlMs??Za),binding:i,...e.storageRoot===void 0?{}:{storageRoot:es(e.storageRoot)}};r.setItem(xe,JSON.stringify(l))}function ei(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(!ni(a)){s();return}const i=e.now??(()=>Date.now());if(a.expiresAt<=i()){s();return}let o;try{o=Zr(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 Jr(){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 ti(t={}){const e=t.storage??ai(),r=new URL(t.origin??jt()).origin,s=t.now??(()=>Date.now()),a=t.ttlMs??Ya,i=t.prefix??Ja,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,x=!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(x&&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 x&&e.getItem(o)===f&&e.removeItem(o),new E("unknown","Xpod login transaction was not found");let g;try{g=JSON.parse(p)}catch{throw h(f),new E("malformed","Xpod login transaction is malformed")}if(!si(g)||g.transaction.id!==f)throw h(f),new E("malformed","Xpod login transaction is malformed");if(g.expiresAt<=s())throw h(f),new E("expired","Xpod login transaction has expired");try{const v=Vt({...g.transaction,authorizationSurface:"redirect",discovery:"strict"},r);return g.transaction={id:v.id,route:v.route,...v.returnTo===void 0?{}:{returnTo:v.returnTo},...v.prompt===void 0?{}:{prompt:v.prompt},...v.selectedStorage===void 0?{}:{selectedStorage:v.selectedStorage}},g}catch(v){throw h(f),v instanceof E?v:new E("malformed","Xpod login transaction is malformed")}};return{begin:f=>{const x=e.getItem(o);if(x){try{u(x)}catch(b){if(!(b instanceof E&&(b.code==="expired"||b.code==="malformed"||b.code==="unknown")))throw b}if(e.getItem(o)===x)throw new E("already_active","An Xpod login transaction is already pending in this tab")}const p=Qt(f.id)?f.id:Jr(),g=Vt({...f,id:p},r),v=s(),S=v+a,I={version:Qr,createdAt:v,expiresAt:S,transaction:{id:g.id,route:g.route,...g.returnTo===void 0?{}:{returnTo:g.returnTo},...g.prompt===void 0?{}:{prompt:g.prompt},...g.selectedStorage===void 0?{}:{selectedStorage:g.selectedStorage}}};return e.setItem(c(g.id),JSON.stringify(I)),e.setItem(o,g.id),g},readSinglePending(){const f=e.getItem(o);if(f)return Ve(u(f).transaction)},updateSelectedStorage(f,x){const p=u(f),g=Ve(p.transaction),v=Yr(x,r,g.route.storageProvider?.url),S={...p,transaction:{...p.transaction,selectedStorage:v}};e.setItem(c(f),JSON.stringify(S))},consume(f){const x=u(f),p=Ve(x.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=As(t)}catch(i){throw new E("malformed",i instanceof Error?i.message:"Transaction is malformed")}let s;try{s=Ts(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=Yr(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 Yr(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 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(!ri(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 es(t){const e=new URL(t);return e.hash="",e.search="",e.pathname.endsWith("/")||(e.pathname+="/"),e.href}function ri(t,e){const r=new URL(es(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 si(t){if(!t||typeof t!="object")return!1;const e=t;return e.version===Qr&&typeof e.createdAt=="number"&&typeof e.expiresAt=="number"&&!!(e.transaction&&typeof e.transaction=="object")}function ni(t){if(!t||typeof t!="object")return!1;const e=t;return e.version===Kr&&typeof e.createdAt=="number"&&typeof e.expiresAt=="number"&&!!(e.binding&&typeof e.binding=="object")}function ai(){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 ii({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 m=await u.json();if(e(),typeof m.id!="string"||!m.id||m.id.includes(":")||typeof m.secret!="string"||!m.secret||typeof m.resource!="string"||!m.resource)throw new Error("账号服务未返回有效的客户端凭据。");const f=await o(m.resource),x=new TextEncoder().encode(`${m.id}:${m.secret}`),p=btoa(Array.from(x,g=>String.fromCharCode(g)).join(""));return e(),{apiKey:`sk-${p}`,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??{}),m=await Promise.all(u.map(async([f,x])=>({clientId:f,label:f,resource:await o(String(x))})));return e(),m},async revoke({clientId:l,resource:h,webId:u}){const m=await o(h),f=JSON.stringify([m,l,u]),x=await c(m,"GET");if(x.status===404||x.status===410){if(i.has(f))return;throw new Error("无法确认客户端凭据已撤销,请检查当前 Account 登录;Key 记录已保留。")}if(!x.ok)throw new Error(`读取客户端凭据失败(HTTP ${x.status})。`);const p=await x.json();if(e(),p.id!==l||p.webId!==u)throw new Error("客户端凭据与当前 Key 或 WebID 不匹配,未执行删除。");const g=await c(m,"DELETE");if(!g.ok)throw new Error(`撤销客户端凭据失败(HTTP ${g.status})。`);i.add(f)}}}class ee extends Error{code;constructor(e,r){super(r),this.name="AccountStorageBindingsError",this.code=e}}async function oi(t){const e=li(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=di(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 ci(l,a.origin,fi(a,t.trustedAccountIndex,e))}function ci(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=ui(i.webId),c=hi(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 li(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 di(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 ui(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 hi(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 fi(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 pi(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){return e?async(a,i)=>{const o=a instanceof Request?mi(a):a,c=await t(a,i);if(!o||!bi(a,s)||c.status!==403||!await gi(c))return c;const l=await e().catch(()=>{});if(!l)return c;const h=new Headers(i?.headers??(a instanceof Request?a.headers:void 0));return h.set("authorization",l),h.delete("dpop"),r(o,{...i,headers:h})}:t}function mi(t){try{return t.clone()}catch{return}}async function gi(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 bi(t,e){if(!e)return!1;try{const r=new URL(t instanceof Request?t.url:String(t),e);return r.origin===new URL(e).origin&&(r.pathname.startsWith("/api/")||r.pathname.startsWith("/v1/"))}catch{return!1}}async function xi(t){if(!t.accountIndex||!t.webId)return;t.assertCurrent(t.webId);const e=t.binding??await vi(t)??await _i(t);if(t.assertCurrent(t.webId),!(!e||e.webId!==t.webId))return e.assertCurrent(),ii({collection:e.collection,assertCurrent:()=>{t.assertCurrent(t.webId),e.assertCurrent()},accountIndex:t.accountIndex,...e.fetch?{fetch:e.fetch}:{}})}async function vi(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 oi({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 _i(t){if(!t.sessionFetch)return;const e=t.webId,r=Zs({accountIndex:t.accountIndex,fetch:t.sessionFetch,assertCurrent:()=>t.assertCurrent(e)}),s=await en({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 wi({children:t,value:e}){const r=e??Us(),s=d.useMemo(()=>r.storage??{},[r]),a=d.useMemo(()=>ji(r),[r]),[i,o]=d.useState(a.snapshot),[c,l]=d.useState(a.issuer),[h,u]=d.useState(),[m,f]=d.useState(),[x,p]=d.useState(),[g,v]=d.useState(0),[S,I]=d.useState(),b=d.useRef(i),j=d.useRef(a.rejected),R=d.useRef(void 0),k=d.useCallback(async(w,P)=>j.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||j.current)throw Zt;return P===void 0?y(w):y(w,P)},[y]),N=d.useCallback(()=>{if(R.current)return R.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))&&(j.current=!1)}catch{}finally{const P={status:"anonymous"};r.pod.clear(),He({storage:s.selectedStorage}),Pt(s.issuer),r.setIssuer(void 0),b.current=P,o(P),l(void 0),u(void 0),f(void 0),p(void 0),I(void 0)}})().finally(()=>{R.current===w&&(R.current=void 0)});return R.current=w,w},[r,s.issuer,s.selectedStorage]),_=d.useContext(bt),C=_?.idpIndex,$=_?.registerAccountSession;d.useLayoutEffect(()=>{if(!(!$||i.status!=="authenticated"||!c||j.current))return $({issuer:c,fetch:A,assertCurrent:()=>{if(j.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 pi({webId:T,resolveCapability:()=>xi({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 W=d.useCallback((w,P)=>Yt(A,()=>z.authorization(),ye,window.location.origin)(w,P),[A,z]),re=d.useCallback((w,P)=>Yt(k,()=>z.authorization(),ye,window.location.origin)(w,P),[k,z]),se=d.useMemo(()=>({...r.session,fetch:re,getSnapshot:()=>b.current}),[re,r.session]);d.useEffect(()=>{const w=L=>{const X=r.getIssuer();if(!tt(L,X,r.getExpectedIssuer?.()??window.location.origin)){j.current=!0,N();return}L.status==="authenticated"&&(j.current=!1);const U=b.current;b.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),I(void 0),r.pod.clear()):U!==L&&(u(void 0),f(void 0),p(void 0),I(void 0),r.pod.clear(U.status==="authenticated"?{webId:U.webId}:void 0))},P=r.session.subscribe(w);return w(r.session.getSnapshot()),P},[N,r,s]),d.useEffect(()=>{j.current&&N()},[N]),d.useEffect(()=>{if(i.status!=="authenticated")return;let w=!1;const P=new AbortController,L=ei({storage:s.selectedStorage,origin:typeof window>"u"?void 0:window.location.origin,webId:i.webId}),X={webId:i.webId,...L?{podUrl:L.storageUrl}:{},fetch:W};return(async()=>{try{const U=r.getProvisionRouteStatus?.()??await Ds(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 Os(q.podUrl,fetch,{signal:P.signal});w||r.setLocalPodRoutes?.(O)}),!w){if(L&&(q.webId!==L.webId||!Ii(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)}},[W,g,r,s.selectedStorage,i]);const le=d.useCallback(()=>{p(void 0),v(w=>w+1)},[]),D=i.status==="authenticated"?i.webId:void 0;d.useEffect(()=>{if(!D)return;let w=!1;return Ni(A).then(P=>{!w&&r.session.getSnapshot().status==="authenticated"&&r.session.getSnapshot().webId===D&&I(P)}),()=>{w=!0}},[A,D,r]);const ne=d.useMemo(()=>{const w=c??r.getIssuer(),P=i.status==="authenticated"&&x?.webId===i.webId?x:void 0,L=Fs(i,h,w);return{session:se,pod:r.pod,fetch:W,transportFetch:r.transportFetch??ye,state:L.status==="error"?{...L,error:Ms(L.error)}:L,webId:L.webId,podUrl:L.podUrl,issuer:L.issuer,currentPod:h,selectedStorage:m,...P?{podError:P}:{},retryPodOpen:le,aiClientConfiguration:S,resolveLocalUrl:X=>r.resolveLocalUrl(X),requestPodAuthorization:()=>z.authorization(),requestPodApiKey:()=>z.apiKey(),login:async X=>{const U=$s(X),q=await Bs(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),fe=globalThis.xpodDesktop?Ka.client_id:void 0;try{await r.session.login({...fe?{clientId:fe}:{},oidcIssuer:Y,redirectUrl:O.toString(),handleRedirect:oe=>{r.setIssuer(Y),l(Y);const ve=new URL(oe);U.prompt?ve.searchParams.set("prompt",U.prompt):fe&&ve.searchParams.get("prompt")==="consent"&&ve.searchParams.delete("prompt"),window.location.assign(q.provisionCode?zs(ve.href,q.provisionCode):ve.href)}}),r.setIssuer(Y),l(Y)}catch(oe){throw console.error("[XpodSolidRuntimeProvider] WebID login failed",oe,oe instanceof Error?oe.cause:void 0),oe}},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),I(void 0)}}},[S,W,h,se,c,x,z,le,r,s,m,i]);return n.jsx(Fa,{value:{session:se,pod:r.pod,currentPod:h},children:n.jsx(fr.Provider,{value:ne,children:t})})}const yi={status:"anonymous"},Zt=new Error("Xpod session is unavailable"),ye=(t,e)=>globalThis.fetch(t,e);function ji(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:yi,issuer:void 0,rejected:!0}}function Ii(t,e){try{return new URL(t).href===new URL(e).href}catch{return t===e}}async function Ni(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(Si(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 Si(t){return!!(t&&typeof t=="object"&&!Array.isArray(t))}function Ri({children:t}){return d.useContext(us)?n.jsx(n.Fragment,{children:t}):n.jsx(hs,{children:t})}function ki(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 ts=d.createContext(null);function rs(){return d.useContext(ts)}function Ce(){const t=rs();if(!t)throw new Error("ShellStateProvider is required");return t}async function Pi({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 Li(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 Ci(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 ss(t,e){return!!(t.thread&&t.toolCallId&&t.thread===e.thread&&t.toolCallId===Ci(e))}function lt(t,e){return e.status==="waiting_input"&&ss(t,e)}function Ei(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 Ai({approvals:t,inbox:e,runs:r,tasks:s}){const a=new Set(["completed","failed","cancelled"]),i=t.filter(o=>{if(!Li(o))return!1;const c=r.filter(l=>ss(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:Ei(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)&<(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 Ti(t){return{...t,activity:t.activity.map(e=>({...e,read:!0}))}}async function Ui(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 Ai({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 Di(t,e,r,s,a=()=>!0){const i=await $a({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 Oi({children:t}){const e=Le();return n.jsx(Fi,{runtime:e,children:t},`${e.state.status}|${e.webId||""}|${e.currentPod?.podUrl||""}`)}function Fi({children:t,runtime:e}){const r=d.useMemo(()=>ki({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([]),m=d.useRef(new Set),[f,x]=d.useState(0),p=d.useRef(new Set),g=d.useRef(!0),v=d.useCallback(()=>x(b=>b+1),[]);d.useEffect(()=>(g.current=!0,()=>{g.current=!1}),[]),d.useEffect(()=>{let b=!0,j=!1;async function R(){if(!j){j=!0,o(!0);try{const[y,A,N]=await Promise.allSettled([e.state.status==="authenticated"&&e.currentPod?Ui(e.currentPod.database):Promise.resolve(De()),sn(),e.state.status==="authenticated"&&e.webId&&e.currentPod?Pi({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"}),N.status==="fulfilled"&&N.value?.storage.status==="available"){const C=N.value.storage;C.limits.storageLimitBytes&&C.usage.storageBytes/C.limits.storageLimitBytes>=.8&&_.attention.push({id:"pod:storage",kind:"quota",title:"Pod 空间快到上限",href:"/pod/data"})}b&&(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{b&&l("通知读取失败,请重试")}finally{j=!1,b&&o(!1)}}}R();const k=window.setInterval(()=>{R()},3e4);return window.addEventListener("focus",v),window.addEventListener("xpod:pod-changed",v),()=>{b=!1,window.clearInterval(k),window.removeEventListener("focus",v),window.removeEventListener("xpod:pod-changed",v)}},[e.currentPod,e.webId,e.fetch,e.state.status,f,v]),d.useEffect(()=>{globalThis.xpodDesktop?.publishAttention?.(s)},[s]),d.useEffect(()=>()=>{globalThis.xpodDesktop?.publishAttention?.(De())},[]);const S=d.useCallback(async(b,j)=>{if(!(!g.current||m.current.has(b))){m.current.add(b),u(R=>R.map(k=>k.approvalId===b?{...k,busy:!0}:k));try{await r.resumeRun(j,b),g.current&&(u(R=>R.filter(k=>k.approvalId!==b)),v())}catch{g.current&&u(R=>[...R.filter(k=>k.approvalId!==b),{approvalId:b,run:j,message:"决定已保存,运行处理失败,请重试。"}])}finally{m.current.delete(b)}}},[r,v]),I=d.useCallback(async(b,j)=>{if(e.state.status!=="authenticated"||!e.currentPod||!e.webId)throw new Error("请先登录并打开 Pod。");const R=s.attention.find(k=>k.approvalId===b)?.run;await Di(e.fetch,b,e.webId,j,()=>g.current),g.current&&(a(k=>({...k,attention:k.attention.filter(y=>y.approvalId!==b),inbox:k.inbox.map(y=>y.approvalId===b?{...y,approvalId:void 0}:y)})),R&&await S(b,R),v())},[e.currentPod,e.webId,e.fetch,e.state.status,s.attention,S,v]);return d.useEffect(()=>globalThis.xpodDesktop?.onApprovalDecision?.(({approvalId:b,decision:j})=>{I(b,j).catch(R=>{g.current&&l(R instanceof Error?R.message:"决定保存失败,请重试")})}),[I]),n.jsx(ts.Provider,{value:{snapshot:s,loading:i,error:c,refresh:v,decide:I,resumeFailures:h,retryResume:S,markAllRead(){s.activity.forEach(b=>p.current.add(b.id)),a(Ti)}},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 ns({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(Ir,{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 as(){const{snapshot:t}=Ce(),[e]=fs(),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(ns,{}),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 is({close:t=()=>{}}){const{snapshot:e,markAllRead:r}=Ce();return n.jsxs("div",{className:"space-y-5",children:[n.jsx(ns,{}),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 $i(){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(m){m.key==="Escape"&&(i(null),l.current?.focus())}function u(m){o.current?.contains(m.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(Cr,{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($n,{size:16}):n.jsx(Hn,{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(Er,{size:16})})]}),r&&n.jsx(Ir,{tone:"destructive",role:"alert",className:"mb-3",action:n.jsx("button",{onClick:s,className:"underline",children:"重试"}),children:r}),a==="notifications"?n.jsx(is,{close:()=>i(null)}):n.jsx(as,{})]})]})}const Bi=d.lazy(()=>ae(()=>import("./PodPage-C4gzEspV.js"),__vite__mapDeps([10,1,2,3,4,5,6,7,11,12,13,8,9]))),zi=[{path:"/device/network",label:"网络访问"},{path:"/device/services",label:"服务状态"},{path:"/device/runtime",label:"运行设置"},{path:"/device/logs",label:"查看日志"}],Mi=[{path:"/pod/models",label:"模型设置"},{path:"/pod/search",label:"检索与索引"},{path:"/pod/apps",label:"授权应用"},{path:"/pod/data",label:"数据管理"}],Xi=[{path:"/settings/appearance",label:"外观"}];function qi({items:t,query:e,label:r}){const{openMain:s}=nn();return n.jsx("nav",{"aria-label":r,className:"p-2",children:t.filter(a=>a.label.includes(e.trim())).map(a=>n.jsx(ms,{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"?zi:t==="pod"?Mi:Xi,[s,a]=d.useState(""),i=r.find(c=>c.path===e.pathname)??r[0],o=t==="device"?"这台设备":t==="pod"?"Pod":"设置";return n.jsx(_r,{mode:"auto",listHeader:n.jsx("div",{className:"flex h-full min-w-0 items-center px-3",children:n.jsx(jr,{"aria-label":"搜索页面",value:s,onChange:c=>a(c.target.value)})}),list:n.jsx(qi,{items:r,query:s,label:o}),mainHeader:n.jsx(os,{title:i.label}),main:n.jsx(ht,{})})}function os({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($i,{})]})]})}function tr({title:t,children:e}){return n.jsx(_r,{className:"workspace-page",pageType:"collection",hasObjectCollection:!1,listHeader:null,list:null,mainHeader:n.jsx(os,{title:t}),main:n.jsx("div",{className:"p-6",children:e})})}function Gi({section:t}){const e=or(),r=Le(),s=r.issuer?new URL("/.account/account/",r.issuer).toString():void 0;return n.jsx(br,{children:n.jsx(Bi,{section:t,onSection:a=>e(`/pod/${a}`),accountUrl:s})})}function Wi(){const t=ps();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(yr,{"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:ca},{id:"ai",label:"AI 连接",labelEn:"AI connections",href:"/ai-connections",activePaths:["/ai-connections"],icon:ia},{id:"pod",label:"Pod",labelEn:"Pod",href:"/pod/models",activePaths:["/pod"],icon:wr},{id:"device",label:"这台设备",labelEn:"This device",href:"/device/network",activePaths:["/device"],icon:ta},{id:"settings",label:"设置",labelEn:"Settings",href:"/settings/appearance",activePaths:["/settings"],icon:na}];function cs(t,e){const r=e.replace(/\/+$/,"")||"/";return t.activePaths.some(s=>r===s||r.startsWith(`${s}/`))}function Hi(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 Vi(){const t=xr(),e=d.useContext(fr),r=t.isLoggedIn&&t.accountState.status==="authenticated",s=e?.state.status==="authenticated"&&!!(e.webId??e.state.webId),a=r||s,[i,o]=d.useState(to(a)),[c,l]=d.useState(),[h,u]=d.useState(),[m,f]=d.useState(),x=d.useRef(null),p=d.useRef(null),g=d.useRef(void 0),v=d.useId(),S=t.identity,I=vr(t.idpIndex),b=!t.isInitializing&&I?new URL(I).origin:void 0,j=b?hr(void 0,t.idpIndex):void 0,R=Be(),k=tn(t.controls,S),y=b&&R?.issuer===b&&k&&R.account.id===k?R.account:void 0,A=r?Qi(S,j,y):void 0,N=_t({accountIdentity:A,runtime:s?e:void 0}),_=N.displayName,C=Ji(N.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?Yi(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,W=d.useCallback(D=>{o(D),D||(f(void 0),sr())},[]);d.useLayoutEffect(()=>{if(!B)return;const D=()=>{const ne=p.current;ne&&f(Hi(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&&(x.current?.contains(P)||p.current?.contains(P)||W(!1))},ne=w=>{w.key==="Escape"&&(W(!1),p.current?.focus())};return document.addEventListener("pointerdown",D),document.addEventListener("keydown",ne),()=>{document.removeEventListener("pointerdown",D),document.removeEventListener("keydown",ne)}},[z,B,W]),d.useEffect(()=>{!B||!m||x.current?.focus({preventScroll:!0})},[B,m]),d.useEffect(()=>()=>{g.current!==void 0&&window.clearTimeout(g.current)},[]);const re=async()=>{l("logout"),W(!1);try{await at(t,e),(t.isAnonymous?.()??!0)&&W(!1)}catch{}finally{l(void 0)}},se=async()=>{l("switch"),W(!1);try{await at(t,e,{onComplete:()=>{pr();const D=new URL(ke,window.location.origin);D.searchParams.set("xpod-login","switch"),window.location.assign(D)}}),W(!1)}catch{}finally{l(void 0)}},le=async()=>{const D=N.webId??$;if(D){try{await navigator.clipboard.writeText(D),u("已复制")}catch{u("复制失败")}g.current!==void 0&&window.clearTimeout(g.current),g.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?v: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:()=>W(!B),children:[n.jsxs(Ut,{className:"h-8 w-8 rounded-md border border-border bg-muted",children:[N.avatarUrl?n.jsx(Dt,{src:N.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"?Js.createPortal(n.jsx("section",{ref:x,id:v,role:"region",tabIndex:-1,"aria-label":a?_:"Xpod account","data-avatar-card":"true","data-selected-pod-url":T,style:m,className:`fixed z-50 overflow-y-auto rounded-xl border border-border/40 bg-card text-card-foreground shadow-xl shadow-black/10 ${m?"":"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:[N.avatarUrl?n.jsx(Dt,{src:N.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:N.webId??$}),n.jsx(pe,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0 text-muted-foreground","aria-label":"复制 WebID",onClick:()=>{le()},children:n.jsx(Gn,{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(xn,{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 已登录"})]})]}),N.note||N.region?n.jsxs("div",{className:"px-6 pb-5 text-sm text-muted-foreground",children:[N.note?n.jsx("p",{className:"line-clamp-2 text-foreground/85",children:N.note}):null,N.region?n.jsx("p",{className:"mt-1 text-xs",children:N.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(wr,{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:Zi(te)}),n.jsxs("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground",children:[eo(T)," · ",J?"已就绪":"尚未就绪"]})]}),J?n.jsx(Xn,{className:"h-4 w-4 shrink-0 text-success","aria-label":"Pod 已就绪"}):n.jsx(zn,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"})]})})}),n.jsx(kr,{}),n.jsxs("div",{className:"p-2",children:[I?n.jsx(pe,{asChild:!0,variant:"ghost",className:"h-10 w-full justify-start px-3 font-normal",children:n.jsxs("a",{href:I,children:[n.jsx(da,{className:"mr-2 h-4 w-4","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(Cr,{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(Jn,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"退出"]})]})]})}),document.body):null]}):n.jsx("a",{href:ke,"aria-label":"登录",title:"登录",className:"flex h-9 w-9 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent",children:n.jsx(Qn,{size:20,"aria-hidden":"true"})})}function Qi(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||Ki(s);return{...r??{},...t??{},...a?{username:a}:{},...r?.displayName?{displayName:r.displayName}:{displayName:a||s||"Xpod account"}}}function Ki(t){if(t)return t.split("@")[0]?.trim()||void 0}function Ji(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 Yi(t){try{return new URL(t).pathname.split("/").filter(Boolean).at(-1)}catch{return}}function Zi(t){return t?`${t} Pod`:"我的 Pod"}function eo(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 to(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?cs(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:on,className:Hs(cn(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 ro({product:t}){const e=$e(),s=rs()?.snapshot.attention.some(g=>g.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(g=>cs(g,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 g=()=>{window.innerWidth>=768&&i(v=>({...v,open:!1}))};return window.addEventListener("resize",g),()=>window.removeEventListener("resize",g)},[]),d.useEffect(()=>{if(!o)return;const g=v=>{if(v.key==="Escape"&&(i(j=>({...j,open:!1})),c.current?.focus()),v.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(j=>j.getClientRects().length&&!j.hasAttribute("disabled")),I=S[0],b=S.at(-1);v.shiftKey&&document.activeElement===I?(v.preventDefault(),b?.focus()):!v.shiftKey&&document.activeElement===b&&(v.preventDefault(),I?.focus())};return document.addEventListener("keydown",g),h.current?.querySelector("[data-drawer-close]")?.focus(),()=>document.removeEventListener("keydown",g)},[o]);const x=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(Zn,{"aria-hidden":"true",size:20})}),p=n.jsxs(n.Fragment,{children:[x,n.jsxs("span",{className:"xpod-header-parent",children:[u?.label??"Xpod"," ›"]})]});return n.jsx(an.Provider,{value:{open:o,onClose:()=>i(g=>({...g,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:[x,n.jsxs("span",{children:[u?.label??"Xpod",f?` › ${f}`:""]})]}),o?n.jsx("button",{className:"xpod-drawer-backdrop","aria-label":"关闭导航",onClick:()=>{i(g=>({...g,open:!1})),c.current?.focus()}}):null,n.jsxs("aside",{className:"xpod-rail","data-app-layout-navigation":!0,"aria-label":"Xpod 工作区导航",onClick:g=>{g.target.closest("a")&&i(v=>({...v,open:!1}))},children:[n.jsx("div",{className:"xpod-rail-profile",children:n.jsx(Vi,{})}),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(g=>({...g,open:!1})),c.current?.focus()},children:n.jsx(Er,{size:18})}):null,n.jsx("div",{className:"xpod-shell-content","data-app-layout-content":!0,children:n.jsx(ht,{})})]})})}function so({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 no(){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 ls(t){const e=new URL(window.location.href);return e.searchParams.get("xpod-login")!==t?!1:(Se(!0),no(),e.searchParams.delete("xpod-login"),window.history.replaceState(window.history.state,"",`${e.pathname}${e.search}${e.hash}`),!0)}function ao(){return new URL(window.location.href).searchParams.get("xpod-login")==="switch"}function io(){return ls("switch")}function oo(){if(ls("cancelled"))return!0;try{return window.localStorage.getItem(ut)==="1"}catch{return!1}}function co(t){const e=t.location??(typeof window>"u"?"http://localhost/":window.location),s=[Xs(e)],a=lo(e),i=t.transactionStore??ti({origin:a}),o=u=>{if(u!==void 0)return et(u);const m=new URL(ds(e)),f=`${m.pathname}${m.search}`;try{return et(f)}catch{return}};let c=!1;const l=u=>{try{return i.begin(u)}catch(m){if(c||!(m instanceof E)||m.code!=="already_active")throw m;try{const f=i.readSinglePending();f&&i.cancel(f.id)}catch{}return i.begin(u)}},h=async(u,m,f)=>{const x=o(u),p={id:Jr(),route:s[0],authorizationSurface:"redirect",discovery:"strict",...f?{prompt:f}:{},...x===void 0?{}:{returnTo:x},...m===void 0?{}:{selectedStorage:m}},g=l(p);c=!0;try{await t.runtime.login(g)}catch(v){try{i.cancel(g.id)}catch{}throw v}finally{c=!1}return g};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 lo(t){return new URL(ds(t)).origin}function ds(t){return typeof t=="string"?t:t.href}function uo(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=lr("zh-CN"),ho={name:"Xpod",icon:n.jsx(pt,{size:24})},fo="无法打开选中的 Pod,请重试。",po="操作未完成,请重试。";function mo(t){return n.jsx(Or,{children:n.jsx(go,{...t})})}function go({children:t,autoStart:e=!1,developerMode:r=!1}){const s=Le(),a=d.useContext(bt),i=d.useSyncExternalStore(Ur,fa,()=>!1),o=d.useMemo(()=>co({runtime:s}),[s]),[c]=d.useState(ao),[l,h]=d.useState(()=>c||oo());d.useLayoutEffect(()=>{c&&io()},[c]),d.useEffect(()=>{if(l)try{o.cancelLogin()}catch{}},[l,o]);const u=vo(s.state),m=xo(s,u),f="remembered"in u?u.remembered:void 0,x=f?bo(f):void 0,[p,g]=d.useState(f&&x?{signature:x,identity:f}:void 0);x!==void 0&&x!==p?.signature&&g({signature:x,identity:f});const v=u.status==="authenticated"&&m?.status==="ready",[S,I]=d.useState(),[b,j]=d.useState(!1),[R,k]=d.useState(!1),[y,A]=d.useState(c?{prompt:"login"}:void 0),N=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),I(po)},[]),K=d.useCallback(O=>{const fe=++N.current;I(void 0),j(!0),O().catch(oe=>{fe===N.current&&V(oe)}).finally(()=>{fe===N.current&&j(!1)})},[V]),te=d.useCallback(()=>{Se(!1),h(!1),I(void 0),A({})},[]),J=d.useCallback(()=>{k(!0),te()},[te]),z=d.useCallback(()=>{if(!y)return;const O=y.prompt;Se(!1),h(!1),A(void 0),K(async()=>{c&&await s.session.initialize({restorePreviousSession:!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()},W=()=>{if(!_){try{o.cancelLogin()}catch{}Se(!0),h(!0),A(void 0),N.current+=1,j(!1),I(void 0)}},re=()=>K(async()=>{k(!0),C(!0);const O=()=>{Se(!1),h(!1),pr(),I(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||b||_||!e||T.current||u.status!=="anonymous"||(T.current=!0,te())},[l,i,e,b,y,te,u.status,_]),v&&!b&&!S)return n.jsx(n.Fragment,{children:t});const se=f,le=u.status==="restoring",D=!!globalThis.xpodDesktop&&e&&!R&&!l&&!c&&!_&&!i&&!S&&(le||u.status==="anonymous"),ne=b||!!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(le)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:On(u.webId),webId:u.webId});m?.status==="conflict"?(L={kind:"remembered",identity:O},X={tone:"warning",text:G.noticeIncomplete,primaryLabel:G.useAnother,developerDetail:m.message},U=re):m?.status==="error"?(L={kind:"remembered",identity:O},X={tone:"warning",text:G.noticeUnreachable,primaryLabel:G.retry,developerDetail:m.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(qs,{ariaLabel:"登录 Xpod",children:[y?n.jsx(so,{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(Dn,{app:ho,brand:n.jsx(Gs,{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:W,children:G.cancel}):null]})}function Oe(t){const e=Be(),r=e&&(!t.webId||e.webId===t.webId)?e.storageBinding.storageUrl:void 0,s=uo(r);return{displayName:t.displayName,...t.avatarUrl?{avatarUrl:t.avatarUrl}:{},...r?{storage:{kind:s,label:s==="cloud"?G.storageCloud:G.storageEdge}}:{}}}function bo(t){return[t.routeId,t.webId??"",t.displayName,t.avatarUrl??""].join("\0")}function xo(t,e){if(e.status!=="authenticated")return;if(t.podError?.webId===e.webId)return{status:"error",message:fo};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&&ir(r.storageUrl,t.currentPod.podUrl)&&(s===void 0||ir(t.currentPod.podUrl,s))?{status:"ready",selected:r}:{status:"conflict",message:"当前 WebID 已登录,但选中的 Pod 与该身份不一致。"}}function ir(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 vo(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 _o=d.lazy(()=>ae(()=>import("./ModelsPage-Be2TPd-x.js").then(t=>t.M),__vite__mapDeps([14,1,2,9,4,5,11,3,6,7,15,12,16]))),wo=d.lazy(()=>ae(()=>import("./DevicePages-HjclpIVm.js"),__vite__mapDeps([17,1,2,9,4,5,18,6,12,15,13,3,7,8])).then(t=>({default:t.DeviceNetworkPage}))),yo=d.lazy(()=>ae(()=>import("./DevicePages-HjclpIVm.js"),__vite__mapDeps([17,1,2,9,4,5,18,6,12,15,13,3,7,8])).then(t=>({default:t.DeviceServicesPage}))),jo=d.lazy(()=>ae(()=>import("./DevicePages-HjclpIVm.js"),__vite__mapDeps([17,1,2,9,4,5,18,6,12,15,13,3,7,8])).then(t=>({default:t.DeviceRuntimePage}))),Io=d.lazy(()=>ae(()=>import("./DevicePages-HjclpIVm.js"),__vite__mapDeps([17,1,2,9,4,5,18,6,12,15,13,3,7,8])).then(t=>({default:t.DeviceLogsPage}))),No=d.lazy(()=>ae(()=>import("./TasksPage-BdO5K2L7.js"),__vite__mapDeps([19,1,2,3,4,5,6,7,9,8,20]))),ge=t=>n.jsx(br,{children:t}),So=[{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(wo,{}))},{path:"services",element:ge(n.jsx(yo,{}))},{path:"runtime",element:ge(n.jsx(jo,{}))},{path:"logs",element:ge(n.jsx(Io,{}))}]},{path:"settings",element:n.jsx(dt,{subject:"settings"}),children:[{index:!0,element:n.jsx(be,{to:"appearance",replace:!0})},{path:"appearance",element:n.jsx(Wi,{})}]}],Ro=[{element:n.jsx(mo,{autoStart:!0,children:n.jsx(ht,{})}),children:[{path:"ai-connections",element:ge(n.jsx(_o,{}))},{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(Gi,{section:t})}))]},{path:"tasks",element:ge(n.jsx(No,{}))},{path:"inbox",element:n.jsx(tr,{title:"收件箱",children:n.jsx(as,{})})},{path:"notifications",element:n.jsx(tr,{title:"通知",children:n.jsx(is,{})})}]}],ko=[{element:n.jsx(ro,{product:"settings"}),children:[...So,...Ro,...Object.entries(Vr).map(([t,e])=>({path:t.slice(1),element:t==="/settings/pod"?n.jsx(Ys,{to:e}):n.jsx(be,{to:e,replace:!0})})),{index:!0,element:n.jsx(be,{to:ke,replace:!0})},{path:"*",element:n.jsx(be,{to:ke,replace:!0})}]}];function Po(){const t=$e(),e=bs(ko);return d.useEffect(()=>{document.title="Xpod"},[t.pathname]),e}function Lo({runtime:t,initialPathname:e}={}){const[r]=d.useState(()=>Co(e));return n.jsx(Ri,{children:n.jsx(rn,{children:n.jsxs(wi,{value:t,children:[n.jsx(Xa,{}),n.jsx(Ba,{}),n.jsxs(gs,{children:[n.jsx(Ha,{}),n.jsx(Wa,{children:n.jsx(Oi,{children:n.jsx(Or,{children:n.jsx(Po,{})})})}),n.jsx(En,{})]},r)]})})})}function Co(t){const r=`${Va(t??globalThis.location?.pathname??ke)}${globalThis.location?.search??""}${globalThis.location?.hash??""}`;return`${globalThis.location?.pathname??""}${globalThis.location?.search??""}${globalThis.location?.hash??""}`!==r&&globalThis.history?.replaceState(null,"",r),r}const Go=Object.freeze(Object.defineProperty({__proto__:null,XpodShellApp:Lo},Symbol.toStringTag,{value:"Module"}));export{er as A,ja as B,zn as C,ya as D,Go as E,Ir as I,Re as L,Gr as N,$r as Q,Cr as R,jr as S,ie as T,Ia as V,ke as X,He as a,Lo as b,ti as c,Na as d,va as e,Fr as f,yr as g,Ce as h,ki as i,ns as j,$i as k,Pi as l,Gn as m,Z as n,vt as o,Xo as p,zo as q,qo as r,Se as s,Mo as t,Le as u,Bo as v,Ln as w,En as x,co as y,ii as z};
|